问:
How would I solve a "Cannot implicitly convert type 'System.Threading.Tasks.Task<string>'to 'string'" error in this example?
I have been experimenting with async and Cli wrap to try and make a network scanner. It involves taking data from a powershell command, storing it in an object and then displaying it in a WPF gui. But every time i try to construct it i get this error.

I have messed around with it trying to not run it asynchronusly but have found no possible way what with Cli wrap. I have also tried adding await to parts of it but that has just caused more errors as you would expect. Any help would be much appreciated, thank you. Here is my code so far:

```<code>
        //method to return ARP data
        static async Task<string> ArpData()
        {
            var powerShellResults = await Cli.Wrap("powershell")
                .WithArguments("arp -a")
                .ExecuteBufferedAsync();
            return powerShellResults.StandardOutput;
        }
        //time of snapshot, to be given when taken
        public int time;
        public string data = ArpData();

    }
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
</code>```

Body:
I have been experimenting with async and Cli wrap to try and make a network scanner. It involves taking data from a powershell command, storing it in an object and then displaying it in a WPF gui. But every time i try to construct it i get this error.

I have messed around with it trying to not run it asynchronusly but have found no possible way what with Cli wrap. I have also tried adding await to parts of it but that has just caused more errors as you would expect. Any help would be much appreciated, thank you. Here is my code so far:

        //method to return ARP data
        static async Task<string> ArpData()
        {
            var powerShellResults = await Cli.Wrap("powershell")
                .WithArguments("arp -a")
                .ExecuteBufferedAsync();
            return powerShellResults.StandardOutput;
        }
        //time of snapshot, to be given when taken
        public int time;
        public string data = ArpData();

    }
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }


来源: stackexchange

问:
Python - Please find the error in this combination function?
```<code>def factorial(n):
    return 1 if (n==1 or n==0) else n * factorial(n - 1)

def perm(n, r):
    nFactorial = factorial(n)
    midValue = n - r
    midFactorial = factorial(midValue)
    answer = nFactorial / midFactorial
    return answer

def comb(n, r):
    perm = perm(n, r)
    rFactorial = factorial(r)
    answer = perm / rFactorial
    return answer

</code>```

The error message says "UnboundLocalError: local variable 'perm' referenced before assignment".

ContentLicense: CC BY-SA 4.0

Body:
def factorial(n):
    return 1 if (n==1 or n==0) else n * factorial(n - 1)

def perm(n, r):
    nFactorial = factorial(n)
    midValue = n - r
    midFactorial = factorial(midValue)
    answer = nFactorial / midFactorial
    return answer

def comb(n, r):
    perm = perm(n, r)
    rFactorial = factorial(r)
    answer = perm / rFactorial
    return answer

The error message says "UnboundLocalError: local variable 'perm' referenced before assignment".


问:
Performing validation using a custom annotation and returning a Response with HTTP error code
I am currently working with Java EE and I have a requirement to validate a field using a custom annotation and if it's valid, do nothing, but if it's not, then return a response. Let me explain it in a bit more detail below.

Firstly I have this Enum called Weekday.

```<code>public enum Weekday {
    Monday("monday"),
    Tuesday("tuesday"),
    Wednesday("wednesday"),
    Thursday("thursday"),
    Friday("Friday),
    Saturday("saturday"),
    Sunday("sunday");

    private final String value;
    Weekday(String value) {
        this.value = value
    }
}
</code>```

Then I have this request that accepts a weekday. Now I want to check if the weekday value is either Monday or Tuesday, if it's not then I want to respond with the HTTP error code 400 Bad request instead of proceeding with processing the request.

```<code>
@Path("/dosomething")
@GET
public Response doSomething(@QueryParam("weekday") Weekday weekday) {
    return Response.ok().build();
}

</code>```

I want to create a @ValidateWeekday annotation for the field which will validate it and send an Error 400 response.

My first approach involved using if-else then a switch case, but that is not clean looking. I want to do it using a custom annotation.

```<code>
if (weekday =! Weekday.Monday && weekday != Weekday.Tuesday) {
    return Response.status(400).build();
}

</code>```

This is a bad practice and I want to avoid this.

What I want is something like this.

```<code>
@Path("/dosomething")
@GET
public Response doSomething(@QueryParam("weekday") @ValidateWeekday Weekday weekday) {
    return Response.ok().build();
}

</code>```

So, how do I go about doing this by making my own @ValidateWeekday annotaion ?

In Spring we can simply use @ControllerAdvice and @ExceptionHandler annotations, but I'm not using Spring so I have to build my own annotations that can achieve this.

Body:
I am currently working with Java EE and I have a requirement to validate a field using a custom annotation and if it's valid, do nothing, but if it's not, then return a response. Let me explain it in a bit more detail below.

Firstly I have this Enum called Weekday.

public enum Weekday {
    Monday("monday"),
    Tuesday("tuesday"),
    Wednesday("wednesday"),
    Thursday("thursday"),
    Friday("Friday),
    Saturday("saturday"),
    Sunday("sunday");

    private final String value;
    Weekday(String value) {
        this.value = value
    }
}

Then I have this request that accepts a weekday. Now I want to check if the weekday value is either Monday or Tuesday, if it's not then I want to respond with the HTTP error code 400 Bad request instead of proceeding with processing the request.

@Path("/dosomething")
@GET
public Response doSomething(@QueryParam("weekday") Weekday weekday) {
    return Response.ok().build();
}

I want to create a @ValidateWeekday annotation for the field which will validate it and send an Error 400 response.

My first approach involved using if-else then a switch case, but that is not clean looking. I want to do it using a custom annotation.

if (weekday =! Weekday.Monday && weekday != Weekday.Tuesday) {
    return Response.status(400).build();
}

This is a bad practice and I want to avoid this.

What I want is something like this.

@Path("/dosomething")
@GET
public Response doSomething(@QueryParam("weekday") @ValidateWeekday Weekday weekday) {
    return Response.ok().build();
}

So, how do I go about doing this by making my own @ValidateWeekday annotaion ?

In Spring we can simply use @ControllerAdvice and @ExceptionHandler annotations, but I'm not using Spring so I have to build my own annotations that can achieve this.


问:
How can I reassign XHR without reloading the page in JavaScript?
This is a PHP Bootstrap CODE I try to dynamically change bootstrap modal body content that can I can easily add or edit product category . Then I submit the entered or changed data to save into database by submitting the form through Ajax .
I use pure JavaScript Ajax request to done this job for me.
For the first time when I click into Create Product Category Everything work fine. But when the first time content add then I try to add anther product the second product will automatically add two times it will increase for the forth time and so on .
I know the problem . But I can't solve it.
how can I reassign or how can I Completely clean Ajax after the task done then after clicking to create new product category I will renew Ajax ?
this is my JavaScript Ajax code :

```<code>// get add category
document.getElementById('add_category').addEventListener('click', () => {

    var xhr = new XMLHttpRequest();

    xhr.open("GET", 'add.php', true);
    console.log("add_category")
    xhr.onload = function() {
        if (this.status == 200) {
            document.getElementById('exampleModalLabel').innerHTML = 'Create Product Category';
            document.getElementById('modal-body').innerHTML = this.response;
            // console.log(this.response)
            dynamicChangePicture()

            // on change category_name
            onChangeCategoryName('category_name');

            // add new Category
            document.getElementById('save_btn').addEventListener('click', (e) => {
                e.preventDefault();
                console.log('save_btn')
                var xhr = new XMLHttpRequest();
                xhr.open('POST', `../includes/functions.php`, true)
                xhr.onload = function() {
                    if (xhr.status == 200) {
                        console.log(xhr.response)

                        if (xhr.response == 'category name add successfully! ') {

                            document.getElementById('close_modal_btn').click();
                            showMessage(xhr.response, 'Add')
                            console.log(xhr.responseText)
                            // document.getElementById('logo_box').innerHTML = `<span class='text-success'>${xhr.response}</span>`;
                        } else {
                            showMessage(xhr.response, 'Remove')
                            document.getElementById('logo_box').innerHTML = `<span class='text-danger'>${xhr.response}</span>`;
                        }

                        setTimeout(() => {
                            document.getElementById('table-body').innerHTML = '';
                            defaultLoad();
                            console.log("data Loaded")
                        }, 5000)
                    }
                }
                const formData = new FormData(document.getElementById('add_category_form'))
                xhr.send(formData);
            })
        }
    }
    xhr.send();
})
</code>```

even I Change inside xhr variable  with the a deferent one it will still have the same problem.

Body:
This is a PHP Bootstrap CODE I try to dynamically change bootstrap modal body content that can I can easily add or edit product category . Then I submit the entered or changed data to save into database by submitting the form through Ajax .
I use pure JavaScript Ajax request to done this job for me.
For the first time when I click into Create Product Category Everything work fine. But when the first time content add then I try to add anther product the second product will automatically add two times it will increase for the forth time and so on .
I know the problem . But I can't solve it.
how can I reassign or how can I Completely clean Ajax after the task done then after clicking to create new product category I will renew Ajax ?
this is my JavaScript Ajax code :

// get add category
document.getElementById('add_category').addEventListener('click', () => {

    var xhr = new XMLHttpRequest();

    xhr.open("GET", 'add.php', true);
    console.log("add_category")
    xhr.onload = function() {
        if (this.status == 200) {
            document.getElementById('exampleModalLabel').innerHTML = 'Create Product Category';
            document.getElementById('modal-body').innerHTML = this.response;
            // console.log(this.response)
            dynamicChangePicture()

            // on change category_name
            onChangeCategoryName('category_name');

            // add new Category
            document.getElementById('save_btn').addEventListener('click', (e) => {
                e.preventDefault();
                console.log('save_btn')
                var xhr = new XMLHttpRequest();
                xhr.open('POST', `../includes/functions.php`, true)
                xhr.onload = function() {
                    if (xhr.status == 200) {
                        console.log(xhr.response)

                        if (xhr.response == 'category name add successfully! ') {

                            document.getElementById('close_modal_btn').click();
                            showMessage(xhr.response, 'Add')
                            console.log(xhr.responseText)
                            // document.getElementById('logo_box').innerHTML = `<span class='text-success'>${xhr.response}</span>`;
                        } else {
                            showMessage(xhr.response, 'Remove')
                            document.getElementById('logo_box').innerHTML = `<span class='text-danger'>${xhr.response}</span>`;
                        }

                        setTimeout(() => {
                            document.getElementById('table-body').innerHTML = '';
                            defaultLoad();
                            console.log("data Loaded")
                        }, 5000)
                    }
                }
                const formData = new FormData(document.getElementById('add_category_form'))
                xhr.send(formData);
            })
        }
    }
    xhr.send();
})

even I Change inside xhr variable  with the a deferent one it will still have the same problem.


问:
is there a way to handle the status of started game by my app in epic games \ steam or other launcher?
I am creating an application that manages the launch of the game from steam \ epic games by id or for epic app name and i want to know if game started without error or even if game is installed.

```<code>STARTUPINFO info = { sizeof(info) };
PROCESS_INFORMATION processInfo;
if (CreateProcessA(epic_path.c_str(), (LPSTR)params.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
    WaitForSingleObject(processInfo.hProcess, INFINITE);

    DWORD exit_code;
    if (GetExitCodeProcess(processInfo.hProcess, &exit_code))
        cout << exit_code << endl << GetLastError() << endl;

    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);
}
</code>```

I am using this code to start games. For steam param is "-applaunch id", for epic games "com.epicgames.launcher://apps/APP_NAME?action=launch&silent=true"

But exit_code shows 0 everytime, even if the game is not installed

Am i able to read this error code and say it to user ? Of Course user can read it manually but i also  hide launcher everytime it shows (beside auth), so user only see my app and can't see this error.

For the steam if the game is paid, it even dont shows me any error and just bring me to the store with this game and still exit_code is 0.

Body:
I am creating an application that manages the launch of the game from steam \ epic games by id or for epic app name and i want to know if game started without error or even if game is installed.

STARTUPINFO info = { sizeof(info) };
PROCESS_INFORMATION processInfo;
if (CreateProcessA(epic_path.c_str(), (LPSTR)params.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
    WaitForSingleObject(processInfo.hProcess, INFINITE);

    DWORD exit_code;
    if (GetExitCodeProcess(processInfo.hProcess, &exit_code))
        cout << exit_code << endl << GetLastError() << endl;

    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);
}

I am using this code to start games. For steam param is "-applaunch id", for epic games "com.epicgames.launcher://apps/APP_NAME?action=launch&silent=true"

But exit_code shows 0 everytime, even if the game is not installed

Am i able to read this error code and say it to user ? Of Course user can read it manually but i also  hide launcher everytime it shows (beside auth), so user only see my app and can't see this error.

For the steam if the game is paid, it even dont shows me any error and just bring me to the store with this game and still exit_code is 0.


问:
Crypt32Import OID does not return the desired values
We have a product that is installed using Install Shield 2016.
I want to update the Install Shield to newer version R3 2020.
After the upgrade the product runs as before, but one part of it that related to activation and licensing gives me an error.

To understand why, the following code was debugged and is the one that gives different results when switching between the installers (even if it's on the same computer).

The lines of code is:

```<code>//--- Get the signature date
SignedCms signedCms = new SignedCms();
signedCms.Decode(encodedMessage);
SignerInfo signerInfo = signedCms.SignerInfos.OfType<SignerInfo>()
.Where(it => it.UnsignedAttributes.OfType<CryptographicAttributeObject>()
.Any(attr => string.Compare(attr.Oid.Value, Crypt32Import.OID_RSA_CounterSign) == 0))
.First();
</code>```

This will return an exception: "Sequence contains no elements"
so debugging this code will return that attr.Oid.Value has different results if I use old/new installer version:

Install Shield 2016: 1.2.840.113549.1.9.6

Install Shield 2020: 1.3.6.1.4.1.311.3.3.1

Why is this happening?

Body:
We have a product that is installed using Install Shield 2016.
I want to update the Install Shield to newer version R3 2020.
After the upgrade the product runs as before, but one part of it that related to activation and licensing gives me an error.

To understand why, the following code was debugged and is the one that gives different results when switching between the installers (even if it's on the same computer).

The lines of code is:

//--- Get the signature date
SignedCms signedCms = new SignedCms();
signedCms.Decode(encodedMessage);
SignerInfo signerInfo = signedCms.SignerInfos.OfType<SignerInfo>()
.Where(it => it.UnsignedAttributes.OfType<CryptographicAttributeObject>()
.Any(attr => string.Compare(attr.Oid.Value, Crypt32Import.OID_RSA_CounterSign) == 0))
.First();

This will return an exception: "Sequence contains no elements"
so debugging this code will return that attr.Oid.Value has different results if I use old/new installer version:

Install Shield 2016: 1.2.840.113549.1.9.6

Install Shield 2020: 1.3.6.1.4.1.311.3.3.1

Why is this happening?


问:
How to connect to Android device from windows pc for internet
I have enabled Bluetooth tethering in Android phone. From windows, i need to connect to Android for internet

How to do via api or windows command?

Uwp app/ win32 api


问:
Collect data from multiple Django signals in session or cache
I have a view in views.py that hits multiple database models. Each model has its own signals registered with it (pre_save, post_save, post_delete, ...etc). Each signal collects the changes in data for each model.

Now, I want to collect all those changes to use them somehow at the end of my view. So, I though about saving such data temporarily in the user's session or cache to retrieve them just at the ned of my view, but unfortunately the signal functions doesn't take request parameter with it.

So, how can I do such?


问:
Why is Godot crashing on startup with this GDNative library?
I'm following this tutorial on voxel terrain generation in Godot. However, I'm using C++ instead of GDScript. I got to about 7:08. The code is pretty much exactly translated and it compiles fine. However, when I try to open the project in Godot I get the Godot Engine has stopped working. A problem caused the program to stop working correctly... error. I don't know what's happening. When I delete the dll from the project it opens fine. Before, I got the official example to compile perfectly.

When I run the shell script Godot_v3.5.1-stable_win64_console.cmd instead of the executable the following error gets printed:

```<code>ERROR: Another resource is loaded from path 'res://Chunk.gdns' (possible cyclic resource inclusion).
   at: (core/resource.cpp:79)
</code>```

chunk.h:

```<code>#ifndef CHUNK_H
#define CHUNK_H

#include <vector>

#include <Godot.hpp>
#include <StaticBody.hpp>
#include <SurfaceTool.hpp>
#include <ArrayMesh.hpp>
#include <Mesh.hpp>
#include <MeshInstance.hpp>

namespace godot {

const Vector3 VERTICES[] = {
    Vector3(0, 0, 0),
    Vector3(1, 0, 0),
    Vector3(0, 1, 0),
    Vector3(1, 1, 0),
    Vector3(0, 0, 1),
    Vector3(1, 0, 1),
    Vector3(0, 1, 1),
    Vector3(1, 1, 1),
};

const Vector3 DIMENSION = Vector3(16, 64, 16);

const unsigned char TOP[] = {2, 3, 7, 6};
const unsigned char BOTTOM[] = {0, 4, 5, 1};
const unsigned char LEFT[] = {6, 4, 0, 2};
const unsigned char RIGHT[] = {3, 1, 5, 7};
const unsigned char FRONT[] = {7, 5, 4, 6};
const unsigned char BACK[] = {2, 0, 1, 3};

struct Block {};

class Chunk : public StaticBody {
GODOT_CLASS(Chunk, StaticBody)

private:
    std::vector<Block> blocks;
    SurfaceTool* st;
    ArrayMesh* mesh;
    MeshInstance* meshInstance;

public:
    void Update();
    void CreateBlock(const unsigned char x, const unsigned char y, const unsigned char z);
    void CreateFace(const unsigned char* indices, const unsigned char x, const unsigned char y, const unsigned char z);

    Chunk();
    ~Chunk();

    static void _register_methods();
    void _init();

    void _process(float delta);
};

}

#endif
</code>```

chunk.cpp:

```<code>#include "chunk.h"

using namespace godot;

void Chunk::_register_methods() {
    register_method("_process", &Chunk::_process);
}

Chunk::Chunk() {}

Chunk::~Chunk() {
    delete st;
    delete mesh;
    delete meshInstance;
}

void Chunk::_init() {
    st = new SurfaceTool();
    mesh = nullptr;
    meshInstance = nullptr;

    Update();
}

void Chunk::_process(float delta) {}

void Chunk::Update() {
    // Unload chunk
    if (meshInstance != nullptr) {
        meshInstance->call_deferred("queue_free");
        meshInstance = nullptr;
    }

    mesh = new ArrayMesh();
    meshInstance = new MeshInstance();
    st->begin(Mesh::PRIMITIVE_TRIANGLES);

    for (unsigned char x = 0; x < DIMENSION.x; x++) {
        for (unsigned char y = 0; y < DIMENSION.y; y++) {
            for (unsigned char z = 0; z < DIMENSION.z; z++) {
                CreateBlock(x, y, z);
            }
        }
    }

    st->generate_normals(false);
    st->commit(mesh);
    meshInstance->set_mesh(mesh);

    add_child(meshInstance);
    meshInstance->create_trimesh_collision();
}

void Chunk::CreateBlock(const unsigned char x, const unsigned char y, const unsigned char z) {
    CreateFace(TOP, x, y, z);
    CreateFace(BOTTOM, x, y, z);
    CreateFace(LEFT, x, y, z);
    CreateFace(RIGHT, x, y, z);
    CreateFace(BACK, x, y, z);
    CreateFace(FRONT, x, y, z);
}

void Chunk::CreateFace(const unsigned char* indices, const unsigned char x, const unsigned char y, const unsigned char z) {
    auto offset = Vector3(x, y, z);

    // Get corners
    auto a = VERTICES[indices[0]] + offset;
    auto b = VERTICES[indices[1]] + offset;
    auto c = VERTICES[indices[2]] + offset;
    auto d = VERTICES[indices[3]] + offset;

    PoolVector3Array triangleOne;
    triangleOne.push_back(a);
    triangleOne.push_back(b);
    triangleOne.push_back(c);

    PoolVector3Array triangleTwo;
    triangleTwo.push_back(a);
    triangleTwo.push_back(c);
    triangleTwo.push_back(d);

    st->add_triangle_fan(triangleOne);
    st->add_triangle_fan(triangleTwo);
}
</code>```

Body:
I'm following this tutorial on voxel terrain generation in Godot. However, I'm using C++ instead of GDScript. I got to about 7:08. The code is pretty much exactly translated and it compiles fine. However, when I try to open the project in Godot I get the Godot Engine has stopped working. A problem caused the program to stop working correctly... error. I don't know what's happening. When I delete the dll from the project it opens fine. Before, I got the official example to compile perfectly.

When I run the shell script Godot_v3.5.1-stable_win64_console.cmd instead of the executable the following error gets printed:

ERROR: Another resource is loaded from path 'res://Chunk.gdns' (possible cyclic resource inclusion).
   at: (core/resource.cpp:79)

chunk.h:

#ifndef CHUNK_H
#define CHUNK_H

#include <vector>

#include <Godot.hpp>
#include <StaticBody.hpp>
#include <SurfaceTool.hpp>
#include <ArrayMesh.hpp>
#include <Mesh.hpp>
#include <MeshInstance.hpp>

namespace godot {

const Vector3 VERTICES[] = {
    Vector3(0, 0, 0),
    Vector3(1, 0, 0),
    Vector3(0, 1, 0),
    Vector3(1, 1, 0),
    Vector3(0, 0, 1),
    Vector3(1, 0, 1),
    Vector3(0, 1, 1),
    Vector3(1, 1, 1),
};

const Vector3 DIMENSION = Vector3(16, 64, 16);

const unsigned char TOP[] = {2, 3, 7, 6};
const unsigned char BOTTOM[] = {0, 4, 5, 1};
const unsigned char LEFT[] = {6, 4, 0, 2};
const unsigned char RIGHT[] = {3, 1, 5, 7};
const unsigned char FRONT[] = {7, 5, 4, 6};
const unsigned char BACK[] = {2, 0, 1, 3};

struct Block {};

class Chunk : public StaticBody {
GODOT_CLASS(Chunk, StaticBody)

private:
    std::vector<Block> blocks;
    SurfaceTool* st;
    ArrayMesh* mesh;
    MeshInstance* meshInstance;

public:
    void Update();
    void CreateBlock(const unsigned char x, const unsigned char y, const unsigned char z);
    void CreateFace(const unsigned char* indices, const unsigned char x, const unsigned char y, const unsigned char z);

    Chunk();
    ~Chunk();

    static void _register_methods();
    void _init();

    void _process(float delta);
};

}

#endif

chunk.cpp:

#include "chunk.h"

using namespace godot;

void Chunk::_register_methods() {
    register_method("_process", &Chunk::_process);
}

Chunk::Chunk() {}

Chunk::~Chunk() {
    delete st;
    delete mesh;
    delete meshInstance;
}

void Chunk::_init() {
    st = new SurfaceTool();
    mesh = nullptr;
    meshInstance = nullptr;

    Update();
}

void Chunk::_process(float delta) {}

void Chunk::Update() {
    // Unload chunk
    if (meshInstance != nullptr) {
        meshInstance->call_deferred("queue_free");
        meshInstance = nullptr;
    }

    mesh = new ArrayMesh();
    meshInstance = new MeshInstance();
    st->begin(Mesh::PRIMITIVE_TRIANGLES);

    for (unsigned char x = 0; x < DIMENSION.x; x++) {
        for (unsigned char y = 0; y < DIMENSION.y; y++) {
            for (unsigned char z = 0; z < DIMENSION.z; z++) {
                CreateBlock(x, y, z);
            }
        }
    }

    st->generate_normals(false);
    st->commit(mesh);
    meshInstance->set_mesh(mesh);

    add_child(meshInstance);
    meshInstance->create_trimesh_collision();
}

void Chunk::CreateBlock(const unsigned char x, const unsigned char y, const unsigned char z) {
    CreateFace(TOP, x, y, z);
    CreateFace(BOTTOM, x, y, z);
    CreateFace(LEFT, x, y, z);
    CreateFace(RIGHT, x, y, z);
    CreateFace(BACK, x, y, z);
    CreateFace(FRONT, x, y, z);
}

void Chunk::CreateFace(const unsigned char* indices, const unsigned char x, const unsigned char y, const unsigned char z) {
    auto offset = Vector3(x, y, z);

    // Get corners
    auto a = VERTICES[indices[0]] + offset;
    auto b = VERTICES[indices[1]] + offset;
    auto c = VERTICES[indices[2]] + offset;
    auto d = VERTICES[indices[3]] + offset;

    PoolVector3Array triangleOne;
    triangleOne.push_back(a);
    triangleOne.push_back(b);
    triangleOne.push_back(c);

    PoolVector3Array triangleTwo;
    triangleTwo.push_back(a);
    triangleTwo.push_back(c);
    triangleTwo.push_back(d);

    st->add_triangle_fan(triangleOne);
    st->add_triangle_fan(triangleTwo);
}


问:
jsONDecodeError. AJAX + Django. Comment system
I'm trying to implement a comment system in Django. The problem is that I can add a comment to the very first post and AJAX will work, that is, the comment will be published without reloading. But if I try to leave a comment on the following posts, I stumble upon an error: jsONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0).

In data = json.loads(request.body), there is a post_id and a body, but only if you leave a comment on the first post. To the rest of the request.body is just an empty string

models.py

```<code>from django.utils import timezone
from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='posts')
    title = models.CharField(max_length=30)
    body = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=timezone.now())

    def __str__(self) -> str:
        return self.title

class Comment(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='comments')
    body = models.CharField(max_length=255)
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, related_name='comments', blank=True)
    created_at = models.DateTimeField(auto_now_add=timezone.now())

    def __str__(self) -> str:
        return self.body
</code>```

views.py

```<code>from django.utils.formats import date_format
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from .models import *
from django.shortcuts import render
import json

def post_detail(request):
    quotes = Post.objects.all()

    context = {
        'quotes': quotes,
    }

    return render(request, 'app_one/post_detail.html', context)

def comment_create(request):
    data = json.loads(request.body)
    post_id = data['post_id']
    comment_body = data['body']

    user = User.objects.get(date_joined='2023-01-08 12:00:29.481762')

    post = get_object_or_404(Post, id=post_id)
    comment = Comment.objects.create(
        user=user,
        body=comment_body,
        post=post
    )

    created_at = date_format(
        comment.created_at, format='M. d, Y, h:m a', use_l10n=True)

    return JsonResponse({
        'user': comment.user.username,
        'body': comment.body,
        'created_at': created_at
    })
</code>```

post_detail.html

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
    <title>Document</title>
</head>

<body>
    {% for post in quotes %}

    <h1>{{post.title}}</h1>
    <h4>{{post.created_at}}</h4>
    <p>{{post.body}}</p>

    <hr>

    <div id="comment-div">
        <form action="{% url 'love:comment-create' %}" id="comment-form">
            <input type="hidden" id="post-id" value="{{post.id}}">
            <textarea id="comment-body" maxlength="255" rows="4" cols="50"></textarea>
            <br>
            <button type="submit" id="submit-comment">Comment</button>
        </form>
        <hr>
    </div>

    <div id="comment-list">
        <h2> Comments </h2>
        {% if post.comments.all %}
        {% for comment in post.comments.all %}
        <p>At {{comment.created_at|date:"M. d, Y, h:m a"}} {{comment.user}} commented:</p>
        <p>{{comment.body}}</p>
        {% endfor %}
        {% endif %}
    </div>
    {% endfor %}

    <script>
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        $('#submit-comment').click(function (e) {
            e.preventDefault();
            var url = $('#comment-form').attr("action");
            var post_id = $('#post-id').attr("value");
            var body = $('#comment-body').val();
            const csrftoken = getCookie('csrftoken');

            console.log(post_id)
            console.log(body)
            $.ajax({
                method: "POST",
                url: url,
                headers: { 'X-CsrfToken': csrftoken },
                data: JSON.stringify({ post_id: post_id, body: body }),
                success: function (comment) {
                    // $('#comment-div').prop("hidden", true);
                    $('#comment-body').val('');
                    $('#comment-list').append(
                        `<p>At ${comment.created_at} ${comment.user} commented:</p>
                        <p>${comment.body}</p>`
                    );
                }
            });
        });
    </script>
</body>

</html>
</code>```

What could be the problem?

And another small problem: when I try to enter a user into the console, an Anonymous User comes out. And when I check for user authentication, the verification does not pass, although I entered the admin panel

What could be the problem?

And another small problem: when I try to enter a user into the console, an Anonymous User comes out. And when I check for user authentication, the verification does not pass, although I entered the admin panel

Body:
I'm trying to implement a comment system in Django. The problem is that I can add a comment to the very first post and AJAX will work, that is, the comment will be published without reloading. But if I try to leave a comment on the following posts, I stumble upon an error: jsONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0).

In data = json.loads(request.body), there is a post_id and a body, but only if you leave a comment on the first post. To the rest of the request.body is just an empty string

models.py

from django.utils import timezone
from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='posts')
    title = models.CharField(max_length=30)
    body = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=timezone.now())

    def __str__(self) -> str:
        return self.title

class Comment(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='comments')
    body = models.CharField(max_length=255)
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, related_name='comments', blank=True)
    created_at = models.DateTimeField(auto_now_add=timezone.now())

    def __str__(self) -> str:
        return self.body

views.py

from django.utils.formats import date_format
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from .models import *
from django.shortcuts import render
import json

def post_detail(request):
    quotes = Post.objects.all()

    context = {
        'quotes': quotes,
    }

    return render(request, 'app_one/post_detail.html', context)

def comment_create(request):
    data = json.loads(request.body)
    post_id = data['post_id']
    comment_body = data['body']

    user = User.objects.get(date_joined='2023-01-08 12:00:29.481762')

    post = get_object_or_404(Post, id=post_id)
    comment = Comment.objects.create(
        user=user,
        body=comment_body,
        post=post
    )

    created_at = date_format(
        comment.created_at, format='M. d, Y, h:m a', use_l10n=True)

    return JsonResponse({
        'user': comment.user.username,
        'body': comment.body,
        'created_at': created_at
    })

post_detail.html

<!DOCTYPE html>

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

    <title>Document</title>

    {% for post in quotes %}

{{post.title}}

{{post.created_at}}

{{post.body}}

        <form action="{% url 'love:comment-create' %}" id="comment-form">
            <input type="hidden" id="post-id" value="{{post.id}}">
            <textarea id="comment-body" maxlength="255" rows="4" cols="50"></textarea>

            <button type="submit" id="submit-comment">Comment</button>
        </form>

 Comments

        {% if post.comments.all %}
        {% for comment in post.comments.all %}

At {{comment.created_at|date:"M. d, Y, h:m a"}} {{comment.user}} commented:

{{comment.body}}

        {% endfor %}
        {% endif %}

    {% endfor %}

What could be the problem?

And another small problem: when I try to enter a user into the console, an Anonymous User comes out. And when I check for user authentication, the verification does not pass, although I entered the admin panel

What could be the problem?

And another small problem: when I try to enter a user into the console, an Anonymous User comes out. And when I check for user authentication, the verification does not pass, although I entered the admin panel


问:
Bootstrap collapse has TypeError: $(...).offset(...) is undefined
I added some code to make the page scroll to top of active (open) accordion panel (Bootstrap 4 accordion).

```<code>$('.collapse').on('show.bs.collapse', function(e) {
var $card = $(this).closest('.card');
var $open = $($(this).data('parent')).find('.collapse.show');

var additionalOffset = 0;
if($card.prevAll().filter($open.closest('.card')).length !== 0)
{
      additionalOffset =  $open.height();
}
$('html,body').animate({
  scrollTop: $card.offset().top - additionalOffset
}, 500);
</code>```

});

This works great for the bootstrap accordions. However, when I now use other collapsibles like buttons or navbars, I get the error: TypeError: $(...).offset(...) is undefined

I'm using the scrollTop function and calling the parameter card as scrollTop. Since, scrollTop is also a jQuery function, I guess, scrollTop is already calling jQuery.

I there a way to define card so that it's specific for scrolling to the top of an open accordion panel and doesn't interfere with other collapsibles?
Or do I have to redefine jQuery? FYI, I'm not an expert in jQuery.

Body:
I added some code to make the page scroll to top of active (open) accordion panel (Bootstrap 4 accordion).

$('.collapse').on('show.bs.collapse', function(e) {
var $card = $(this).closest('.card');
var $open = $($(this).data('parent')).find('.collapse.show');

var additionalOffset = 0;
if($card.prevAll().filter($open.closest('.card')).length !== 0)
{
      additionalOffset =  $open.height();
}
$('html,body').animate({
  scrollTop: $card.offset().top - additionalOffset
}, 500);

});

This works great for the bootstrap accordions. However, when I now use other collapsibles like buttons or navbars, I get the error: TypeError: $(...).offset(...) is undefined

I'm using the scrollTop function and calling the parameter card as scrollTop. Since, scrollTop is also a jQuery function, I guess, scrollTop is already calling jQuery.

I there a way to define card so that it's specific for scrolling to the top of an open accordion panel and doesn't interfere with other collapsibles?
Or do I have to redefine jQuery? FYI, I'm not an expert in jQuery.


问:
ErrorException file_get_contents(C:\wamp64\www\casting\.env): failed to open stream: No such file or directory
I'm trying to run a laravel project on wampserver.

I have the following structure:

I executed the following commands :

```<code>composer update
composer install
php artisan cache:clear
php artisan config:clear
</code>```

And when I run this Cmd: php artisan key:generate, I get the following error:

```<code>ErrorException

  file_get_contents(C:\wamp64\www\casting\.env): failed to open stream: No such file or directory

  at C:\wamp64\www\casting\vendor\laravel\framework\src\Illuminate\Foundation\Console\KeyGenerateCommand.php:96
</code>```

I don't know what I should do.

Body:
I'm trying to run a laravel project on wampserver.

I have the following structure:

I executed the following commands :

composer update
composer install
php artisan cache:clear
php artisan config:clear

And when I run this Cmd: php artisan key:generate, I get the following error:

ErrorException

  file_get_contents(C:\wamp64\www\casting\.env): failed to open stream: No such file or directory

  at C:\wamp64\www\casting\vendor\laravel\framework\src\Illuminate\Foundation\Console\KeyGenerateCommand.php:96

I don't know what I should do.


问:
What is the use of Apache Tomcat Webserver
When building the Java web application through the maven build tool we get the war file as the artifact which is an executable file. So I have a basic doubt which is if we can execute the war file directly then why do we need an Apache tomcat webserver to host this war artifact?</p>


问:
show autocomplete suggestions only with street and number
I have this code for google autocomplete:

```<code>// Google Autocomplete Addresses
let autocomplete;
var street;
var streetNumber;
var city;
var zip;

function initAutocomplete() {
  autocomplete = new google.maps.places.Autocomplete(document.querySelector("#autocompleteAddress"), {
    componentRestrictions: { country: ["de", "DE"] },
    fields: ["address_components", "geometry"],
    types: ["address"],
  });
  autocomplete.addListener("place_changed", fillInAddress);
}

function fillInAddress() {

  const place = autocomplete.getPlace();

  for (const component of place.address_components) {

    switch (component.types[0]) {

      case "route":
        street = component.long_name;
        $( "#street" ).val( street )
        break;

      case "street_number":
        streetNumber = component.long_name
        $("#streetnumber").val( streetNumber )
        break;

      case "postal_code":
        plz = component.long_name;
        $("#zip").val( plz )
        break;

      case "locality":
        city = component.long_name;
        $("#city").val( city )
      break;

    }
  }

  $("#autocompleteAddress").val( street + " " + streetNumber)

}
</code>```

This works fine, but not perfectly
My problem: If you only write the streetname, you get the suggestions:

If you now pick a suggestion, I get no streetnumber and no zip code (logically):

how can i display the suggestions only after street and house number have been entered (a string and a number)?

Thanks!

Body:
I have this code for google autocomplete:

// Google Autocomplete Addresses
let autocomplete;
var street;
var streetNumber;
var city;
var zip;

function initAutocomplete() {
  autocomplete = new google.maps.places.Autocomplete(document.querySelector("#autocompleteAddress"), {
    componentRestrictions: { country: ["de", "DE"] },
    fields: ["address_components", "geometry"],
    types: ["address"],
  });
  autocomplete.addListener("place_changed", fillInAddress);
}

function fillInAddress() {

  const place = autocomplete.getPlace();

  for (const component of place.address_components) {

    switch (component.types[0]) {

      case "route":
        street = component.long_name;
        $( "#street" ).val( street )
        break;

      case "street_number":
        streetNumber = component.long_name
        $("#streetnumber").val( streetNumber )
        break;

      case "postal_code":
        plz = component.long_name;
        $("#zip").val( plz )
        break;

      case "locality":
        city = component.long_name;
        $("#city").val( city )
      break;

    }
  }

  $("#autocompleteAddress").val( street + " " + streetNumber)

}

This works fine, but not perfectly
My problem: If you only write the streetname, you get the suggestions:

If you now pick a suggestion, I get no streetnumber and no zip code (logically):

how can i display the suggestions only after street and house number have been entered (a string and a number)?

Thanks!


问:
PyCharm .jpg file is not getting uploaded
When I move my downloaded file to the PyCharm, I am getting the following error:
"Image not loaded, Try to open it externally to fix format problem"

Can someone please help me to overcome this problem?

I tried to upload/move this image by simply dragging from the download folder to the PyCharm project, but the error is popping up!


问:
Java Jakarta API from basic to bearer
I am new to Java Jakarta development, please could someone tell me how to convert authentication type in existing Java Jakarta-ee API from basic-auth to bearer-token, does it need a lot of effort?

I searched in internet, it seems it uses specific libraries.

Title: Java Jakarta API from basic to bearer


问:
Authenticate ElasticSearchClient in Nifi with Kerberos
I have been trying to push the audit payload to elastic search datasource from my Nifi pipeline. I see PutElasticsearchRecord we could have ElasticSearchClientServiceImpl set with username and password. But my requirement is with a principal and keytab based auth. Has someone done similar stuff or is implmenting your own ElasticSearchClient with kereberos auth the best way ?</p>


问:
How on class name get some hints of existing classes of my project for valid declaration?
Working with PhpStorm 2021.1 on Laravel site. In some cases I know which  class I need to use but I do not know its declaration.

An example when I use BelongsTo in my model :

public function user() : BelongsTo
{
    return $this->belongsTo(User::class);
}
```
<p>PhpStorm shows me an error that <code>BelongsTo</code> is not defined. So I try to find which class I have to use with right menu options like :  “GoTo => Declaration or Usages” or “GoTo => Implementations” or “GoTo => Type Declarations” and others and failed...</p>
<p>Actually I need :</p>
<pre class="lang-php prettyprint-override"><code>use Illuminate\Database\Eloquent\Relations\BelongsTo;
</code>```

Can I got some hints of existing classes of my project with such names?

Body:
Working with PhpStorm 2021.1 on Laravel site. In some cases I know which  class I need to use but I do not know its declaration.

An example when I use BelongsTo in my model :

public function user() : BelongsTo
{
    return $this->belongsTo(User::class);
}

PhpStorm shows me an error that BelongsTo is not defined. So I try to find which class I have to use with right menu options like :  “GoTo => Declaration or Usages” or “GoTo => Implementations” or “GoTo => Type Declarations” and others and failed...

Actually I need :

use Illuminate\Database\Eloquent\Relations\BelongsTo;

Can I got some hints of existing classes of my project with such names?


问:
Django admin download reportlab PDF
I use this guide(https://docs.djangoproject.com/en/4.1/howto/outputting-pdf/) to download PDF. It works on regular public page. But I am trying to get it working in the admin for a specific model and have model data on the PDF.

In my admin I have:

cakes/models.py

```<code>from django.db import models

class Cake(models.Model):
    date = models.DateField("Date ordered")
    name = models.CharField()

    def pdf_link(self):
        from django.utils.html import format_html
        return format_html("<a href='pdf/%s/'>Download PDF</a>" % self.pk)
</code>```

Dislay the PDF link in the django admin. The link is showing up in admin, it just doesn't link to the PDF yet(pass pdf_link)...

cakes/admin.py

```<code>from django.contrib import admin
from .models import Cake

@admin.register(Cake)
class CakeAdmin(admin.ModelAdmin):
    list_display = (
        'id',
        'customer',
        'date',
        'pdf_link',
    )
</code>```

On my cakes.views.py I have the generate_pdf function from the django docs.

How do I connect/link my view function(generate_pdf) with the pdf_link function in my model?

I can download the PDF outside the admin. I'm just not sure how to tie it all together in the admin.

Title: Django admin download reportlab PDF

Body:
I use this guide(https://docs.djangoproject.com/en/4.1/howto/outputting-pdf/) to download PDF. It works on regular public page. But I am trying to get it working in the admin for a specific model and have model data on the PDF.

In my admin I have:

cakes/models.py

from django.db import models

class Cake(models.Model):
    date = models.DateField("Date ordered")
    name = models.CharField()

    def pdf_link(self):
        from django.utils.html import format_html
        return format_html("Download PDF" % self.pk)

Dislay the PDF link in the django admin. The link is showing up in admin, it just doesn't link to the PDF yet(pass pdf_link)...

cakes/admin.py

from django.contrib import admin
from .models import Cake

@admin.register(Cake)
class CakeAdmin(admin.ModelAdmin):
    list_display = (
        'id',
        'customer',
        'date',
        'pdf_link',
    )

On my cakes.views.py I have the generate_pdf function from the django docs.

How do I connect/link my view function(generate_pdf) with the pdf_link function in my model?

I can download the PDF outside the admin. I'm just not sure how to tie it all together in the admin.


问:
mongo not found error even after path setup
```<code>mongo : The term 'mongo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ mongo
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (mongo:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

help me to run mongo and mongod please

Body:
mongo : The term 'mongo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ mongo
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (mongo:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

help me to run mongo and mongod please


问:
Invalid Hook Call when using styled-components in React
Can't get styled components to work. All I'm doing is

npx create-react-app

and writing this in my App.js file:

```<code>import './App.css';
import styled from "styled-components";

const Main = styled.main`
  font-family: "Clear Sans", "Helvetica Neue", Arial, sans-serif;

  display: flex;
  flex-direction: column;
  align-items:  center;

  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  `;

  const Header = styled.header`
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  width: 100%;

  border-bottom: 1px solid #3a3a3c;

  font-weight: 700;
  font-size: 3.6rem;
  letter-spacing: 0.2rem;
  text-transform: uppercase;
  `;

function App() {

  return (
    <div>
      <Main>
        <Header>My App</Header>
      </Main>
    </div>
  );
}

export default App;
</code>```

When I run the app i get this wall of errors

```<code>Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. react.development.js:209
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. react.development.js:209
Uncaught TypeError: dispatcher is null
    useDebugValue React
    O StyledComponent.js:116
    O StyledComponent.js:174
    React 11
    workLoop scheduler.development.js:266
    flushWork scheduler.development.js:239
    performWorkUntilDeadline scheduler.development.js:533
react.development.js:1659
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. react.development.js:209
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. react.development.js:209
Uncaught TypeError: dispatcher is null
    useDebugValue React
    O StyledComponent.js:116
    O StyledComponent.js:174
    React 12
    workLoop scheduler.development.js:266
    flushWork scheduler.development.js:239
    performWorkUntilDeadline scheduler.development.js:533
react.development.js:1659
The above error occurred in the <styled.main> component:

O@http://localhost:3000/static/js/bundle.js:4518:8
div
App

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries. react-dom.development.js:18687
Uncaught TypeError: dispatcher is null
    useDebugValue React
    O StyledComponent.js:116
    O StyledComponent.js:174
    React 9
    workLoop scheduler.development.js:266
    flushWork scheduler.development.js:239
    performWorkUntilDeadline scheduler.development.js:533
react.development.js:1659
    useDebugValue React
    O StyledComponent.js:116
    O StyledComponent.js:174
    React 9
    performConcurrentWorkOnRoot self-hosted:1406
    workLoop scheduler.development.js:266
    flushWork scheduler.development.js:239
    performWorkUntilDeadline scheduler.development.js:533
</code>```

Any ideas how to fix this? React and ReactDOM should be up to date. I'm not even using any hooks.

I expected the styled-components to show up correctly, instead I get an empty page with the errors described above in the browser console.

Heres package.json

```<code>    {
  "name": "wordle",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

Body:
Can't get styled components to work. All I'm doing is

npx create-react-app

and writing this in my App.js file:

import './App.css';
import styled from "styled-components";

const Main = styled.main`
  font-family: "Clear Sans", "Helvetica Neue", Arial, sans-serif;

  display: flex;
  flex-direction: column;
  align-items:  center;

  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  `;

  const Header = styled.header`
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  width: 100%;

  border-bottom: 1px solid #3a3a3c;

  font-weight: 700;
  font-size: 3.6rem;
  letter-spacing: 0.2rem;
  text-transform: uppercase;
  `;

function App() {

  return (

        My App

  );
}

export default App;

When I run the app i get this wall of errors

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. react.development.js:209
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. react.development.js:209
Uncaught TypeError: dispatcher is null
    useDebugValue React
    O StyledComponent.js:116
    O StyledComponent.js:174
    React 11
    workLoop scheduler.development.js:266
    flushWork scheduler.development.js:239
    performWorkUntilDeadline scheduler.development.js:533
react.development.js:1659
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. react.development.js:209
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. react.development.js:209
Uncaught TypeError: dispatcher is null
    useDebugValue React
    O StyledComponent.js:116
    O StyledComponent.js:174
    React 12
    workLoop scheduler.development.js:266
    flushWork scheduler.development.js:239
    performWorkUntilDeadline scheduler.development.js:533
react.development.js:1659
The above error occurred in the


问:
Can @Async method see data inserted by the calling thread which is @Transactional? -Spring Boot / JPA
I have an Async call at the end of a Service which is annotated @Transactional. The service updates some data (with JPA/Hibernate). After all the manipulation is done on the data, the same service makes an Async calls which fetches data including the records updated earlier in the service. My question is - Would the Async step be able to see the updated data? If not, is there a way to run the Async method in the same Transaction as for the invoking thread so that it can see the data? Below is the pseudo/rough code:</p>
```<code>@Transactional
@Service
public class ContactService {

   public ContactDetailsDTO updateContactAndFetchProjects(ContactDTO contact){

      contactRepository.updateContact(contact);

      asyncProjectFetcher.fetchContactProjects(contact);
      CompletableFuture.allOf(asyncProjectFetcher).join();
      .......
      .......
      return contactDetailsDTO;

   }

}

public class AsyncProjectFetcher {

     @Async
     public CompletableFuture<ContactDetailsDTO> fetchContactProjects(ContactDTO contact)
     {
         .......
         //can this see the data updates done in updateContactAndFetchProjects?
     }

}
</code>```

Body:
I have an Async call at the end of a Service which is annotated @Transactional. The service updates some data (with JPA/Hibernate). After all the manipulation is done on the data, the same service makes an Async calls which fetches data including the records updated earlier in the service. My question is - Would the Async step be able to see the updated data? If not, is there a way to run the Async method in the same Transaction as for the invoking thread so that it can see the data? Below is the pseudo/rough code:

@Transactional
@Service
public class ContactService {

   public ContactDetailsDTO updateContactAndFetchProjects(ContactDTO contact){

      contactRepository.updateContact(contact);

      asyncProjectFetcher.fetchContactProjects(contact);
      CompletableFuture.allOf(asyncProjectFetcher).join();
      .......
      .......
      return contactDetailsDTO;

   }

}

public class AsyncProjectFetcher {

     @Async
     public CompletableFuture<ContactDetailsDTO> fetchContactProjects(ContactDTO contact)
     {
         .......
         //can this see the data updates done in updateContactAndFetchProjects?
     }

}


问:
How to prevent chunks for ckeditor library in Vite + Vue 3 / Running into "failed to fetch dynamically imported module"
We are using a CKEditor in a html editor (TheHtmlEditor.vue) that loads up 'contentItems' dynamically, depending on what content the user has stored at a given page previously.
However, revisiting that page at a later time, it fails loading randomly, due to loading errors of chunked imports:

GET https://gts.dev/node_modules/.vite/deps/@ckeditor_ckeditor5-typing_src_texttransformation__js.js?v=c9825b52 net::ERR_FAILED
runtime-core.esm-bundler.js:223

TypeError: Failed to fetch dynamically imported module: https://gts.dev/src/components/cms/TheHtmlEditor.vue
...
createNewEditorInstanceEntry @ TheCmsPage.vue:88

(anonymous) @ TheCmsPage.vue:187
TheHtmlEditor.vue:62

GET https://gts.dev/node_modules/.vite/deps/@ckeditor_ckeditor5-list_src_todolist.js?v=33cc3966 net::ERR_FAILED
TheHtmlEditor.vue:63

GET https://gts.dev/node_modules/.vite/deps/@ckeditor_ckeditor5-basic-styles_src_underline__js.js?v=e4b76b9d net::ERR_FAILED
TheHtmlEditor.vue:64

GET https://gts.dev/node_modules/.vite/deps/@ckeditor_ckeditor5-undo_src_undo__js.js?v=c361c7f7 net::ERR_FAILED

In our content management system "TheCmsPage.vue" is a placeholder page for all the dynamically created content items that the user has previously added on each different page.

The template of "TheCmsPage.vue" looks as follows:

```<code>
<template>
    <div class="container bg-vue">
        <TheNavbar />
        <main>
            <TheCmsSubBar />
            <div
                class="d-flex flex-column align-items-stretch flex-grow-1 bg-white p-3 pt-4 position-relative scrollarea"
            >
                <div class="ps-3">
                    <p class="fs-6 text-muted text-start">
                        {{ pageStore.getCurrentPage?.path }}
                    </p>
                </div>
                <TheEditCmsPageBtnsForPageTop
                    v-if="pageStore.getCurrentPage != null"
                    :pageId="pageStore.getCurrentPage.id.toString()"
                />
                <div
                    v-for="componentInstance in propsForEditorInstances || [] as PropsForEditorInstance[]"
                    :key="componentInstance.contentItemId.toString()"
                >
                    <TheHtmlEditor :contentItemId="componentInstance.contentItemId" />
                </div>
                <TheButtonAddWysiwygEditor
                    v-if="pageStore.getCurrentPage != null"
                    :pageId="pageStore.getCurrentPage.id"
                    :buttonStyles="buttonStyles()"
                />
            </div>
        </main>
        <TheFooter />
    </div>
</template>

<script setup lang="ts">
import TheCmsSubBar from '@/components/cms/TheCmsSubBar.vue'
import TheButtonAddWysiwygEditor from '@/components/cms/TheButtonAddWysiwygEditor.vue'
import TheLoadingHtmlEditor from './TheLoadingHtmlEditor.vue'
import TheEditCmsPageBtnsForPageTop from './TheEditCmsPageBtnsForPageTop.vue'
import TheErrorCouldNotLoadHtmlEditor from './TheErrorCouldNotLoadHtmlEditor.vue'
import TheFooter from '@/components/TheFooter.vue'
import TheNavbar from '@/components/TheNavbar.vue'
import { defineAsyncComponent, onMounted, onUpdated, ref, watch } from 'vue'

import CmsManager from '@/managers/cms-manager'
import { useContentStore } from '@/stores/content-store'
import { usePageStore } from '@/stores/page-store'
import { useUserStore } from '@/stores/user-store'
import { ContentItemDoc } from '@shadowgames/gts-shared-models'

const TheHtmlEditor = defineAsyncComponent({
    loader: () => import('@/components/cms/TheHtmlEditor.vue'),
    loadingComponent: TheLoadingHtmlEditor,
    delay: 200,
    errorComponent: TheErrorCouldNotLoadHtmlEditor,
    timeout: 30000
})

</script>

</code>```

According to the answer of @domnantas here "TypeError: Failed to fetch dynamically imported module" on Vue/Vite vanilla setup,
asynchronous loading is problematic due to vite creating individual chunks of every contentItem that is being loaded on a single page.

In like 80% of the cases it leads to a "failed to fetch" error and in 20% of the time it works right way - which I think has to do with the dynamic loading of the contentItems. However this is awkward because a) when creating a "TheHtmlEditor" instance only the contentItemId is passed in, see the following editor component:

Snippet from "TheHtmlEditor.vue":

```<code>
<template>
...

        <div :style="editorStyles">
            <ckeditor
                :editor="editor"
                v-model="editorData"
                :config="editorConfig"
                @ready="onEditorReady"
                :readonly="editorDisabled"
                :disabled="editorDisabled"
            ></ckeditor>
        </div>

</template>

<script>

import '@ckeditor/ckeditor5-vue/dist/ckeditor.js'
import CKEditor from '@ckeditor/ckeditor5-vue'
import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor.js'
... // importing tons of other ckeditor plugins for every different feature of ckeditor...
import CmsManager from '@/managers/cms-manager'
import { useContentStore } from '@/stores/content-store'
import { usePageStore } from '@/stores/page-store'
import { useUserStore } from '@/stores/user-store'

export default {
    name: 'TheHtmlEditor',
    components: {
        ckeditor: CKEditor.component
    },
    props: {
        contentItemId: String
    },
    setup() {
        const contentStore = useContentStore()
        const userStore = useUserStore()
        const pageId = usePageStore().getCurrentPage.id
        console.log('(TheHtmlEditor:setup()) pageId = ', pageId)
        return { pageId, contentStore, userStore }
    },

    // ...

    data() {
        //console.log('In data(): Configuring editor...')
        return {
            contentItem: null,
            editor: ClassicEditor,
            editorData: '',
            editorConfig: { ... }
        }
    },

    created() {
        console.log('(TheHtmlEditor:created()) Trying to loadAndAssignContentItem with id', this.contentItemId)
        this.loadAndAssignContentItem(this.contentItemId)
        this.createInterval()
    },
    methods: {
        assignContentItemToLocalProp(contentItem) {
            this.contentItem = contentItem
        },
        loadAndAssignContentItem(contentItemId) {
            useContentStore()
                .getContentItem(contentItemId)
                .then((contentItem) => {
                    console.log('(TheHtmlEditor:loadAndAssignContentItem()) Loaded contentItem', contentItem)
                    this.assignContentItemToLocalProp(contentItem)
                    this.assignContentToEditor()
                })
                .catch((error) => {
                    console.error('Could not load contentItem. Error: ', error)
                })
        },
        // ...
     }
}
</script>
</code>```

... and b) as you can see, the loading happens in the created() lifecycle and should actually make the editor load the contentItem pull the data AFTER creation. However, when browsing to a page it seems both the async loading of the html editor AND the dynamic loading of a contentItem still occurs. Because: When commenting out the created() method the "failed fetch" error does not occur anymore.

So what would be the best approach to resolve this issue? Is there a way to prevent Vite from creating chunks for each and every single html editor? And what would need to be added to the vite.config.ts?

I haven't been able to get much of helpful information in the rollup documentation nor from threads like this: https://github.com/rollup/rollup/issues/2756

Any ideas are much appreciated.

Body:
We are using a CKEditor in a html editor (TheHtmlEditor.vue) that loads up 'contentItems' dynamically, depending on what content the user has stored at a given page previously.
However, revisiting that page at a later time, it fails loading randomly, due to loading errors of chunked imports:

GET https://gts.dev/node_modules/.vite/deps/@ckeditor_ckeditor5-typing_src_texttransformation__js.js?v=c9825b52 net::ERR_FAILED
runtime-core.esm-bundler.js:223

TypeError: Failed to fetch dynamically imported module: https://gts.dev/src/components/cms/TheHtmlEditor.vue
...
createNewEditorInstanceEntry @ TheCmsPage.vue:88

(anonymous) @ TheCmsPage.vue:187
TheHtmlEditor.vue:62

GET https://gts.dev/node_modules/.vite/deps/@ckeditor_ckeditor5-list_src_todolist.js?v=33cc3966 net::ERR_FAILED
TheHtmlEditor.vue:63

GET https://gts.dev/node_modules/.vite/deps/@ckeditor_ckeditor5-basic-styles_src_underline__js.js?v=e4b76b9d net::ERR_FAILED
TheHtmlEditor.vue:64

GET https://gts.dev/node_modules/.vite/deps/@ckeditor_ckeditor5-undo_src_undo__js.js?v=c361c7f7 net::ERR_FAILED

In our content management system "TheCmsPage.vue" is a placeholder page for all the dynamically created content items that the user has previously added on each different page.

The template of "TheCmsPage.vue" looks as follows:

<template>

        <TheNavbar />

            <TheCmsSubBar />

                        {{ pageStore.getCurrentPage?.path }}

                <TheEditCmsPageBtnsForPageTop
                    v-if="pageStore.getCurrentPage != null"
                    :pageId="pageStore.getCurrentPage.id.toString()"
                />

                    <TheHtmlEditor :contentItemId="componentInstance.contentItemId" />

                <TheButtonAddWysiwygEditor
                    v-if="pageStore.getCurrentPage != null"
                    :pageId="pageStore.getCurrentPage.id"
                    :buttonStyles="buttonStyles()"
                />

        <TheFooter />

</template>

According to the answer of @domnantas here "TypeError: Failed to fetch dynamically imported module" on Vue/Vite vanilla setup,
asynchronous loading is problematic due to vite creating individual chunks of every contentItem that is being loaded on a single page.

In like 80% of the cases it leads to a "failed to fetch" error and in 20% of the time it works right way - which I think has to do with the dynamic loading of the contentItems. However this is awkward because a) when creating a "TheHtmlEditor" instance only the contentItemId is passed in, see the following editor component:

Snippet from "TheHtmlEditor.vue":

<template>
...

            <ckeditor
                :editor="editor"
                v-model="editorData"
                :config="editorConfig"
                @ready="onEditorReady"
                :readonly="editorDisabled"
                :disabled="editorDisabled"
            ></ckeditor>

</template>

... and b) as you can see, the loading happens in the created() lifecycle and should actually make the editor load the contentItem pull the data AFTER creation. However, when browsing to a page it seems both the async loading of the html editor AND the dynamic loading of a contentItem still occurs. Because: When commenting out the created() method the "failed fetch" error does not occur anymore.

So what would be the best approach to resolve this issue? Is there a way to prevent Vite from creating chunks for each and every single html editor? And what would need to be added to the vite.config.ts?

I haven't been able to get much of helpful information in the rollup documentation nor from threads like this: https://github.com/rollup/rollup/issues/2756

Any ideas are much appreciated.


问:
Connection between R-Shiny and SQL
I'm a beginner and practicing R and SQL connection. I connected R shiny with a classicmodels database and got an 'unused argument' error in the parameter settings. I've looked up various references and done a lot of experimenting but I still can't get around the error. I hope to receive help from more skilled friends.

below is what my code and the shiny window look like

My shiny window

part of my ui.R script

```<code>fluidRow(
                tabBox(
                  height = "470px",
                  tabPanel(title = "Daily Sales",
                           sidebarLayout(
                             sidebarPanel(
                               selectInput(
                                 inputId = "prod_type",
                                 label = 'Product Type:',
                                 choices = prodtype$productLine,
                                 selected = '',
                                 width = "200px"
                                 ),
                               dateRangeInput(
                                     inputId = "date_range",
                                     label = "Date Range:",
                                     start = "2003-01-29",
                                     end = "2005-05-31",
                                     width = "200px"
                               ),
                               status="primary"
                             ),
                             mainPanel(
                               plotOutput(outputId = 'playChrt')
                             )
                           )
                  ),
</code>```

part of my server.R script

```<code>output$playChrt <- renderPlot(
    {rconn=dbConnect(MySQL(),user="root",
                     password="",
                     host="127.0.0.1",
                     dbname="classicmodels")

      d <- dbGetQuery(
        conn = rconn,
        statement =
          'SELECT productLine,
                  orderDate as day,
                  sum(quantityOrdered) as qty,
                  sum(buyPrice*qty) as sales
           FROM orders a
              LEFT JOIN orderdetails b ON a.orderNumber = b.orderNumber
              LEFT JOIN products c ON b.productCode = c.productCode
           WHERE productLine = ? and (@day BETWEEN ? AND ?)
           GROUP BY day
           ORDER BY day DESC',
        params = list(input$prod_type,
                      format(input$date_range[1], format="%Y-%m-%d"),
                      format(input$date_range[2], format="%Y-%m-%d"))
      )

      ggplot(data=d, aes(x = as.Date(day), y=sales)) +
        geom_col(size=1) +
        labs(x='Day', y='Sales Revenues ($)') +
        theme_minimal(base_size=16) +
        theme(axis.text.x=element_text(angle=60, hjust=1)) +
        theme(legend.position = 'none')
    }
  )
</code>```

Title: Connection between R-Shiny and SQL

Body:
I'm a beginner and practicing R and SQL connection. I connected R shiny with a classicmodels database and got an 'unused argument' error in the parameter settings. I've looked up various references and done a lot of experimenting but I still can't get around the error. I hope to receive help from more skilled friends.

below is what my code and the shiny window look like

My shiny window

part of my ui.R script

fluidRow(
                tabBox(
                  height = "470px",
                  tabPanel(title = "Daily Sales",
                           sidebarLayout(
                             sidebarPanel(
                               selectInput(
                                 inputId = "prod_type",
                                 label = 'Product Type:',
                                 choices = prodtype$productLine,
                                 selected = '',
                                 width = "200px"
                                 ),
                               dateRangeInput(
                                     inputId = "date_range",
                                     label = "Date Range:",
                                     start = "2003-01-29",
                                     end = "2005-05-31",
                                     width = "200px"
                               ),
                               status="primary"
                             ),
                             mainPanel(
                               plotOutput(outputId = 'playChrt')
                             )
                           )
                  ),

part of my server.R script

output$playChrt <- renderPlot(
    {rconn=dbConnect(MySQL(),user="root",
                     password="",
                     host="127.0.0.1",
                     dbname="classicmodels")

      d <- dbGetQuery(
        conn = rconn,
        statement =
          'SELECT productLine,
                  orderDate as day,
                  sum(quantityOrdered) as qty,
                  sum(buyPrice*qty) as sales
           FROM orders a
              LEFT JOIN orderdetails b ON a.orderNumber = b.orderNumber
              LEFT JOIN products c ON b.productCode = c.productCode
           WHERE productLine = ? and (@day BETWEEN ? AND ?)
           GROUP BY day
           ORDER BY day DESC',
        params = list(input$prod_type,
                      format(input$date_range[1], format="%Y-%m-%d"),
                      format(input$date_range[2], format="%Y-%m-%d"))
      )

      ggplot(data=d, aes(x = as.Date(day), y=sales)) +
        geom_col(size=1) +
        labs(x='Day', y='Sales Revenues ($)') +
        theme_minimal(base_size=16) +
        theme(axis.text.x=element_text(angle=60, hjust=1)) +
        theme(legend.position = 'none')
    }
  )


问:
Fetching remote refs has encountered a problem in eclipse IDE when push the project to github
When i am trying to push the project into Github shows an error "Fetching remote refs from git@github.com:MoreVilas/Git-Repo.git has encountered a problem. i don't recognise how to rectify the error.

enter image description here
Multiple trying to push the code. in Git-Bash i am finding the remote.origin.url
it was ok as same as my url.
I am earlier sended the projects on github.com but no error were there, that time what is the problem i could not find it out.
if any help.


问:
component not re rendering though it has got the updated state [REACT]
DESIGN

Parent component [p1] > Child component [c1] > Child component [c2] (issue here)

PROBLEM

One of my component is not re-rendering though updated state has reached the component. p1 has updated state and it is passed down to the c1 and then to c2. All of them are functional component

p1 has a initial state

```<code>state = {
 data1: value1,
 defaultColumn: true
}

// let's say state1
</code>```

and then after some service. After user some interaction, I am updating or creating the new state object with filter and map. so the object looks like below.

 state = {
 ...state,
 defaultColumn: false //updated
 }
 // let's say updatedState
 // these are updated with setState function of useState hook in p1. [state, setState]

Now this object is passed to c1 and c2. If I console log or debug, I can see the updated object in both, but c2 doesn't update. Sharing code snippet of c2 below for same.

component c2  (column manager) snippets, allcolumns is the state which is passed and I can see it has the latest state and updates the columns variable with in the component.

Now component is not re-rendered. While debugging the  loadFilterOptions, I see that it has the old state only that is state1 . This is quite confusing, why does it take the old state and why not the new state.

```<code>const ColumnManager = ({
  allColumns,
  setColumnOrder,
  hasColumnManagerOpen,
  openColumnManager,
  onCloseSaveColumnPrefs,
  setHiddenColumns
}) => {
  const [columns, setColumns] = useState(allColumns);
// ****************** HERE I AM GETTING NEW DATA ***************************************

const loadFilterOptions = columnData => {
    console.log('loadFilterOptions columnData',columnData);
    // ************ HERE I AM GETTING OLD DATA ***************************************

    return columnData.map((column, index) => {

      return (
        <Option
          draggable={isDraggable}
          onDragStart={() => handleDragStart(index)}
          onDrag={handleDraging}
          onDragEnd={handleDragEnd}
          onDragOver={e => e.preventDefault()}
          onDrop={() => handleDrop(index)}
          key={`${column.id}${index}`}
        >
          <Icon iconName="ic-sixdots-move" />
          <input
            type="checkbox"
            {...column.getToggleHiddenProps()}
            checked={column.defaultColumn}
            disabled={(column && column.strict) || false}
            value={column.id}
            onClick={onColumnSelected}
          />
          <span>{column.label}</span>
        </Option>
      );
    });
  };

  return (
    <ColumnManagerContainer>
      <Popup
        placement="bottom-end"
        isOpen={hasColumnManagerOpen}
        onToggle={openColumnManager}
        content={() => (
          <OptionsContainer data-testid="option">
            <ResetTxtContainer data-testid="button-reset" onClick={handleReset}>
              Reset
            </ResetTxtContainer>
            <Separator />
            <div className="custom-scroll">{loadFilterOptions(columns)}</div>
          </OptionsContainer>
        )}
      >
        {() => <Fragment />}
      </Popup>
    </ColumnManagerContainer>
  );
};
</code>```

Things tried

div is used while calling the 'loadFilteroptions'.

Assumption was while converting the div in virtual dom, somewhere state was lost. Changing it to fragment didn't help

Every time I pass data to child component, I did deepclone using the loadash library.
Assumption was some somewhere it was pointing to old reference. This didn't help too.

With map and filter a new object is created every time, so it will create a new reference.

Result
Always pointed to old object i.e, state as per example

Expectation
it should take the latest state instead of pointing to the old state. that is updatedState as per example

Body:
DESIGN

Parent component [p1] > Child component [c1] > Child component [c2] (issue here)

PROBLEM

One of my component is not re-rendering though updated state has reached the component. p1 has updated state and it is passed down to the c1 and then to c2. All of them are functional component

p1 has a initial state

state = {
 data1: value1,
 defaultColumn: true
}

// let's say state1

and then after some service. After user some interaction, I am updating or creating the new state object with filter and map. so the object looks like below.

 state = {
 ...state,
 defaultColumn: false //updated
 }
 // let's say updatedState
 // these are updated with setState function of useState hook in p1. [state, setState]

Now this object is passed to c1 and c2. If I console log or debug, I can see the updated object in both, but c2 doesn't update. Sharing code snippet of c2 below for same.

component c2  (column manager) snippets, allcolumns is the state which is passed and I can see it has the latest state and updates the columns variable with in the component.

Now component is not re-rendered. While debugging the  loadFilterOptions, I see that it has the old state only that is state1 . This is quite confusing, why does it take the old state and why not the new state.

const ColumnManager = ({
  allColumns,
  setColumnOrder,
  hasColumnManagerOpen,
  openColumnManager,
  onCloseSaveColumnPrefs,
  setHiddenColumns
}) => {
  const [columns, setColumns] = useState(allColumns);
// ****************** HERE I AM GETTING NEW DATA ***************************************

const loadFilterOptions = columnData => {
    console.log('loadFilterOptions columnData',columnData);
    // ************ HERE I AM GETTING OLD DATA ***************************************

    return columnData.map((column, index) => {

      return (
        <Option
          draggable={isDraggable}
          onDragStart={() => handleDragStart(index)}
          onDrag={handleDraging}
          onDragEnd={handleDragEnd}
          onDragOver={e => e.preventDefault()}
          onDrop={() => handleDrop(index)}
          key={`${column.id}${index}`}
        >
          <Icon iconName="ic-sixdots-move" />
          <input
            type="checkbox"
            {...column.getToggleHiddenProps()}
            checked={column.defaultColumn}
            disabled={(column && column.strict) || false}
            value={column.id}
            onClick={onColumnSelected}
          />
          {column.label}
        </Option>
      );
    });
  };

  return (
    <ColumnManagerContainer>
      <Popup
        placement="bottom-end"
        isOpen={hasColumnManagerOpen}
        onToggle={openColumnManager}
        content={() => (
          <OptionsContainer data-testid="option">
            <ResetTxtContainer data-testid="button-reset" onClick={handleReset}>
              Reset
            </ResetTxtContainer>
            <Separator />

{loadFilterOptions(columns)}

          </OptionsContainer>
        )}
      >
        {() => <Fragment />}
      </Popup>
    </ColumnManagerContainer>
  );
};

Things tried

div is used while calling the 'loadFilteroptions'.

Assumption was while converting the div in virtual dom, somewhere state was lost. Changing it to fragment didn't help

Every time I pass data to child component, I did deepclone using the loadash library.
Assumption was some somewhere it was pointing to old reference. This didn't help too.

With map and filter a new object is created every time, so it will create a new reference.

Result
Always pointed to old object i.e, state as per example

Expectation
it should take the latest state instead of pointing to the old state. that is updatedState as per example


问:
Sveltekit start.js is outside of Vite serving allow list
I created a fresh project with svelte, using the commandline

```<code>npm create svelte@latest my-app
</code>```

When running npm run dev it results into an error saying

The request url "[path_to_workspace]/node_modules/@sveltejs/kit/src/runtime/client/start.js" is outside of Vite serving allow list.

I tried solutions suggested in other answers, but nothing helps.
I tried the following:

Adding ['..'] to the server.fs.allow inside the vite.config.js

```<code>import { sveltekit } from '@sveltejs/kit/vite';

/** @type {import('vite').UserConfig} */
const config = {
    plugins: [sveltekit()],
    server: {
        fs: {
            // Allow serving files from one level up to the project root
            allow: ['..'],
        },
    },
};

export default config;
</code>```

Doesn't help, error stays exacly as is.

Adding the workspace directory inside the server.fs.allow works, but shows a different error.

```<code>import { sveltekit } from '@sveltejs/kit/vite';

/** @type {import('vite').UserConfig} */
const config = {
    plugins: [sveltekit()],
    server: {
        fs: {
            // Allow serving files from one level up to the project root
            allow: ['C:/Users/Richa/Local Sites/pyro_db'],
        },
    },
};

export default config;
</code>```

The error now is:

14:17:40 [vite] Internal server error: Failed to resolve import "../../../../../../Local Sites/pyro_db/node_modules/@sveltejs/kit/src/runtime/components/error.svelte" from "......\Local Sites\pyro_db.svelte-kit\generated\nodes\1.js". Does the file exist?

Anybody knows how to resolve this?

Body:
I created a fresh project with svelte, using the commandline

npm create svelte@latest my-app

When running npm run dev it results into an error saying

The request url "[path_to_workspace]/node_modules/@sveltejs/kit/src/runtime/client/start.js" is outside of Vite serving allow list.

I tried solutions suggested in other answers, but nothing helps.
I tried the following:

Adding ['..'] to the server.fs.allow inside the vite.config.js

import { sveltekit } from '@sveltejs/kit/vite';

/** @type {import('vite').UserConfig} */
const config = {
    plugins: [sveltekit()],
    server: {
        fs: {
            // Allow serving files from one level up to the project root
            allow: ['..'],
        },
    },
};

export default config;

Doesn't help, error stays exacly as is.

Adding the workspace directory inside the server.fs.allow works, but shows a different error.

import { sveltekit } from '@sveltejs/kit/vite';

/** @type {import('vite').UserConfig} */
const config = {
    plugins: [sveltekit()],
    server: {
        fs: {
            // Allow serving files from one level up to the project root
            allow: ['C:/Users/Richa/Local Sites/pyro_db'],
        },
    },
};

export default config;

The error now is:

14:17:40 [vite] Internal server error: Failed to resolve import "../../../../../../Local Sites/pyro_db/node_modules/@sveltejs/kit/src/runtime/components/error.svelte" from "......\Local Sites\pyro_db.svelte-kit\generated\nodes\1.js". Does the file exist?

Anybody knows how to resolve this?


问:
Join Lines isn't working with prettier in VS code
So I am trying to convert multiple line of code into one single code, when I use Join Lines it converts it one line ,but when i am saving with Ctrl + s to save code, prettier converts it as it was before. even so i changed settings: print Width to 150. but it's not working anyway...

any ideas how to fix it?


问:
Typescript not applied to files for my NPM module
I've written an NPM module which I install in an app. However I get an error that suggests that Typescript isn't being applied to the .ts files in the NPM. When I run the NPM as its own app it works fine.

The line in question assigns a type to a const:

```<code>const usersService: UsersService = new UsersService()
</code>```

Here's the error I get:

```<code>Module parse failed: Unexpected token (5:14)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
</code>```

The app the NPM is installed to has its own .ts files which work fine.

Body:
I've written an NPM module which I install in an app. However I get an error that suggests that Typescript isn't being applied to the .ts files in the NPM. When I run the NPM as its own app it works fine.

The line in question assigns a type to a const:

const usersService: UsersService = new UsersService()

Here's the error I get:

Module parse failed: Unexpected token (5:14)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

The app the NPM is installed to has its own .ts files which work fine.


问:
How to affect other elements when one element is hovered in JSX
I have the following structure:

      DIV_1

      DIV_2

```

I'm trying to change the width of DIV_1 when DIV_2 is hovered over. I've seen many solutions that involve setting a state and using onMouseEnter, onMouseLeave but that solution doesn't work well for my project.

I've seen how to solve this using css and was wondering how I can do the same thing with JSX styling?

Note: DIV_1 and DIV_2 do not share a direct parent. I need to be able to access either the parent of DIV_2 or DIV_2 itself from DIV_1.

Body:
I have the following structure:

      DIV_1

      DIV_2

I'm trying to change the width of DIV_1 when DIV_2 is hovered over. I've seen many solutions that involve setting a state and using onMouseEnter, onMouseLeave but that solution doesn't work well for my project.

I've seen how to solve this using css and was wondering how I can do the same thing with JSX styling?

Note: DIV_1 and DIV_2 do not share a direct parent. I need to be able to access either the parent of DIV_2 or DIV_2 itself from DIV_1.