问:
eslint failed to load plugin 'import' declared in '.eslintrc.js » eslint-config-airbnb; cannot find module 'typescript/package.json'
I'm trying to set up eslint for a basic React project (Javascript only, no Typescript). When linting my project with npx eslint ./, I get the following error:

```<code>ESLint: 8.31.0

Error: Failed to load plugin 'import' declared in '.eslintrc.js »
eslint-config-airbnb » /Users/me/project/node_modules/eslint-config-airbnb-base/index.js »
/Users/me/project/node_modules/eslint-config-airbnb-base/rules/imports.js':
Cannot find module 'typescript/package.json'
</code>```

I'm not really sure what's going on here, as my project doesn't use any Typescript. Some additional information that might help:

I followed this tutorial to set up eslint, prettier, and editorconfig for working in a team environment.

Here is my .eslintrc.js file:

```<code>module.exports = {
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
    "plugin:react/recommended",
    "airbnb",
    'prettier'
    ],
    "overrides": [
    ],
    "parserOptions": {
        "ecmaVersion": "latest",
    "sourceType": "module"
    },
    "plugins": [
    "react"
    ],
    "rules": {
    "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
    }
}
</code>```

I do have a .eslintignore file in the root directory of my project that contains node_modules.

Here is my package.json:

```<code>{
  "name": "project",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@fontsource/roboto": "^4.5.8",
    "@mui/material": "^5.11.4",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.2.2",
    "firebase": "^9.15.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-firebaseui": "^6.0.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",
    "lint": "npx eslint ./",
    "format": "npx prettier --write ."
  },
  "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"
    ]
  },
  "devDependencies": {
    "eslint": "^8.31.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-prettier": "^8.6.0",
    "eslint-plugin-import": "^2.27.0",
    "eslint-plugin-jsx-a11y": "^6.7.0",
    "eslint-plugin-react": "^7.32.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "prettier": "2.8.2"
  }
}
</code>```

Finally here is my file tree:

```<code>.vscode
node_modules
public
src
.editorconfig
.eslintignore
.eslintrc.js
.gitignore
.prettierignore
.prettierrc.json
package-lock.json
package.json
README.md
</code>```

I found a somewhat questionable solution by installing typescript related packages for eslint:

```<code>npm install typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
</code>```

After installing these packages, npx eslint ./ works fine, but I don't think I should need to install typescript-related plugins/parsers for eslint when my project doesn't use typescript and I set eslint to ignore the node_modules folder. I'm also unsure how installing these packages might affect the linting behavior (I didn't make any changes to .eslintrc.js or any other config files after installing those packages).

Does anyone know of a better solution that doesn't involve installing these additional packages? Or are these packages actually necessary despite my project not using Typescript?

Thank you in advance for the help!

Body:
I'm trying to set up eslint for a basic React project (Javascript only, no Typescript). When linting my project with npx eslint ./, I get the following error:

ESLint: 8.31.0

Error: Failed to load plugin 'import' declared in '.eslintrc.js »
eslint-config-airbnb » /Users/me/project/node_modules/eslint-config-airbnb-base/index.js »
/Users/me/project/node_modules/eslint-config-airbnb-base/rules/imports.js':
Cannot find module 'typescript/package.json'

I'm not really sure what's going on here, as my project doesn't use any Typescript. Some additional information that might help:

I followed this tutorial to set up eslint, prettier, and editorconfig for working in a team environment.

Here is my .eslintrc.js file:

module.exports = {
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
    "plugin:react/recommended",
    "airbnb",
    'prettier'
    ],
    "overrides": [
    ],
    "parserOptions": {
        "ecmaVersion": "latest",
    "sourceType": "module"
    },
    "plugins": [
    "react"
    ],
    "rules": {
    "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
    }
}

I do have a .eslintignore file in the root directory of my project that contains node_modules.

Here is my package.json:

{
  "name": "project",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@fontsource/roboto": "^4.5.8",
    "@mui/material": "^5.11.4",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.2.2",
    "firebase": "^9.15.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-firebaseui": "^6.0.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",
    "lint": "npx eslint ./",
    "format": "npx prettier --write ."
  },
  "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"
    ]
  },
  "devDependencies": {
    "eslint": "^8.31.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-prettier": "^8.6.0",
    "eslint-plugin-import": "^2.27.0",
    "eslint-plugin-jsx-a11y": "^6.7.0",
    "eslint-plugin-react": "^7.32.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "prettier": "2.8.2"
  }
}

Finally here is my file tree:

.vscode
node_modules
public
src
.editorconfig
.eslintignore
.eslintrc.js
.gitignore
.prettierignore
.prettierrc.json
package-lock.json
package.json
README.md

I found a somewhat questionable solution by installing typescript related packages for eslint:

npm install typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

After installing these packages, npx eslint ./ works fine, but I don't think I should need to install typescript-related plugins/parsers for eslint when my project doesn't use typescript and I set eslint to ignore the node_modules folder. I'm also unsure how installing these packages might affect the linting behavior (I didn't make any changes to .eslintrc.js or any other config files after installing those packages).

Does anyone know of a better solution that doesn't involve installing these additional packages? Or are these packages actually necessary despite my project not using Typescript?

Thank you in advance for the help!


来源: stackexchange

问:
How to pass async data from host activity to child fragments
I've an host activity with 4 tabs, one fragment for each tab.

In the host activity I collect the user's location through FusedLocationProviderClient.

I want to pass that location to the child fragments.

It seems that I've to use a ViewModel like:

class LocationViewModel : ViewModel() {
    lateinit var location: Location
}
```
<p>How can I inform the fragments when the <code>location</code> has been set by the host Activity?
Thanks.</p>
<h2>EDIT - Solution</h2>
<p>Using <code>MutableLiveData</code> as suggested did the trick.</p>
```class LocationViewModel : ViewModel()
{
    private val mutableLiveLocation = MutableLiveData<Location>()
    val liveLocation: LiveData<Location> get() = mutableLiveLocation

    fun setLocation(location: Location)
    {
        mutableLiveLocation.value = location
    }
}
```

ContentLicense: CC BY-SA 4.0

Body:
I've an host activity with 4 tabs, one fragment for each tab.

In the host activity I collect the user's location through FusedLocationProviderClient.

I want to pass that location to the child fragments.

It seems that I've to use a ViewModel like:

class LocationViewModel : ViewModel() {
    lateinit var location: Location
}

How can I inform the fragments when the location has been set by the host Activity?
Thanks.

EDIT - Solution

Using MutableLiveData as suggested did the trick.

class LocationViewModel : ViewModel()
{
    private val mutableLiveLocation = MutableLiveData<Location>()
    val liveLocation: LiveData<Location> get() = mutableLiveLocation

    fun setLocation(location: Location)
    {
        mutableLiveLocation.value = location
    }
}


问:
Changing the underlying pointer type of a Singleton
I have a singleton class B which contains a certain method RunTimer() that I'd like to unit test which is a wrapper around an external utility. For unit test, I want to exclude the testing of the timer and rely on other parameters (not shown here)

Fake is what I'd use in unit test which will contain additional ways for the sake of testing.

Since there's only ever a single instance of a Singleton, does the idea of switching out the std::unique_ptr<ITimer> _ptr for Fake in unit test make sense for the sake of testing?

```<code>class ITimer
{
    public:
    virtual void foo() = 0;
    virtual ~Base() = default;
};

class Real : public ITimer
{
    public:
    void foo() override {}
};

// For unit test
class Fake : public ITimer
{
    public:
    void foo() override {}
};

class B
{
    std::unique_ptr<ITimer> _ptr;

    // default ctor creates a Real
    B() : B(std::make_unique<Real>())
    {

    }

    B(std::unique_ptr<ITimer> ptr) : _ptr(std::move(ptr))
    {

    }

    public:
    static B& get()
    {
        static B b;
        return b;
    }

    void RunTimer()
    {
       Timer::Run(); // external utility
    }

    void change(std::unique_ptr<Base> ptr)
    {
        _ptr = std::move(ptr);
    }
};

int main()
{
    B::get();       // use Real in actual code

    // use Fake - for testing (eventually to be in TEST_F())
    auto mk = std::make_unique<Fake>();
    B::get().change(std::move(mk));
    // do testing on B::_ptr
}
</code>```

Body:
I have a singleton class B which contains a certain method RunTimer() that I'd like to unit test which is a wrapper around an external utility. For unit test, I want to exclude the testing of the timer and rely on other parameters (not shown here)

Fake is what I'd use in unit test which will contain additional ways for the sake of testing.

Since there's only ever a single instance of a Singleton, does the idea of switching out the std::unique_ptr<ITimer> _ptr for Fake in unit test make sense for the sake of testing?

class ITimer
{
    public:
    virtual void foo() = 0;
    virtual ~Base() = default;
};

class Real : public ITimer
{
    public:
    void foo() override {}
};

// For unit test
class Fake : public ITimer
{
    public:
    void foo() override {}
};

class B
{
    std::unique_ptr<ITimer> _ptr;

    // default ctor creates a Real
    B() : B(std::make_unique<Real>())
    {

    }

    B(std::unique_ptr<ITimer> ptr) : _ptr(std::move(ptr))
    {

    }

    public:
    static B& get()
    {
        static B b;
        return b;
    }

    void RunTimer()
    {
       Timer::Run(); // external utility
    }

    void change(std::unique_ptr<Base> ptr)
    {
        _ptr = std::move(ptr);
    }
};

int main()
{
    B::get();       // use Real in actual code

    // use Fake - for testing (eventually to be in TEST_F())
    auto mk = std::make_unique<Fake>();
    B::get().change(std::move(mk));
    // do testing on B::_ptr
}


问:
Base64 PDF as source as Iframe results in blank Iframe loaded in Chrome/Edge but not Firefox
I am trying to display a base64-encoded PDF as a string in an iframe but when I load it in Chrome or Edge, a blank page is displayed. When I load the string in Firefox, it displays the PDF in the default Firefox PDF viewer.

The content itself is in the form: .

I saw that there might be a length limitation on the data field for iframes in Chrome/Edge but not in Firefox. Some of my strings contain over 2 MB of data or maybe over 2000 characters in the string. However, I am not sure if that is an actual limitation.

I do know that there may be a solution using blobs, but I am working in .NET and am returning a ContentResult.

Any ideas?

References:

https://stackoverflow.com/a/58500450/19831782

https://stackoverflow.com/a/417184/19831782


问:
Should Service A be dependent on service B or abstract the logic in a fat client
This is a system design/architecture question around setting up 2 TIER 0 services - Service A & Service B.

Service A depends on service B for additional information to return a more accurate response. I have 2 options here:

Service A internally calls Service B for this additional information. So clients of service A use a thin client library.

Clients of service A provide this additional information in the request to Service A. Maybe by hiding the logic to call Service B before calling Service A in the client.

Features of Option 1

Client library for Service A is a thin client with no logic.

Failure and latency of Service A are tied to service B.

Sending a request to Service A is a one-stop solution for the entire request.

Features of Option 2

Client library for Service A has to have some logic to get all the request arguments from Service B before sending the request to Service A.

Failures of Service A and Service B are independent and easier to reason about.

Service A is no longer a one-stop solution for a detailed, accurate response.

Sample API for service A:

```<code>// Returns true if any of the user in the list can perform the |action| on the |resource|.
isAllowed(User[], Action, Resource): Boolean
</code>```

Sample API for service B:

```<code>// Returns all the relatives for the provided list of users
getRelatives(User[]): User[]
</code>```

Option 1

Now should the service A look like:

```<code>// Client for Service A:
class clientA {
  isAllowed(User[] users, Action action, Resource res): Boolean = {
    return ServiceA.isAllowed(users, action, res)
  }
}

// Service A implementation
class ServiceA {
  isAllowed(User[] users, Action action, Resource res): Boolean = {
    allUsers = ServiceB.getRelatives(users) + users

    return allUsers.any(user => res.canPerform(action, user))
}
</code>```

Option 2

or should it look like:

```<code>// Client for Service A:
class clientA {
  isAllowed(User[] users, Action action, Resource res): Boolean = {
    allUsers = ServiceB.getRelatives(users) + users
    return ServiceA.isAllowed(allUsers, action, res)
  }
}

// Service A implementation
class ServiceA {
  isAllowed(User[] users, Action action, Resource res): Boolean = {
    allUsers = ServiceB.getRelatives(users) + users

    return allUsers.any(user => res.canPerform(action, user))
 }
}
</code>```

Question:

What are the benefits of one approach over the other?

When should one pick one option over the other?

Body:
This is a system design/architecture question around setting up 2 TIER 0 services - Service A & Service B.

Service A depends on service B for additional information to return a more accurate response. I have 2 options here:

Service A internally calls Service B for this additional information. So clients of service A use a thin client library.

Clients of service A provide this additional information in the request to Service A. Maybe by hiding the logic to call Service B before calling Service A in the client.

Features of Option 1

Client library for Service A is a thin client with no logic.

Failure and latency of Service A are tied to service B.

Sending a request to Service A is a one-stop solution for the entire request.

Features of Option 2

Client library for Service A has to have some logic to get all the request arguments from Service B before sending the request to Service A.

Failures of Service A and Service B are independent and easier to reason about.

Service A is no longer a one-stop solution for a detailed, accurate response.

Sample API for service A:

// Returns true if any of the user in the list can perform the |action| on the |resource|.
isAllowed(User[], Action, Resource): Boolean

Sample API for service B:

// Returns all the relatives for the provided list of users
getRelatives(User[]): User[]

Option 1

Now should the service A look like:

// Client for Service A:
class clientA {
  isAllowed(User[] users, Action action, Resource res): Boolean = {
    return ServiceA.isAllowed(users, action, res)
  }
}

// Service A implementation
class ServiceA {
  isAllowed(User[] users, Action action, Resource res): Boolean = {
    allUsers = ServiceB.getRelatives(users) + users

    return allUsers.any(user => res.canPerform(action, user))
}

Option 2

or should it look like:

// Client for Service A:
class clientA {
  isAllowed(User[] users, Action action, Resource res): Boolean = {
    allUsers = ServiceB.getRelatives(users) + users
    return ServiceA.isAllowed(allUsers, action, res)
  }
}

// Service A implementation
class ServiceA {
  isAllowed(User[] users, Action action, Resource res): Boolean = {
    allUsers = ServiceB.getRelatives(users) + users

    return allUsers.any(user => res.canPerform(action, user))
 }
}

Question:

What are the benefits of one approach over the other?

When should one pick one option over the other?


问:
dlfcn is not linked by cgo
I'm working on Go code that invokes C, and this is the current set up.

build system: bazel with cgo

C code calls dlsym()

added // #cgo LDFLAGS: -ldl in Go code above the line import "C"

Added #include <dlfcn.h> in C code

execution command with verbose_failures enabled and it looks like LDFLAGS -ldl is not set.

```<code>cd /usr/local/home/<REMOVED> && \
  exec env - \
    CGO_ENABLED=1 \
    GOARCH=amd64 \
    GOOS=linux \
    GOPATH='' \
    GOROOT=bazel-out/k8-fastbuild-ST-03006dd95b75/bin/external/io_bazel_rules_go/stdlib_ \
    GOROOT_FINAL=GOROOT \
    PATH=external/llvm_toolchain/bin:/bin:/usr/bin \
  bazel-out/k8-opt-exec-3CAA6C3F-ST-f279a0ffb7f5/bin/external/go_sdk/builder '-param=bazel-out/k8-fastbuild-ST-4a519fd6d3e4/bin/scanner/<REMOVED>.params' -- -extld external/llvm_toolchain/bin/cc_wrapper.sh -race '-buildid=redacted' -extldflags '--target=x86_64-unknown-linux-gnu -lm -no-canonical-prefixes -fuse-ld=lld -Wl,--build-id=md5 -Wl,--hash-style=gnu -Wl,-z,relro,-z,now -l:libstdc++.a --sysroot=external/debian_bullseye_sysroot'
</code>```

build error:

```<code>external/go_sdk/pkg/tool/linux_amd64/link: running external/llvm_toolchain/bin/cc_wrapper.sh failed: exit status 1
ld.lld: error: undefined symbol: dlsym
</code>```

How can I fix the missing dependency dlfcn / dlsym() with cgo? Thanks!

Title: dlfcn is not linked by cgo

Body:
I'm working on Go code that invokes C, and this is the current set up.

build system: bazel with cgo

C code calls dlsym()

added // #cgo LDFLAGS: -ldl in Go code above the line import "C"

Added #include <dlfcn.h> in C code

execution command with verbose_failures enabled and it looks like LDFLAGS -ldl is not set.

cd /usr/local/home/<REMOVED> && \
  exec env - \
    CGO_ENABLED=1 \
    GOARCH=amd64 \
    GOOS=linux \
    GOPATH='' \
    GOROOT=bazel-out/k8-fastbuild-ST-03006dd95b75/bin/external/io_bazel_rules_go/stdlib_ \
    GOROOT_FINAL=GOROOT \
    PATH=external/llvm_toolchain/bin:/bin:/usr/bin \
  bazel-out/k8-opt-exec-3CAA6C3F-ST-f279a0ffb7f5/bin/external/go_sdk/builder '-param=bazel-out/k8-fastbuild-ST-4a519fd6d3e4/bin/scanner/<REMOVED>.params' -- -extld external/llvm_toolchain/bin/cc_wrapper.sh -race '-buildid=redacted' -extldflags '--target=x86_64-unknown-linux-gnu -lm -no-canonical-prefixes -fuse-ld=lld -Wl,--build-id=md5 -Wl,--hash-style=gnu -Wl,-z,relro,-z,now -l:libstdc++.a --sysroot=external/debian_bullseye_sysroot'

build error:

external/go_sdk/pkg/tool/linux_amd64/link: running external/llvm_toolchain/bin/cc_wrapper.sh failed: exit status 1
ld.lld: error: undefined symbol: dlsym

How can I fix the missing dependency dlfcn / dlsym() with cgo? Thanks!


问:
Do I need to connect AudioListener to AudioDestinationNode?
Im working on spatial audio for a project. Im trying to figure out the correct way to use AudioListener and AudioDestinationNode. I don't have my dev machine available, so I can't test and brute-force to find out, so what is the proper way to connect all this?

AudioListener says it's not an Audio node. And I can't find the documentation for this specific issue


问:
Rust rocket.rs not launching properly in Docker Container
I'm trying to build a docker image of a Rocket application. I've followed the rust docker documentation to make an image with a builder, but the resulting container wont launch the application.

Dockerfile

```<code>FROM rust:latest as builder

COPY ./id_rsa* /root/.ssh/
RUN chmod 600 /root/.ssh/id_rsa
RUN git config --global user.name "Runner"
RUN git config --global user.email "some@email.com"
RUN ssh-keyscan -t rsa gitlab.com >> ~/.ssh/known_hosts

RUN rustup default nightly

WORKDIR /usr/src/api
COPY ./api .

VOLUME /redis

RUN cargo install --path .

# ---

FROM debian:buster

ENV ROCKET_DATABASES={redis={url="redis://redis:6379/"}}
COPY --from=builder /usr/local/cargo/bin/api /usr/local/bin/api

EXPOSE 8000
CMD api
</code>```

This is the dockerfile I expect to work, but instead results in a 'hanging' container. To be more percise the container runs with no console output.

I have connected to the resulting container and verified that the executable is being copied over properly and that it runs as expected in the container's shell. I can even get it to launch properly by removing the second stage, but this isn't ideal as it leaves SSH keys in the container.

Working Dockerfile

```<code>FROM rust:latest as builder

COPY ./id_rsa* /root/.ssh/
RUN chmod 600 /root/.ssh/id_rsa
RUN git config --global user.name "Runner"
RUN git config --global user.email "some@email.com"
RUN ssh-keyscan -t rsa gitlab.com >> ~/.ssh/known_hosts

RUN rustup default nightly

WORKDIR /usr/src/api
COPY ./api .

VOLUME /redis

RUN cargo install --path .

CMD /usr/local/cargo/bin/api
</code>```

Body:
I'm trying to build a docker image of a Rocket application. I've followed the rust docker documentation to make an image with a builder, but the resulting container wont launch the application.

Dockerfile

FROM rust:latest as builder

COPY ./id_rsa* /root/.ssh/
RUN chmod 600 /root/.ssh/id_rsa
RUN git config --global user.name "Runner"
RUN git config --global user.email "some@email.com"
RUN ssh-keyscan -t rsa gitlab.com >> ~/.ssh/known_hosts

RUN rustup default nightly

WORKDIR /usr/src/api
COPY ./api .

VOLUME /redis

RUN cargo install --path .

# ---

FROM debian:buster

ENV ROCKET_DATABASES={redis={url="redis://redis:6379/"}}
COPY --from=builder /usr/local/cargo/bin/api /usr/local/bin/api

EXPOSE 8000
CMD api

This is the dockerfile I expect to work, but instead results in a 'hanging' container. To be more percise the container runs with no console output.

I have connected to the resulting container and verified that the executable is being copied over properly and that it runs as expected in the container's shell. I can even get it to launch properly by removing the second stage, but this isn't ideal as it leaves SSH keys in the container.

Working Dockerfile

FROM rust:latest as builder

COPY ./id_rsa* /root/.ssh/
RUN chmod 600 /root/.ssh/id_rsa
RUN git config --global user.name "Runner"
RUN git config --global user.email "some@email.com"
RUN ssh-keyscan -t rsa gitlab.com >> ~/.ssh/known_hosts

RUN rustup default nightly

WORKDIR /usr/src/api
COPY ./api .

VOLUME /redis

RUN cargo install --path .

CMD /usr/local/cargo/bin/api


问:
Python website login presents same login form upon clicking login
I'm at a total loss here. I'm using python to open Edge, enter a user name and password, and then click Log In. I'm not getting any errors.

However, upon clicking login, the login form loads a second time. Now the page displays as an empty login form on top and then the login form I just entered at the bottom.

Basically, hitting Login causes the login form to just load a second time on top of the already completed login form. Below is my code. Any ideas?

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
import login_details
import time

username = login_details.username
password = login_details.password

driver = webdriver.Edge()

driver.get("name_of_website")
driver.maximize_window()

driver.find_element(By.ID, "txtUserId").send_keys(username)
driver.find_element(By.ID, "txtPassword").send_keys(password)

driver.find_element(By.XPATH,"//*[@id=\"btnLogIn\"]").click()
</code>```

Body:
I'm at a total loss here. I'm using python to open Edge, enter a user name and password, and then click Log In. I'm not getting any errors.

However, upon clicking login, the login form loads a second time. Now the page displays as an empty login form on top and then the login form I just entered at the bottom.

Basically, hitting Login causes the login form to just load a second time on top of the already completed login form. Below is my code. Any ideas?

from selenium import webdriver
from selenium.webdriver.common.by import By
import login_details
import time

username = login_details.username
password = login_details.password

driver = webdriver.Edge()

driver.get("name_of_website")
driver.maximize_window()

driver.find_element(By.ID, "txtUserId").send_keys(username)
driver.find_element(By.ID, "txtPassword").send_keys(password)

driver.find_element(By.XPATH,"//*[@id=\"btnLogIn\"]").click()


问:
Add the installation prefix of "Qt5OpenCV" to CMAKE_PREFIX_PATH or set "Qt5OpenCV_DIR" to a directory containing one of the above files
It is normal when qt5 and opencv are running separately.

Now I want to use OpenCV in Qt5, When building, I got the following error, I can't find relevant solutions online
.

```<code>CMake Error at /opt/Qt5.13.0/5.13.0/gcc_64/lib/cmake/Qt5/Qt5Config.cmake:28 (find_package):

  Could not find a package configuration file provided by "Qt5OpenCV" with
  any of the following names:

    Qt5OpenCVConfig.cmake
    qt5opencv-config.cmake

  Add the installation prefix of "Qt5OpenCV" to CMAKE_PREFIX_PATH or set
  "Qt5OpenCV_DIR" to a directory containing one of the above files.  If
  "Qt5OpenCV" provides a separate development package or SDK, be sure it has
  been installed.
Call Stack (most recent call first):
</code>```

This is the compilation command of my opencv.

```<code>cmake -D CMAKE_BUILD_TYPE=RELEASE -D WITH_QT=ON -D WITH_GTK=ON ../opencv-4.7.0
make && make install
</code>```

My CMakeLists.txt

```<code>set(CMAKE_PREFIX_PATH "/opt/Qt5.13.0/5.13.0/gcc_64/")

#I think this directory should be included, but I don't know where it is.
set(CMAKE_PREFIX_PATH "Qt5OpenCV")

find_package(Qt5
    COMPONENTS
    Core
    Quick
    OpenCV
    REQUIRED)

include_directories(${OpenCV_INCLUDE_DIRS})

add_executable(${PROJECT_NAME} "src/main.cpp" "qml/qml.qrc")

link_directories(${OpenCV_LIBRARY_DIRS})

target_link_libraries(${PROJECT_NAME}
    PRIVATE
    Qt5::Core
    Qt5::Quick
    ${OpenCV_LIBS}
    )
</code>```

My system is Ubuntu22.10

I hope everything is normal.

Body:
It is normal when qt5 and opencv are running separately.

Now I want to use OpenCV in Qt5, When building, I got the following error, I can't find relevant solutions online
.

CMake Error at /opt/Qt5.13.0/5.13.0/gcc_64/lib/cmake/Qt5/Qt5Config.cmake:28 (find_package):

  Could not find a package configuration file provided by "Qt5OpenCV" with
  any of the following names:

    Qt5OpenCVConfig.cmake
    qt5opencv-config.cmake

  Add the installation prefix of "Qt5OpenCV" to CMAKE_PREFIX_PATH or set
  "Qt5OpenCV_DIR" to a directory containing one of the above files.  If
  "Qt5OpenCV" provides a separate development package or SDK, be sure it has
  been installed.
Call Stack (most recent call first):

This is the compilation command of my opencv.

cmake -D CMAKE_BUILD_TYPE=RELEASE -D WITH_QT=ON -D WITH_GTK=ON ../opencv-4.7.0
make && make install

My CMakeLists.txt

set(CMAKE_PREFIX_PATH "/opt/Qt5.13.0/5.13.0/gcc_64/")

#I think this directory should be included, but I don't know where it is.
set(CMAKE_PREFIX_PATH "Qt5OpenCV")

find_package(Qt5
    COMPONENTS
    Core
    Quick
    OpenCV
    REQUIRED)

include_directories(${OpenCV_INCLUDE_DIRS})

add_executable(${PROJECT_NAME} "src/main.cpp" "qml/qml.qrc")

link_directories(${OpenCV_LIBRARY_DIRS})

target_link_libraries(${PROJECT_NAME}
    PRIVATE
    Qt5::Core
    Qt5::Quick
    ${OpenCV_LIBS}
    )

My system is Ubuntu22.10

I hope everything is normal.


问:
Error: ('HY000', 'The driver did not supply an error!') - with string
I am trying to push a pandas DataFrame from python to Impala but am getting a very uninformative error. The code I am using looks as such:

```<code>cursor = connection.cursor()
cursor.fast_executemany = True
cursor.executemany(
    f"INSERT INTO table({', '.join(df.columns.tolist())}) VALUES ({('?,' * len(df.columns))[:-1]})",
    list(df.itertuples(index=False, name=None))
)
cursor.commit()
connection.close()
</code>```

This works for the first 23 rows and then suddenly throws this error:

```<code>Error: ('HY000', 'The driver did not supply an error!')
</code>```

This doesn't help me locate the issue at all. I've turned all Na values to None so there is compatibility, Unfortunatly I can't share the data.

Does anyone have any ideas/ leads as to how I would solve this. Thanks

Body:
I am trying to push a pandas DataFrame from python to Impala but am getting a very uninformative error. The code I am using looks as such:

cursor = connection.cursor()
cursor.fast_executemany = True
cursor.executemany(
    f"INSERT INTO table({', '.join(df.columns.tolist())}) VALUES ({('?,' * len(df.columns))[:-1]})",
    list(df.itertuples(index=False, name=None))
)
cursor.commit()
connection.close()

This works for the first 23 rows and then suddenly throws this error:

Error: ('HY000', 'The driver did not supply an error!')

This doesn't help me locate the issue at all. I've turned all Na values to None so there is compatibility, Unfortunatly I can't share the data.

Does anyone have any ideas/ leads as to how I would solve this. Thanks


问:
D3 axisBottom scale domain issue when resizing after transform
I am trying to create a simple plot that is zoomable, pannable, and dynamically resizes with the window. In this case I only want it be to zoomable and pannable on the x axis. I'm using d3 v4.

The main issue I have run into is that the domain of the bottom axis will shift/slide when the page is being resized after the plot has been transformed. On resizing without having first transformed the plot, the bottom axis behaves as desired and maintains its domain, just "compressing" and "expanding" on resize.

To see the desired behavior, you can resize the plot without first transforming the plot by zooming or panning, and you'll see that the bottom axis maintains its domain.

To see the undesirable behavior, you can pan or zoom the plot and then resize the page. You will notice that the domain of the bottom axis will slide/shift.

I suspect there is something I'm doing wrong with setting my scales, however I am quite stuck.

The snippet below is a minimum working example of what I am working with:

window.addEventListener("resize", redraw);

let parentRect = $("#i3061007142472").parent()[0].getBoundingClientRect();
let pWidth = parentRect.width;
let pHeight = parentRect.height;

var margin = {
    'top': 10,
    'right': 30,
    'bottom': 30,
    'left': 60
  },
  width = pWidth - margin.left - margin.right,
  height = pHeight - margin.top - margin.bottom;

var svg = d3.select("#i3061007142472")
  .attr("width", width)
  .attr("height", height + 20);

var zoom = d3.zoom();
zoom.on("zoom", zoom_handler_dataplot);
d3.select("#i3061007142472").call(zoom);

var x_i3061007142472 = d3.scaleTime()
  .domain([new Date('0'), new Date('10')])
  .range([60, width]);

x_i3061007142472.type = "time";

var svg_gX = svg.append("g")
  .attr("class", "xAxis dataplot")
  .attr("transform", `translate(0, ${height})`)

svg_gX.call(d3.axisBottom(x_i3061007142472).ticks(5));

var y_i3061007142472 = d3.scaleLinear()
  .domain([0, 10])
  .range([height, 0]);
y_i3061007142472.type = "linear";

let vd_xaxis_i3061007142472 = x_i3061007142472.copy();
let vd_yaxis_i3061007142472 = y_i3061007142472.copy();

var svg_gY = svg.append("g")
  .attr("class", "yAxis dataplot")
  .style("padding-left", "50px")
  .attr("transform", "translate(" + 60 + ", 0)")
  .call(d3.axisLeft(y_i3061007142472).ticks(5));

allow_pan_dir = "x";
domain = x_i3061007142472.domain();

function zoom_handler_dataplot() {
  if (allow_pan_dir != "none") {
    if (allow_pan_dir == "x" || allow_pan_dir == "both") {

      vd_xaxis_i3061007142472 = d3.event.transform.rescaleX(x_i3061007142472);
      domain = vd_xaxis_i3061007142472.domain()
      svg_gX.call(d3.axisBottom(vd_xaxis_i3061007142472));

    } else {
      vd_xaxis_i3061007142472 = x_i3061007142472;
    }
    if (allow_pan_dir == "y" || allow_pan_dir == "both") {
      vd_yaxis_i3061007142472 = d3.event.transform.rescaleY(y_i3061007142472);
      svg_gY.call(d3.axisLeft(vd_yaxis_i3061007142472));
    } else {
      vd_yaxis_i3061007142472 = y_i3061007142472;
    }
  }
}

function redraw() {
  console.warn("calling redraw");
  console.warn(allow_pan_dir);
  chartWidth = parseInt(d3.select(".dataplot_i3061007142472").style("width"));
  chartHeight = parseInt(d3.select(".dataplot_i3061007142472").style("height"));
  height = chartHeight - margin.top - margin.bottom + 20;

  x_i3061007142472.range([60, chartWidth]);
  y_i3061007142472.range([chartHeight - 30 - 10 + 20, 0]);

  if (allow_pan_dir == "x" || allow_pan_dir == "both") {

    vd_xaxis_i3061007142472 = d3.zoomTransform(d3.select("#i3061007142472").node()).rescaleX(x_i3061007142472);

    svg_gX.call(d3.axisBottom(vd_xaxis_i3061007142472));

  } else {
    vd_xaxis_i3061007142472 = x_i3061007142472;
  }

  if (allow_pan_dir == "y" || allow_pan_dir == "both") {
    vd_yaxis_i3061007142472 = d3.zoomTransform(d3.select("#i3061007142472").node()).rescaleY(y_i3061007142472);
    svg_gY.call(d3.axisLeft(vd_yaxis_i3061007142472));
  } else {
    vd_yaxis_i3061007142472 = y_i3061007142472;
  }

  let currTransform = d3.zoomTransform(d3.select('#i3061007142472').node());
  d3.select("#i3061007142472").call(zoom.transform, currTransform);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><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">
  <link rel="stylesheet" href="./styles.css ">
  <title>Document</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.0.0/d3.min.js" integrity="sha512-il/oXcqETt5LGGmWWbOZLxrDgQQXlr7+ZI37ksA//3e9mxFloAOzlkF8SqtMOlWL6zTCk8hPYUQnreiQvT4elQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
</head>

<body>
  <div id="my_plot" style="display: flex; flex: 1;">
    <svg id="i3061007142472" class="dataplot_i3061007142472 dataplot"></svg>
  </div>

  <script src="./app.js"></script>
</body>

</html></code>```

I tried changing the domain on resize to match the transformed, tried using an intermediary scale, tried modifying the reference scale.

Body:
I am trying to create a simple plot that is zoomable, pannable, and dynamically resizes with the window. In this case I only want it be to zoomable and pannable on the x axis. I'm using d3 v4.

The main issue I have run into is that the domain of the bottom axis will shift/slide when the page is being resized after the plot has been transformed. On resizing without having first transformed the plot, the bottom axis behaves as desired and maintains its domain, just "compressing" and "expanding" on resize.

To see the desired behavior, you can resize the plot without first transforming the plot by zooming or panning, and you'll see that the bottom axis maintains its domain.

To see the undesirable behavior, you can pan or zoom the plot and then resize the page. You will notice that the domain of the bottom axis will slide/shift.

I suspect there is something I'm doing wrong with setting my scales, however I am quite stuck.

The snippet below is a minimum working example of what I am working with:

window.addEventListener("resize", redraw);

let parentRect = $("#i3061007142472").parent()[0].getBoundingClientRect();
let pWidth = parentRect.width;
let pHeight = parentRect.height;

var margin = {
    'top': 10,
    'right': 30,
    'bottom': 30,
    'left': 60
  },
  width = pWidth - margin.left - margin.right,
  height = pHeight - margin.top - margin.bottom;

var svg = d3.select("#i3061007142472")
  .attr("width", width)
  .attr("height", height + 20);

var zoom = d3.zoom();
zoom.on("zoom", zoom_handler_dataplot);
d3.select("#i3061007142472").call(zoom);

var x_i3061007142472 = d3.scaleTime()
  .domain([new Date('0'), new Date('10')])
  .range([60, width]);

x_i3061007142472.type = "time";

var svg_gX = svg.append("g")
  .attr("class", "xAxis dataplot")
  .attr("transform", `translate(0, ${height})`)

svg_gX.call(d3.axisBottom(x_i3061007142472).ticks(5));

var y_i3061007142472 = d3.scaleLinear()
  .domain([0, 10])
  .range([height, 0]);
y_i3061007142472.type = "linear";

let vd_xaxis_i3061007142472 = x_i3061007142472.copy();
let vd_yaxis_i3061007142472 = y_i3061007142472.copy();

var svg_gY = svg.append("g")
  .attr("class", "yAxis dataplot")
  .style("padding-left", "50px")
  .attr("transform", "translate(" + 60 + ", 0)")
  .call(d3.axisLeft(y_i3061007142472).ticks(5));

allow_pan_dir = "x";
domain = x_i3061007142472.domain();

function zoom_handler_dataplot() {
  if (allow_pan_dir != "none") {
    if (allow_pan_dir == "x" || allow_pan_dir == "both") {

      vd_xaxis_i3061007142472 = d3.event.transform.rescaleX(x_i3061007142472);
      domain = vd_xaxis_i3061007142472.domain()
      svg_gX.call(d3.axisBottom(vd_xaxis_i3061007142472));

    } else {
      vd_xaxis_i3061007142472 = x_i3061007142472;
    }
    if (allow_pan_dir == "y" || allow_pan_dir == "both") {
      vd_yaxis_i3061007142472 = d3.event.transform.rescaleY(y_i3061007142472);
      svg_gY.call(d3.axisLeft(vd_yaxis_i3061007142472));
    } else {
      vd_yaxis_i3061007142472 = y_i3061007142472;
    }
  }
}

function redraw() {
  console.warn("calling redraw");
  console.warn(allow_pan_dir);
  chartWidth = parseInt(d3.select(".dataplot_i3061007142472").style("width"));
  chartHeight = parseInt(d3.select(".dataplot_i3061007142472").style("height"));
  height = chartHeight - margin.top - margin.bottom + 20;

  x_i3061007142472.range([60, chartWidth]);
  y_i3061007142472.range([chartHeight - 30 - 10 + 20, 0]);

  if (allow_pan_dir == "x" || allow_pan_dir == "both") {

    vd_xaxis_i3061007142472 = d3.zoomTransform(d3.select("#i3061007142472").node()).rescaleX(x_i3061007142472);

    svg_gX.call(d3.axisBottom(vd_xaxis_i3061007142472));

  } else {
    vd_xaxis_i3061007142472 = x_i3061007142472;
  }

  if (allow_pan_dir == "y" || allow_pan_dir == "both") {
    vd_yaxis_i3061007142472 = d3.zoomTransform(d3.select("#i3061007142472").node()).rescaleY(y_i3061007142472);
    svg_gY.call(d3.axisLeft(vd_yaxis_i3061007142472));
  } else {
    vd_yaxis_i3061007142472 = y_i3061007142472;
  }

  let currTransform = d3.zoomTransform(d3.select('#i3061007142472').node());
  d3.select("#i3061007142472").call(zoom.transform, currTransform);
}

<!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">
  <link rel="stylesheet" href="./styles.css ">
  <title>Document</title>

    <svg id="i3061007142472" class="dataplot_i3061007142472 dataplot"></svg>

I tried changing the domain on resize to match the transformed, tried using an intermediary scale, tried modifying the reference scale.


问:
Python Pandas: How can I group different days of a month that are part of my dataset into one month?
I am currently working on my master thesis and I have a problem with regards to data organization in pandas. I downloaded multiple economic indicators that are published once a month and consolidated them in one dataframe.

However, the economic indicators are released on different days each month. Therefore my dataframe has for example five different rows for January 2020 (e.g. January 1st, January 5th, January 13th, January 28th, January 31st) and many „NaN“ values in each row.

I want to organize my data so that I have one row for each month, so for example one row for January 2020. However, I cannot figure out how to solve this problem in pandas.

Another challenge represents the fact that sometimes the data is released on March 1st and on March 31st. Therefore consolidating everything in one month could also lead to new problems if the values are summed up.

The table below visualizes my problem. My index column in the dataframe are the dates.

```<code>| Dates    | Indicator 1 | Indicator 2
| ———————— | ——————————— | ———————————
| 01.01.20 | 1           | 1
| 08.01.20 | 2           | NaN
| 02.02.20 | 5           | 5
| 01.03.20 | 8           | 6
| 31.03.20 | 7           | 7
</code>```

I already tried pd.to_period or pd.groupby, but I could not solve the problem.

Body:
I am currently working on my master thesis and I have a problem with regards to data organization in pandas. I downloaded multiple economic indicators that are published once a month and consolidated them in one dataframe.

However, the economic indicators are released on different days each month. Therefore my dataframe has for example five different rows for January 2020 (e.g. January 1st, January 5th, January 13th, January 28th, January 31st) and many „NaN“ values in each row.

I want to organize my data so that I have one row for each month, so for example one row for January 2020. However, I cannot figure out how to solve this problem in pandas.

Another challenge represents the fact that sometimes the data is released on March 1st and on March 31st. Therefore consolidating everything in one month could also lead to new problems if the values are summed up.

The table below visualizes my problem. My index column in the dataframe are the dates.

| Dates    | Indicator 1 | Indicator 2
| ———————— | ——————————— | ———————————
| 01.01.20 | 1           | 1
| 08.01.20 | 2           | NaN
| 02.02.20 | 5           | 5
| 01.03.20 | 8           | 6
| 31.03.20 | 7           | 7

I already tried pd.to_period or pd.groupby, but I could not solve the problem.


问:
users.insertOne()` buffering timed out after 10000ms
I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error

```<code>MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (E:\e-commer backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:158:23)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)

I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error

I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error

I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error

Node.js v18.12.1

db.js
const mongoose = require('mongoose');
const mongoURI = "mongodb+srv://wasif:kingofnoobs@cluster0.fmaocsf.mongodb.net/new"

// const server = 'mongodb://localhost:27017'
// const dbName = 'ecommerceBackend'
mongoose.set("strictQuery", false);
const connectToMongo =  () => {

  try {
     mongoose.createConnection(mongoURI);
    console.log("Connected");

  } catch (error) {
    console.log("Error In Connection");
  }

}
module.exports = connectToMongo;

index.js
const connectToMongo = require('./db');
const express = require('express')

 connectToMongo();

const app = express()
const port = 3000
app.use(express.json())

app.use(require('./routes/auth'))

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

auth.js
const express = require('express');
const { body, validationResult } = require('express-validator');
const router = express.Router();
const User = require('../models/User');

router.post('/api/auth', [
    body('name').isLength({ min: 3 }),
    body('email').isEmail(),
    body('password').isLength({ min: 5 }),
],  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

     const user =  User(req.body);
     user.save()

    res.send(req.body);
})
module.exports = router
</code>```

I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error

sorry, posting for the first time that's why

Body:
I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error

MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (E:\e-commer backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:158:23)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)

I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error

I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error

I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error

Node.js v18.12.1

db.js
const mongoose = require('mongoose');
const mongoURI = "mongodb+srv://wasif:kingofnoobs@cluster0.fmaocsf.mongodb.net/new"

// const server = 'mongodb://localhost:27017'
// const dbName = 'ecommerceBackend'
mongoose.set("strictQuery", false);
const connectToMongo =  () => {

  try {
     mongoose.createConnection(mongoURI);
    console.log("Connected");

  } catch (error) {
    console.log("Error In Connection");
  }

}
module.exports = connectToMongo;

index.js
const connectToMongo = require('./db');
const express = require('express')

 connectToMongo();

const app = express()
const port = 3000
app.use(express.json())

app.use(require('./routes/auth'))

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

auth.js
const express = require('express');
const { body, validationResult } = require('express-validator');
const router = express.Router();
const User = require('../models/User');

router.post('/api/auth', [
    body('name').isLength({ min: 3 }),
    body('email').isEmail(),
    body('password').isLength({ min: 5 }),
],  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

     const user =  User(req.body);
     user.save()

    res.send(req.body);
})
module.exports = router

I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error

sorry, posting for the first time that's why


问:
GIFs displayed incorrectly using FLAnimatedImage Library on SWIFT
I am using the FLAnimatedImage Library (downloaded via CocoaPods) to display GIFs in a simple test app.  The app is designed to play a GIF just once when a button is pressed.  To play the GIF only once I make use of a loopCompletionBlock.

Problem: the FLAnimatedImage routine briefly displays the final frame of the GIF before correctly playing the frames of the GIF. The error takes place regardless of what GIF is displayed so it is a code problem and not a GIF problem.  The problem is not caused by the loopCompletionBlock because it still takes place even when I remove that code.  Does anyone know how to fix this problem?

I am running Xcode 14.1. and Swift 5.7.

```<code>import UIKit
import FLAnimatedImage

class ViewController: UIViewController {

    @IBOutlet weak var GIFImageView: FLAnimatedImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func playGIFButtonPressed(_ sender: Any) {

        if let path =  Bundle.main.path(forResource: "check-mark-verified", ofType: "gif") {
            if let data = NSData(contentsOfFile: path) {
                let gif = FLAnimatedImage(animatedGIFData: data as Data)
                GIFImageView.animatedImage = gif
            }
        }

        self.GIFImageView.loopCompletionBlock = {_ in
            self.GIFImageView.stopAnimating()
        }
    }
}

</code>```

Body:
I am using the FLAnimatedImage Library (downloaded via CocoaPods) to display GIFs in a simple test app.  The app is designed to play a GIF just once when a button is pressed.  To play the GIF only once I make use of a loopCompletionBlock.

Problem: the FLAnimatedImage routine briefly displays the final frame of the GIF before correctly playing the frames of the GIF. The error takes place regardless of what GIF is displayed so it is a code problem and not a GIF problem.  The problem is not caused by the loopCompletionBlock because it still takes place even when I remove that code.  Does anyone know how to fix this problem?

I am running Xcode 14.1. and Swift 5.7.

import UIKit
import FLAnimatedImage

class ViewController: UIViewController {

    @IBOutlet weak var GIFImageView: FLAnimatedImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func playGIFButtonPressed(_ sender: Any) {

        if let path =  Bundle.main.path(forResource: "check-mark-verified", ofType: "gif") {
            if let data = NSData(contentsOfFile: path) {
                let gif = FLAnimatedImage(animatedGIFData: data as Data)
                GIFImageView.animatedImage = gif
            }
        }

        self.GIFImageView.loopCompletionBlock = {_ in
            self.GIFImageView.stopAnimating()
        }
    }
}


问:
VSCode api - get fsPath to current state of file
I'm trying to build an extension that uses jq to help parse and jump through large json files. I have the basics setup, the issue I'm running into is since I'm using jq in a child process execute (cp.exec(...)) I'm only able to parse the data that's saved on the file. While I want to be able to parse even that json data in the editor that isn't saved. I know this is possible since vscode does something similar with ripgrep for its search. For example in the vscode source code (src\vs\workbench\services\search\node) you can see ripgrep is launched as a child process and searches the files for matches. It seems to use the fsPath of the file but it gets current editor results but I dont using the activeTextEdtiro.document.uri.fsPath.

I know you can get the entire current contents of the editor with something like

```<code>vscode.workspace.openTextDocument(uri).then((document) => {
  let text = document.getText();
});
</code>```

or your can get the uri / fsPath to the file with

```<code>vscode.window.activeTextEditor.document.uri.fsPath;
</code>```

But the problem is the uri is outdated (ie doesnt have the unsaved changes) and I cant pipe or echo all the text into the jq command in a cp.exec using the getText() method. So how do you fetch the uri to the current state of the file.

Body:
I'm trying to build an extension that uses jq to help parse and jump through large json files. I have the basics setup, the issue I'm running into is since I'm using jq in a child process execute (cp.exec(...)) I'm only able to parse the data that's saved on the file. While I want to be able to parse even that json data in the editor that isn't saved. I know this is possible since vscode does something similar with ripgrep for its search. For example in the vscode source code (src\vs\workbench\services\search\node) you can see ripgrep is launched as a child process and searches the files for matches. It seems to use the fsPath of the file but it gets current editor results but I dont using the activeTextEdtiro.document.uri.fsPath.

I know you can get the entire current contents of the editor with something like

vscode.workspace.openTextDocument(uri).then((document) => {
  let text = document.getText();
});

or your can get the uri / fsPath to the file with

vscode.window.activeTextEditor.document.uri.fsPath;

But the problem is the uri is outdated (ie doesnt have the unsaved changes) and I cant pipe or echo all the text into the jq command in a cp.exec using the getText() method. So how do you fetch the uri to the current state of the file.


问:
Node application issue when using google speech to text on centos server
I have a node application using google speech to text service on a centos server. Locally I have no problems but on the centos server I have this error when I start the registration:
sox warn alsa can't encode 0-bit unknown or not applicable
I tried to install a fake sound card thinking that was the problem but it didn't solve it. Has anyone ever had this problem?


问:
Javascript, make a variable inside a function globally available
this application has 2 select functions, the first select function takes data from a json file. when one is selected it saves the ID in a variable. this variable is created using let outside the function. in the second select function it takes data from a json file and only shows the data where the ID from the json matches the ID saved in the first select variable.

The problem is that the variable cant be found outside of the function. when i console the variable outside the function it came back undefined

I tried changing the variable from let to var. this didn't work. i expected it to be solved but instead there didn't happen anything diffrent.

```<code>let locID;
let select;
let select2;

function preload() {
  data = loadJSON(
    "https://raw.githubusercontent.com/mia-mmt2-2223/leesfestival/main/festival.json"
  );
}

function setup() {
  createCanvas(400, 400);
  //LOCATION  SELECTION
  //create select element with as options name from locations from json
  select = createSelect();
  select.position(10, 10);
  select.option("Select a location");
  for (let i = 0; i < data.locations.length; i++) {
    select.option(data.locations[i].name);
  }
  //when a location is selected, save the location id
  select.changed(function () {
    item = select.value();
    for (let i = 0; i < data.locations.length; i++) {
      if (data.locations[i].name == item) {
        locID = data.locations[i].id;
      }
    }
  });

  //WORKSHOP SELECTION
  //create select element with as options name from workshops where location matches locID from json
  select2 = createSelect();
  select2.position(10, 50);
  select2.option("Select a workshop");
  for (let i = 0; i < data.workshops.length; i++) {
    if (data.workshops[i].location == locID) {
      select2.option(data.workshops[i].name);
    }
  }
}````
```

Body:
this application has 2 select functions, the first select function takes data from a json file. when one is selected it saves the ID in a variable. this variable is created using let outside the function. in the second select function it takes data from a json file and only shows the data where the ID from the json matches the ID saved in the first select variable.

The problem is that the variable cant be found outside of the function. when i console the variable outside the function it came back undefined

I tried changing the variable from let to var. this didn't work. i expected it to be solved but instead there didn't happen anything diffrent.

let locID;
let select;
let select2;

function preload() {
  data = loadJSON(
    "https://raw.githubusercontent.com/mia-mmt2-2223/leesfestival/main/festival.json"
  );
}

function setup() {
  createCanvas(400, 400);
  //LOCATION  SELECTION
  //create select element with as options name from locations from json
  select = createSelect();
  select.position(10, 10);
  select.option("Select a location");
  for (let i = 0; i < data.locations.length; i++) {
    select.option(data.locations[i].name);
  }
  //when a location is selected, save the location id
  select.changed(function () {
    item = select.value();
    for (let i = 0; i < data.locations.length; i++) {
      if (data.locations[i].name == item) {
        locID = data.locations[i].id;
      }
    }
  });

  //WORKSHOP SELECTION
  //create select element with as options name from workshops where location matches locID from json
  select2 = createSelect();
  select2.position(10, 50);
  select2.option("Select a workshop");
  for (let i = 0; i < data.workshops.length; i++) {
    if (data.workshops[i].location == locID) {
      select2.option(data.workshops[i].name);
    }
  }
}````


问:
Permission denied querying a view in AWS Redshift
Why do I get permission denied when querying a view in AWS Redshift but not when running the query used to make the view?

When I try to run:

```<code>SELECT * FROM "dev"."public"."stg_kfdb_answers_flattened";
</code>```

I get the error:

```<code>ERROR: permission denied for relation answers [ErrorId: 1-63c08c6b-616566234b35efdf64d5f06c]
</code>```

But stg_kfdb_answers_flattened is a view, with the definition being:

```<code>CREATE
OR
REPLACE
  VIEW "public".stg_kfdb_answers_flattened AS
SELECT
  json_extract_path_text(answers.document ::text, '_id' ::text) AS id,
  <etc.>,
FROM
  <source_schema>.<source_table>;
</code>```

When I run the query by itself, it works just fine. But when I create the view, as you see above, it gives me a permission denied error.

I have already tried giving myself permissions with statements like from this previous question.

```<code>GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to jerry;
</code>```

But none of these have seemed to help. What am I doing wrong?

Body:
Why do I get permission denied when querying a view in AWS Redshift but not when running the query used to make the view?

When I try to run:

SELECT * FROM "dev"."public"."stg_kfdb_answers_flattened";

I get the error:

ERROR: permission denied for relation answers [ErrorId: 1-63c08c6b-616566234b35efdf64d5f06c]

But stg_kfdb_answers_flattened is a view, with the definition being:

CREATE
OR
REPLACE
  VIEW "public".stg_kfdb_answers_flattened AS
SELECT
  json_extract_path_text(answers.document ::text, '_id' ::text) AS id,
  <etc.>,
FROM
  <source_schema>.<source_table>;

When I run the query by itself, it works just fine. But when I create the view, as you see above, it gives me a permission denied error.

I have already tried giving myself permissions with statements like from this previous question.

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to jerry;

But none of these have seemed to help. What am I doing wrong?


问:
Problem with post tracking by php or javascript
i m sorry but my english is not good
i am new in php programming and i want to write a program for tracking order from a post traking website .

the url is : https://tracking.post.ir/
i can sed the traking code by url address like this : example : "045150128401189670000147"
https://tracking.post.ir/?id=045150128401189670000147

but the problem is that i cannot get data by simple xml dom becuse the site need "enter" command for searching and then return traking status by javascript .

i have no idea for getting data back from this site .

i write a program for a traking website name TIPAX but it didnt need "Enter command
Example : https://tipaxco.com/tracking?id=4366202317151765837 "this is worked ok"

please help me
I really need this program. If there is a method that simulates the ENTER command after the page is ready and has the return tracking information in the form of dom, I can extract the data with the "simple dom html" library.

please write an Examle code that can do this .
I don't have much experience in programming, but I have worked with php to some extent and I know very little about javascript.

I tried with "curl" but it didn't work.
Apparently, the forms use JavaScript, and every time the page is loaded, a series of codes are created as tokens for the input form, which makes it impossible to get information from this page.


问:
Spring Boot - SQL error instead of thrown exception
I'm making my first Spring Boot project, and it's working well. It uses a H2 database. The problem is that it returns 5xx HTTP responses, instead of 4xx with exceptions in cases of sql errors.
For example, I have this constraint:

Pet.java

@Table(uniqueConstraints={
        @UniqueConstraint(columnNames = {"name","customer_id"})
})
```
<p>I made this constraint because you shouldn't be able to save 2 pets with the same name, for the same owner (customer).</p>
<p>But when I try to POST a pet with the same name, for the same owner, it returns me an 5xx error, and SQL error appear in the log.</p>
<p>Pet.java</p>
<pre class="lang-java prettyprint-override"><code>@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity(name = "pet")
@Table(uniqueConstraints={
        @UniqueConstraint(columnNames = {"name","customer_id"})
})
public class Pet implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Getter
    @Setter
    @Column(nullable = false, insertable = false, updatable = false)
    private Long id;
    @Column (name = "name", nullable = false)
    private String name;
    @Column (name = "birthdate")
    private LocalDate birthdate;
    @Column (name = "weight_KG")
    private Double weight_KG;
    @Column
    private String color;
    @Column
    String breed;
    @Getter
    @Setter
    @ManyToOne (cascade =  CascadeType.ALL)
    @JoinColumn (name = "customer_id", referencedColumnName = "id", nullable = false)
    private Customer customer;
    @JsonIgnore
    @OneToMany(mappedBy = "pet")
    List<Vaccination> vaccination;

}

</code>```

Customer.java

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity (name = "customer")
public class Customer implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Getter
    @Setter
    @Column(nullable = false, insertable = false, updatable = false)
    private Long id;
    @Column (name = "name", nullable = false, unique = true)
    private String name;
    @Column (name = "surname")
    private String surname;
    @Column (name = "birthdate")
    private LocalDate birthdate;
    @OneToMany(mappedBy = "customer",cascade={CascadeType.ALL})
    @JsonIgnore
    private List<Pet> pets;
}
```
<p>CustomerController.java</p>
<pre class="lang-java prettyprint-override"><code>@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private CustomerRepository customerRepository;

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Customer save(@RequestBody Customer customer) {
        if (customerRepository.findByName(customer.getName()).isPresent()){
            throw new ResponseStatusException(HttpStatus.CONFLICT, "Customer with the inserted name already exists.");
        }
        //customerRepository.findByName(customer.getName()).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found"));
        return customerService.save(customer);
    }
    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    public List<Customer> findAllCustomers(){
        return customerService.findAll();
    }
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public Customer findCustomerById(@PathVariable("id") Long id) {
        return customerService.findById(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found"));
    }
    @GetMapping("/name/{name}")
    @ResponseStatus(HttpStatus.OK)
    public List<Customer> findCustomerByName(@PathVariable("name") String name) {
        List<Customer> customer = customerRepository.findByNameStartsWithIgnoreCase(name);
        return customer;
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteCustomer(@PathVariable("id") Long id){
        customerService.findById(id)
                .map(customer -> {
                    customerService.deleteById(customer.getId());
                    return Void.TYPE;
                }).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found"));
    }
    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void updateCustomer (@PathVariable("id") Long id, @RequestBody Customer customer) {
        customerService.findById(id)
                .map(customerBase -> {
                    modelMapper.map(customer,customerBase);
                    customerService.save(customerBase);
                    return Void.TYPE;
                }).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found"));
    }

}
</code>```

PetController.java

@RestController
@RequestMapping("/pet")
public class PetController {
    @Autowired
    private PetService petService;

    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private PetRepository petRepository;

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Pet save(@RequestBody Pet pet){
        customerRepository.findById(pet.getCustomer().getId()).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer does not exists."));
        Customer customer = customerRepository.findById(pet.getCustomer().getId()).get();
        pet.setCustomer(customer);
        //petRepository.findByCustomer(customer);
        return petService.save(pet);
    }
    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    public List<Pet> findAllPets(){
        return petService.findAll();
    }
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public Pet findPetById(@PathVariable("id") Long id){
        return petService.findById(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Pet not found"));
    }
    @GetMapping("/name/{name}")
    @ResponseStatus(HttpStatus.OK)
    public List<Pet> findPetByName(@PathVariable("name") String name){
        List<Pet> pet = petRepository.findByNameStartsWithIgnoreCase(name);
        return pet;
    }
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deletePet(@PathVariable("id") Long id){
        petService.findById(id)
                .map(pet -> {
                    petService.deleteById(pet.getId());
                    return Void.TYPE;
                }).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Pet not found"));
    }
    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void updatePet (@PathVariable("id") Long id, @RequestBody Pet pet) {
        petService.findById(id)
                .map(petBase -> {
                    modelMapper.map(pet,petBase);
                    petService.save(petBase);
                    return Void.TYPE;
                }).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Pet not found"));
    }

}
```
<p>I had the same problem when saving two customers with the same name, but I solved the problem by adding these lines of code to the controller:</p>
<p>CustomerController.java</p>
<pre class="lang-java prettyprint-override"><code>if (customerRepository.findByName(customer.getName()).isPresent()){
   throw new ResponseStatusException(HttpStatus.CONFLICT, "Customer with the inserted name already exists.");
}
</code>```

But the pet's constraint is more complex, and I couldn't find a solution the same way I did above. I tried to create a petRepository.findbyCustomer, send the customer that was gonna  be saved. Then I would have a list of pets that have the same customer, and somehow try to findByName these pets, searching for the name of the pet that is going to be saved.

But I stopped with these crazy idea, because there could be a cleaner way to to this. I tried to search for it, but couldn't find a solution.

What I want is a exception throw in the case I try to save two pets with the same name for the same owner. I don't want SQL errors, and I don't want 5xx returns.

Body:
I'm making my first Spring Boot project, and it's working well. It uses a H2 database. The problem is that it returns 5xx HTTP responses, instead of 4xx with exceptions in cases of sql errors.
For example, I have this constraint:

Pet.java

@Table(uniqueConstraints={
        @UniqueConstraint(columnNames = {"name","customer_id"})
})

I made this constraint because you shouldn't be able to save 2 pets with the same name, for the same owner (customer).

But when I try to POST a pet with the same name, for the same owner, it returns me an 5xx error, and SQL error appear in the log.

Pet.java

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity(name = "pet")
@Table(uniqueConstraints={
        @UniqueConstraint(columnNames = {"name","customer_id"})
})
public class Pet implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Getter
    @Setter
    @Column(nullable = false, insertable = false, updatable = false)
    private Long id;
    @Column (name = "name", nullable = false)
    private String name;
    @Column (name = "birthdate")
    private LocalDate birthdate;
    @Column (name = "weight_KG")
    private Double weight_KG;
    @Column
    private String color;
    @Column
    String breed;
    @Getter
    @Setter
    @ManyToOne (cascade =  CascadeType.ALL)
    @JoinColumn (name = "customer_id", referencedColumnName = "id", nullable = false)
    private Customer customer;
    @JsonIgnore
    @OneToMany(mappedBy = "pet")
    List<Vaccination> vaccination;

}

Customer.java

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity (name = "customer")
public class Customer implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Getter
    @Setter
    @Column(nullable = false, insertable = false, updatable = false)
    private Long id;
    @Column (name = "name", nullable = false, unique = true)
    private String name;
    @Column (name = "surname")
    private String surname;
    @Column (name = "birthdate")
    private LocalDate birthdate;
    @OneToMany(mappedBy = "customer",cascade={CascadeType.ALL})
    @JsonIgnore
    private List<Pet> pets;
}

CustomerController.java

@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private CustomerRepository customerRepository;

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Customer save(@RequestBody Customer customer) {
        if (customerRepository.findByName(customer.getName()).isPresent()){
            throw new ResponseStatusException(HttpStatus.CONFLICT, "Customer with the inserted name already exists.");
        }
        //customerRepository.findByName(customer.getName()).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found"));
        return customerService.save(customer);
    }
    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    public List<Customer> findAllCustomers(){
        return customerService.findAll();
    }
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public Customer findCustomerById(@PathVariable("id") Long id) {
        return customerService.findById(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found"));
    }
    @GetMapping("/name/{name}")
    @ResponseStatus(HttpStatus.OK)
    public List<Customer> findCustomerByName(@PathVariable("name") String name) {
        List<Customer> customer = customerRepository.findByNameStartsWithIgnoreCase(name);
        return customer;
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteCustomer(@PathVariable("id") Long id){
        customerService.findById(id)
                .map(customer -> {
                    customerService.deleteById(customer.getId());
                    return Void.TYPE;
                }).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found"));
    }
    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void updateCustomer (@PathVariable("id") Long id, @RequestBody Customer customer) {
        customerService.findById(id)
                .map(customerBase -> {
                    modelMapper.map(customer,customerBase);
                    customerService.save(customerBase);
                    return Void.TYPE;
                }).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found"));
    }

}

PetController.java

@RestController
@RequestMapping("/pet")
public class PetController {
    @Autowired
    private PetService petService;

    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private PetRepository petRepository;

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Pet save(@RequestBody Pet pet){
        customerRepository.findById(pet.getCustomer().getId()).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer does not exists."));
        Customer customer = customerRepository.findById(pet.getCustomer().getId()).get();
        pet.setCustomer(customer);
        //petRepository.findByCustomer(customer);
        return petService.save(pet);
    }
    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    public List<Pet> findAllPets(){
        return petService.findAll();
    }
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public Pet findPetById(@PathVariable("id") Long id){
        return petService.findById(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Pet not found"));
    }
    @GetMapping("/name/{name}")
    @ResponseStatus(HttpStatus.OK)
    public List<Pet> findPetByName(@PathVariable("name") String name){
        List<Pet> pet = petRepository.findByNameStartsWithIgnoreCase(name);
        return pet;
    }
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deletePet(@PathVariable("id") Long id){
        petService.findById(id)
                .map(pet -> {
                    petService.deleteById(pet.getId());
                    return Void.TYPE;
                }).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Pet not found"));
    }
    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void updatePet (@PathVariable("id") Long id, @RequestBody Pet pet) {
        petService.findById(id)
                .map(petBase -> {
                    modelMapper.map(pet,petBase);
                    petService.save(petBase);
                    return Void.TYPE;
                }).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Pet not found"));
    }

}

I had the same problem when saving two customers with the same name, but I solved the problem by adding these lines of code to the controller:

CustomerController.java

if (customerRepository.findByName(customer.getName()).isPresent()){
   throw new ResponseStatusException(HttpStatus.CONFLICT, "Customer with the inserted name already exists.");
}

But the pet's constraint is more complex, and I couldn't find a solution the same way I did above. I tried to create a petRepository.findbyCustomer, send the customer that was gonna  be saved. Then I would have a list of pets that have the same customer, and somehow try to findByName these pets, searching for the name of the pet that is going to be saved.

But I stopped with these crazy idea, because there could be a cleaner way to to this. I tried to search for it, but couldn't find a solution.

What I want is a exception throw in the case I try to save two pets with the same name for the same owner. I don't want SQL errors, and I don't want 5xx returns.


问:
How do I add a data frame to an existing Excel file and specify the row and column where to begin in R? e.g., start in row 9
I've looked all over and every solution I've found does not work for me. When I use the XLSX package with this syntax:

```<code>wb <- loadWorkbook(file path)
sheets <- getSheets(wb)
isotope <-sheets[[5]]
addDataFrame(mydataframe, isotope, row.Names = FALSE, col.names = FALSE, startRow = 9)
saveWorkbook(wb, new file path & name)
</code>```

All of the data for each column is saved into a single cell. However! If I set row.names and col.names to TRUE, the data copies over correctly (although I get a column and row I don't need). Unfortunately there are formulas in the Excel sheet I'm trying to put the data in so the data frame needs to come over all clean.

```<code>   wb <- loadWorkbook(file path)
    sheets <- getSheets(wb)
    isotope <-sheets[[5]]
    addDataFrame(mydataframe, isotope, row.Names = FALSE, col.names = FALSE, startRow = 9)
    saveWorkbook(wb, new file path & name)
</code>```

Body:
I've looked all over and every solution I've found does not work for me. When I use the XLSX package with this syntax:

wb <- loadWorkbook(file path)
sheets <- getSheets(wb)
isotope <-sheets[[5]]
addDataFrame(mydataframe, isotope, row.Names = FALSE, col.names = FALSE, startRow = 9)
saveWorkbook(wb, new file path & name)

All of the data for each column is saved into a single cell. However! If I set row.names and col.names to TRUE, the data copies over correctly (although I get a column and row I don't need). Unfortunately there are formulas in the Excel sheet I'm trying to put the data in so the data frame needs to come over all clean.

   wb <- loadWorkbook(file path)
    sheets <- getSheets(wb)
    isotope <-sheets[[5]]
    addDataFrame(mydataframe, isotope, row.Names = FALSE, col.names = FALSE, startRow = 9)
    saveWorkbook(wb, new file path & name)


问:
Doing something when payment is successfull with stripe and DjangoRest
I integrated stripe payment in my projects so now i can make a payment.

My app about an advertising app so the ad keep active for 30 days then disappear so i want to use payment to extend the expiration date of the ad.

Here is Payment view:

```<code>

class StripeCheckoutView(APIView):
    def post(self, request):
        try:
            checkout_session = stripe.checkout.Session.create(
                line_items=[
                    {
                        'price': 'price_1MPUIXGslCuRnIIuUV1ME6Kn',
                        'quantity': 1,
                    },
                ],
                payment_method_types=['card',],
                mode='payment',
                success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}',
                cancel_url=settings.SITE_URL + '/?canceled=true',
            )

            return redirect(checkout_session.url)
        except:
            return Response(
                {'error': 'Something went wrong when creating stripe checkout session'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

</code>```

models:

```<code>class Advertise(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="advertise")
    category = models.CharField(max_length= 200, choices = CATEGORY)
    location = models.CharField(max_length= 200, choices = LOCATIONS)
    description = models.TextField(max_length=600)
    price = models.FloatField(max_length=100)
    expiration_date  = models.DateField(default = Expire_date, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)

</code>```

EDIT :
I want to use payment to extend the duration of the expiration date.
So when the user made the payment the expiration date be 60 days.

Body:
I integrated stripe payment in my projects so now i can make a payment.

My app about an advertising app so the ad keep active for 30 days then disappear so i want to use payment to extend the expiration date of the ad.

Here is Payment view:

class StripeCheckoutView(APIView):
    def post(self, request):
        try:
            checkout_session = stripe.checkout.Session.create(
                line_items=[
                    {
                        'price': 'price_1MPUIXGslCuRnIIuUV1ME6Kn',
                        'quantity': 1,
                    },
                ],
                payment_method_types=['card',],
                mode='payment',
                success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}',
                cancel_url=settings.SITE_URL + '/?canceled=true',
            )

            return redirect(checkout_session.url)
        except:
            return Response(
                {'error': 'Something went wrong when creating stripe checkout session'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

models:

class Advertise(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="advertise")
    category = models.CharField(max_length= 200, choices = CATEGORY)
    location = models.CharField(max_length= 200, choices = LOCATIONS)
    description = models.TextField(max_length=600)
    price = models.FloatField(max_length=100)
    expiration_date  = models.DateField(default = Expire_date, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)

EDIT :
I want to use payment to extend the duration of the expiration date.
So when the user made the payment the expiration date be 60 days.


问:
Images layering over old image in Python Pygame
I don't understand why old image doesn't clearing and a new image layering over old image in debug

```<code>    import pygame
from setting import WIN_HEIGHT, WIN_WIDTH
from debug import debug
from pygame.locals import (
    K_ESCAPE,
    KEYDOWN
)

pygame.init()

# Rise text rectangular
def text_objects(text, font, color):
    text_surf = font.render(text, True, color)
    return text_surf, text_surf.get_rect()

# Make button
def button(screen, color, x, y):
    pygame.draw.rect(screen, color, (x, y, WIN_WIDTH/11, WIN_HEIGHT/11), 0, 15)

# Pause menu
def paused(main_txt):
    screen = pygame.display.get_surface()
    text = pygame.font.SysFont("comicsansms",115)
    text_surf, text_rect = text_objects(main_txt, text, 'black')
    text_rect.center = ((WIN_WIDTH/2), (WIN_HEIGHT/3))
    screen.fill((120, 120, 120))
    screen.blit(text_surf, text_rect)

    while paused:
        music = pygame.mixer.music
        music.pause()
        resume = button(screen, 'green', WIN_WIDTH/3, WIN_HEIGHT/1.95)
        exit = button(screen, (200, 0, 0), WIN_WIDTH/1.77, WIN_HEIGHT/1.95)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()
                pygame.quit()

            elif (event.type == KEYDOWN and event.key == K_ESCAPE):
                music.unpause()
                return

        mouse = pygame.mouse.get_pos()
        debug(mouse)

        if WIN_WIDTH/3 + WIN_WIDTH/11 > mouse[0] > WIN_WIDTH/3 and WIN_HEIGHT/1.95 + WIN_HEIGHT/11 > mouse[1] > WIN_HEIGHT/1.95:
            button(screen, 'black', WIN_WIDTH/3, WIN_HEIGHT/1.95)
        else:
            resume

        pygame.display.update()
        pygame.time.Clock().tick(60)
</code>```

The debug function is

```<code>    import pygame

pygame.init()
font = pygame.font.Font(None, 30)
def debug(info, y = 10, x = 10):
    disp_surf = pygame.display.get_surface()
    debug_surf = font.render(str(info), True, 'Red')
    debug_rect = debug_surf.get_rect(topleft = (x,y))
    disp_surf.blit(debug_surf, debug_rect)
</code>```

Body:
I don't understand why old image doesn't clearing and a new image layering over old image in debug

    import pygame
from setting import WIN_HEIGHT, WIN_WIDTH
from debug import debug
from pygame.locals import (
    K_ESCAPE,
    KEYDOWN
)

pygame.init()

# Rise text rectangular
def text_objects(text, font, color):
    text_surf = font.render(text, True, color)
    return text_surf, text_surf.get_rect()

# Make button
def button(screen, color, x, y):
    pygame.draw.rect(screen, color, (x, y, WIN_WIDTH/11, WIN_HEIGHT/11), 0, 15)

# Pause menu
def paused(main_txt):
    screen = pygame.display.get_surface()
    text = pygame.font.SysFont("comicsansms",115)
    text_surf, text_rect = text_objects(main_txt, text, 'black')
    text_rect.center = ((WIN_WIDTH/2), (WIN_HEIGHT/3))
    screen.fill((120, 120, 120))
    screen.blit(text_surf, text_rect)

    while paused:
        music = pygame.mixer.music
        music.pause()
        resume = button(screen, 'green', WIN_WIDTH/3, WIN_HEIGHT/1.95)
        exit = button(screen, (200, 0, 0), WIN_WIDTH/1.77, WIN_HEIGHT/1.95)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()
                pygame.quit()

            elif (event.type == KEYDOWN and event.key == K_ESCAPE):
                music.unpause()
                return

        mouse = pygame.mouse.get_pos()
        debug(mouse)

        if WIN_WIDTH/3 + WIN_WIDTH/11 > mouse[0] > WIN_WIDTH/3 and WIN_HEIGHT/1.95 + WIN_HEIGHT/11 > mouse[1] > WIN_HEIGHT/1.95:
            button(screen, 'black', WIN_WIDTH/3, WIN_HEIGHT/1.95)
        else:
            resume

        pygame.display.update()
        pygame.time.Clock().tick(60)

The debug function is

    import pygame

pygame.init()
font = pygame.font.Font(None, 30)
def debug(info, y = 10, x = 10):
    disp_surf = pygame.display.get_surface()
    debug_surf = font.render(str(info), True, 'Red')
    debug_rect = debug_surf.get_rect(topleft = (x,y))
    disp_surf.blit(debug_surf, debug_rect)


问:
Events Parameters are not showing in Firebase Analytics for Flutter app (both iOS and Android)
I am using Firebase Analytics for logging events for my Flutter App (Supporting both iOS and Android). In the Firebase Console I can see the Events logged for Android but the Event Parameters are missing.
in main.dart I have done

```<code>await Firebase.initializeApp
(
      options: DefaultFirebaseOptions.currentPlatform,
);
</code>```

and then I am calling the LogEvent like

```<code>await FirebaseAnalytics.instance

        .logEvent(name: 'LoginSuccess', parameters: {

      'Email': _authService.loogedinUserEmail,

      'Platform': Platform.operatingSystem,

      'Model': device.toMap()['model']

    })
</code>```

Also, for iOS I am not seeing the Events in the console. I am testing using Simulator and I have waited 2 days .

Thanks in Advance.

Body:
I am using Firebase Analytics for logging events for my Flutter App (Supporting both iOS and Android). In the Firebase Console I can see the Events logged for Android but the Event Parameters are missing.
in main.dart I have done

await Firebase.initializeApp
(
      options: DefaultFirebaseOptions.currentPlatform,
);

and then I am calling the LogEvent like

await FirebaseAnalytics.instance

        .logEvent(name: 'LoginSuccess', parameters: {

      'Email': _authService.loogedinUserEmail,

      'Platform': Platform.operatingSystem,

      'Model': device.toMap()['model']

    })

Also, for iOS I am not seeing the Events in the console. I am testing using Simulator and I have waited 2 days .

Thanks in Advance.


问:
Cannot control #if defined(condition) in VSCode source
Our embedded product will now produce two image from one set of source files. VSCode is used for editing but not compiling or debugging. However, intellisense and syntax checking is handy.

When I added

```<code>#if defined(ORIGINAL)
   // code looked the same
#endif
</code>```

but when I added

```<code>#if defined(ALTERNATE)
   // code was dulled and intellisense was inactive
#endif
</code>```

Is there a way to tell VSCode which definitions may be passed to the compiler so that I can check all of the code?

Body:
Our embedded product will now produce two image from one set of source files. VSCode is used for editing but not compiling or debugging. However, intellisense and syntax checking is handy.

When I added

#if defined(ORIGINAL)
   // code looked the same
#endif

but when I added

#if defined(ALTERNATE)
   // code was dulled and intellisense was inactive
#endif

Is there a way to tell VSCode which definitions may be passed to the compiler so that I can check all of the code?


问:
How to handle field injection to Couchbase repository
In order to add functionality to the couchbase repository I implemented the below class.
Inside this class is another @componenet name extensionHelper. Since this class is not standard spring bean I can't find a way to inject this field in order to use it in save()

Any idea how to inject such a class?

```<code>public class SimpleCustomRepository<T, ID> extends SimpleCouchbaseRepository<T, ID> {
    @Autowired
    ExtensionHelper extensionHelper;

    public SimpleCustomRepository(CouchbaseEntityInformation<T, String> entityInformation,
                                  CouchbaseOperations couchbaseOperations, Class<?> repositoryInterface) {
        super(entityInformation, couchbaseOperations, repositoryInterface);
    }

    @Override
    public <S extends T> S save(S entity) {
        extensionHelper.applyExtensions(entity);
        return super.save(entity);
    }

    @Override
    public void delete(T entity) {
        super.delete(entity);
    }
}
</code>```

Body:
In order to add functionality to the couchbase repository I implemented the below class.
Inside this class is another @componenet name extensionHelper. Since this class is not standard spring bean I can't find a way to inject this field in order to use it in save()

Any idea how to inject such a class?

public class SimpleCustomRepository<T, ID> extends SimpleCouchbaseRepository<T, ID> {
    @Autowired
    ExtensionHelper extensionHelper;

    public SimpleCustomRepository(CouchbaseEntityInformation<T, String> entityInformation,
                                  CouchbaseOperations couchbaseOperations, Class<?> repositoryInterface) {
        super(entityInformation, couchbaseOperations, repositoryInterface);
    }

    @Override
    public <S extends T> S save(S entity) {
        extensionHelper.applyExtensions(entity);
        return super.save(entity);
    }

    @Override
    public void delete(T entity) {
        super.delete(entity);
    }
}


问:
How can I load my CSS directly into a style tag instead of linking to it with Next.JS?
I have a Next.JS site that sometimes needs to be accessed by a backend process to generate a PDF of the contents on the page. The problem is, when generating the PDF, I only have access to the HTML of the page (i.e., links out to external stylesheets do not work). To work around this limitation, I would like to put the page's stylesheets directly in

```

I understand that this is less efficient than the built-in way Next is doing things but this is unfortunately a hard requirement for my project. Is there any way to achieve this using idiomatic Next?

Body:
I have a Next.JS site that sometimes needs to be accessed by a backend process to generate a PDF of the contents on the page. The problem is, when generating the PDF, I only have access to the HTML of the page (i.e., links out to external stylesheets do not work). To work around this limitation, I would like to put the page's stylesheets directly in

I understand that this is less efficient than the built-in way Next is doing things but this is unfortunately a hard requirement for my project. Is there any way to achieve this using idiomatic Next?


问:
Python: Search for term#1, then search backwards for search#2 in file with multiple results
I have a file with text like this for example

"Name: John| Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco FRUIT: APPLE
Name: Mike|  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in cu FRUIT: PEAR
Name: James| Eleifend donec pretium vulputate sapien nec sagittis aliquam malesuada. Egestas tellus rutrum tellus pellentesque eu tincidunt tortor aliquam nulla. Scelerisque eleifend donec pretium vulputate sapien nec sagittis. Egestas tellus rutrum tellus pellentesque eu tincidunt. FRUIT: APPLE"

Once I load this file, I want to search for search term #1, for example, "APPLE"
Then search backwards for "Name" and then have it return the names.

So a search for "APPLE" would return John & James
A search for "PEAR" would return Mike

My file has a character like a | after the name to help determine what to grab.

I thought a regex would be appropriate but I'm not that familiar with them and not sure how to do 2 search terms.

In Python thanks

I've tried regex expressions but getting stuck on finding the correct syntax