问:
How to decode base64 string before downloading images in react
I have an array of encoded string for images download and fetch data from API, I want the user to be able to click the download button to have the images locally.

```<code>import React from "react";

export default function App() {

//example of API data
//  const URLs = ["data:image/jpg;base64,b'/9j/4AAQSkZJRgABAQEAY..."]

  const handleDownload = async () => {

         Axios({
            url: `${baseUrl}/bulk/images/download`,
            method: "GET",
            responseType: "blob",
         })
            .then((response) => {
                const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement("a");
            link.href = url;
                link.setAttribute("download", "file.jpg");
            document.body.appendChild(link);
                link.click();
            })
            .catch((error) => {
                console.log(error);
            });
    };

  return (
    <div className="App">
      <h1>Download Images</h1>
      <button type="button" onClick={handleDownload}>
        download
      </button>
    </div>
  );
}

</code>```

From the API is 500 list of encoded strings to download. This implementation is what I got on search but it doesn't work as it throws exceptions. Please what's the most clean way to implement this on how to down images in bulk and in a sequence?

Body:
I have an array of encoded string for images download and fetch data from API, I want the user to be able to click the download button to have the images locally.

import React from "react";

export default function App() {

//example of API data
//  const URLs = ["data:image/jpg;base64,b'/9j/4AAQSkZJRgABAQEAY..."]

  const handleDownload = async () => {

         Axios({
            url: `${baseUrl}/bulk/images/download`,
            method: "GET",
            responseType: "blob",
         })
            .then((response) => {
                const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement("a");
            link.href = url;
                link.setAttribute("download", "file.jpg");
            document.body.appendChild(link);
                link.click();
            })
            .catch((error) => {
                console.log(error);
            });
    };

  return (

Download Images

      <button type="button" onClick={handleDownload}>
        download
      </button>

  );
}

From the API is 500 list of encoded strings to download. This implementation is what I got on search but it doesn't work as it throws exceptions. Please what's the most clean way to implement this on how to down images in bulk and in a sequence?


来源: stackexchange

问:
The startup script is executed on the VM defined as a resource but not on the VMs from the Terraform's instance template module
I tried to create a load balancer with the MIG consisting of three VMs. Additionally, I created a VM that is not part of the MIG but operates within the same subnet. The reason for making it was to check the connectivity between the VM and the VMs from the MIG.

Both MIG's VMs and the additional VM have the same startup script. I'll present it using the configuration of the additional VM (var.server_port is 80):

```<code>resource "google_compute_instance" "ssh-vm" {
  name = "ssh-vm"
  machine_type = "e2-standard-2"
  project = var.pro
  tags = ["allow-ssh"]
  zone = "europe-west1-b"

  boot_disk {
    initialize_params {
      image = "ubuntu-2004-focal-v20221213"
    }
  }

  network_interface {
    subnetwork = google_compute_subnetwork.subnetwork.self_link
    access_config {
      nat_ip = google_compute_address.static.address
    }
  }

  metadata = {
    startup-script = <<-EOF
        #!/bin/bash
        sudo snap install docker
        sudo docker version > file1.txt
        sleep 5
        sudo docker run -d --rm -p ${var.server_port}:${var.server_port} \
        busybox sh -c "while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; \
        echo 'yo'; } | nc -l -p ${var.server_port}; done"
        EOF
  }
}

</code>```

One can see that the idea is to spin up docker and run the server that listens on :80. When I ssh onto this instance and run sudo docker ps, I receive the info that the process is running and serving on 80.
The problem is that I have the same startup script within Terraform's instance_template module, but when I ssh into any of the machines from the MIG and run the same command, it says that the docker command is not found.
Here's the configuration of the module:

```<code>module "instance_template" {
  source = "terraform-google-modules/vm/google//modules/instance_template"
  version = "7.9.0"
  region = var.region
  project_id = var.pro
  network = google_compute_network.vpc-network.self_link
  subnetwork = google_compute_subnetwork.subnetwork.self_link
  service_account = {
    email = google_service_account.service-acc.email
    scopes = ["cloud-platform"]
  }

  name_prefix = "webserver"
  tags = ["template-vm", "allow-ssh"]
  machine_type = "e2-standard-2"
  startup_script = <<-EOF
  #!/bin/bash
  sudo snap install docker
  sudo docker version > docker_version.txt
  sleep 5
  sudo docker run -d --rm -p ${var.server_port}:${var.server_port} \
  busybox sh -c "while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; \
  echo 'yo'; } | nc -l -p ${var.server_port}; done"
  EOF
  source_image = "https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/images/ubuntu-2004-focal-v20221213"
  disk_size_gb = 10
  disk_type = "pd-balanced"
  preemptible = true

}
</code>```

I checked and the module's attribute for the startup script is indeed startup_script and not metadata_startup_script.

ContentLicense: CC BY-SA 4.0

Body:
I tried to create a load balancer with the MIG consisting of three VMs. Additionally, I created a VM that is not part of the MIG but operates within the same subnet. The reason for making it was to check the connectivity between the VM and the VMs from the MIG.

Both MIG's VMs and the additional VM have the same startup script. I'll present it using the configuration of the additional VM (var.server_port is 80):

resource "google_compute_instance" "ssh-vm" {
  name = "ssh-vm"
  machine_type = "e2-standard-2"
  project = var.pro
  tags = ["allow-ssh"]
  zone = "europe-west1-b"

  boot_disk {
    initialize_params {
      image = "ubuntu-2004-focal-v20221213"
    }
  }

  network_interface {
    subnetwork = google_compute_subnetwork.subnetwork.self_link
    access_config {
      nat_ip = google_compute_address.static.address
    }
  }

  metadata = {
    startup-script = <<-EOF
        #!/bin/bash
        sudo snap install docker
        sudo docker version > file1.txt
        sleep 5
        sudo docker run -d --rm -p ${var.server_port}:${var.server_port} \
        busybox sh -c "while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; \
        echo 'yo'; } | nc -l -p ${var.server_port}; done"
        EOF
  }
}

One can see that the idea is to spin up docker and run the server that listens on :80. When I ssh onto this instance and run sudo docker ps, I receive the info that the process is running and serving on 80.
The problem is that I have the same startup script within Terraform's instance_template module, but when I ssh into any of the machines from the MIG and run the same command, it says that the docker command is not found.
Here's the configuration of the module:

module "instance_template" {
  source = "terraform-google-modules/vm/google//modules/instance_template"
  version = "7.9.0"
  region = var.region
  project_id = var.pro
  network = google_compute_network.vpc-network.self_link
  subnetwork = google_compute_subnetwork.subnetwork.self_link
  service_account = {
    email = google_service_account.service-acc.email
    scopes = ["cloud-platform"]
  }

  name_prefix = "webserver"
  tags = ["template-vm", "allow-ssh"]
  machine_type = "e2-standard-2"
  startup_script = <<-EOF
  #!/bin/bash
  sudo snap install docker
  sudo docker version > docker_version.txt
  sleep 5
  sudo docker run -d --rm -p ${var.server_port}:${var.server_port} \
  busybox sh -c "while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; \
  echo 'yo'; } | nc -l -p ${var.server_port}; done"
  EOF
  source_image = "https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/images/ubuntu-2004-focal-v20221213"
  disk_size_gb = 10
  disk_type = "pd-balanced"
  preemptible = true

}

I checked and the module's attribute for the startup script is indeed startup_script and not metadata_startup_script.


问:
NextAuth.js signIn() method not working using serverless-http in AWS Lambda
I am trying to deploy NextJs and NextAuth.js to AWS using CDK (Cloud Development Kit). I have cloned the NextAuth.js example project (https://github.com/nextauthjs/next-auth-example) and
installed "serverless-http" for handling the binding from Lambda to NextJs. I attempted to follow this guide https://remaster.com/blog/nextjs-lambda-serverless-framework but using AWS CDK instead of the serverless.yml file as I am integrating it with existing infrastructure.

next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  images: {
    unoptimized: true
  },
  output: 'standalone'
}

module.exports = nextConfig
```
<p>[...nextauth].ts (From the example but using a simple credentials provider that always resolves):</p>
```import NextAuth, { NextAuthOptions } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text", placeholder: "jsmith" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials, req) {
        return { id: "1", name: "J Smith", email: "jsmith@example.com" }
      }
    })

  ],
  theme: {
    colorScheme: "light",
  },
  callbacks: {
    async jwt({ token }) {
      token.userRole = "admin"
      return token
    },
  },
}

export default NextAuth(authOptions)
```
<p>server.ts:</p>
```import { NextConfig } from "next";
import NextServer from "next/dist/server/next-server";
import serverless from "serverless-http";
// @ts-ignore
import { config } from "./.next/required-server-files.json";

const nextServer = new NextServer({
    hostname: "localhost",
    port: 3000,
    dir: __dirname,
    dev: false,
    conf: {
        ...(config as NextConfig),
    },
});

export const handler = serverless(nextServer.getRequestHandler());
```
<p>It is being built using the following script:</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/bash

BUILD_FOLDER=.dist

yarn build
rm -rf $BUILD_FOLDER
mv .next/standalone/ $BUILD_FOLDER/
cp -r .next/static $BUILD_FOLDER/.next
rm $BUILD_FOLDER/server.js
cp -r next.config.js $BUILD_FOLDER/
cp -r node_modules/serverless-http $BUILD_FOLDER/node_modules/serverless-http
tsc server.ts --outDir .dist --esModuleInterop true
cp -r public $BUILD_FOLDER/
</code>```

This is deployed using AWS written in CDK C#. Primarily using a HttpApi and a single Lambda. Each configured as shown below:

Lambda:

var function = new Function(this, "nextjs-function", new FunctionProps
{
    Code = Code.FromAsset(...".dist"),
    Handler = "server.handler",
    Runtime = Runtime.NODEJS_16_X,
    ...
    Environment = new Dictionary<string, string>
    {
        { "NEXTAUTH_URL", "https://myDomainName.com" },
        { "NEXTAUTH_SECRET", portalSecret },
    }
});
```
<p>HttpApi:</p>
<pre class="lang-cs prettyprint-override"><code>var httpApi = new HttpApi(this, "http-api", new HttpApiProps
{
    DisableExecuteApiEndpoint = true,
    DefaultIntegration = new HttpLambdaIntegration("nextjs-route", function),
    DefaultDomainMapping = new DomainMappingOptions
    {
        DomainName = "myDomainName.com"
    }
});
</code>```

Opening the deployed webpage and clicking the "Sign In" button at the top, I get taken to /api/auth/signin?callbackUrl=%2F with a form. Without touching the credentials I click "Sign in with credentials". This results in the page reloading and nothing happening. Expected behaviour should be a session and a redirect back to the home page (/) as is happening when running it locally using either yarn dev or yarn build && yarn start.

I get no errors client/server-side thus leaving me in the dark.

I suspect that it has to do with domain configuration but I am unable to find the problem. I tested with another NextJs/NextAuth project using a AWS Cognito provider. This also had problems as when I clicked the sign in button I got an "Unexpected token" error due to the underlying signIn(...) function (from the NextAuth library) trying to parse the fetched page as JSON, which turned out to be the sign-in-page. Thus my suspicion of something domain-related.

Body:
I am trying to deploy NextJs and NextAuth.js to AWS using CDK (Cloud Development Kit). I have cloned the NextAuth.js example project (https://github.com/nextauthjs/next-auth-example) and
installed "serverless-http" for handling the binding from Lambda to NextJs. I attempted to follow this guide https://remaster.com/blog/nextjs-lambda-serverless-framework but using AWS CDK instead of the serverless.yml file as I am integrating it with existing infrastructure.

next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  images: {
    unoptimized: true
  },
  output: 'standalone'
}

module.exports = nextConfig

[...nextauth].ts (From the example but using a simple credentials provider that always resolves):

import NextAuth, { NextAuthOptions } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text", placeholder: "jsmith" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials, req) {
        return { id: "1", name: "J Smith", email: "jsmith@example.com" }
      }
    })

  ],
  theme: {
    colorScheme: "light",
  },
  callbacks: {
    async jwt({ token }) {
      token.userRole = "admin"
      return token
    },
  },
}

export default NextAuth(authOptions)

server.ts:

import { NextConfig } from "next";
import NextServer from "next/dist/server/next-server";
import serverless from "serverless-http";
// @ts-ignore
import { config } from "./.next/required-server-files.json";

const nextServer = new NextServer({
    hostname: "localhost",
    port: 3000,
    dir: __dirname,
    dev: false,
    conf: {
        ...(config as NextConfig),
    },
});

export const handler = serverless(nextServer.getRequestHandler());

It is being built using the following script:

#!/bin/bash

BUILD_FOLDER=.dist

yarn build
rm -rf $BUILD_FOLDER
mv .next/standalone/ $BUILD_FOLDER/
cp -r .next/static $BUILD_FOLDER/.next
rm $BUILD_FOLDER/server.js
cp -r next.config.js $BUILD_FOLDER/
cp -r node_modules/serverless-http $BUILD_FOLDER/node_modules/serverless-http
tsc server.ts --outDir .dist --esModuleInterop true
cp -r public $BUILD_FOLDER/

This is deployed using AWS written in CDK C#. Primarily using a HttpApi and a single Lambda. Each configured as shown below:

Lambda:

var function = new Function(this, "nextjs-function", new FunctionProps
{
    Code = Code.FromAsset(...".dist"),
    Handler = "server.handler",
    Runtime = Runtime.NODEJS_16_X,
    ...
    Environment = new Dictionary<string, string>
    {
        { "NEXTAUTH_URL", "https://myDomainName.com" },
        { "NEXTAUTH_SECRET", portalSecret },
    }
});

HttpApi:

var httpApi = new HttpApi(this, "http-api", new HttpApiProps
{
    DisableExecuteApiEndpoint = true,
    DefaultIntegration = new HttpLambdaIntegration("nextjs-route", function),
    DefaultDomainMapping = new DomainMappingOptions
    {
        DomainName = "myDomainName.com"
    }
});

Opening the deployed webpage and clicking the "Sign In" button at the top, I get taken to /api/auth/signin?callbackUrl=%2F with a form. Without touching the credentials I click "Sign in with credentials". This results in the page reloading and nothing happening. Expected behaviour should be a session and a redirect back to the home page (/) as is happening when running it locally using either yarn dev or yarn build && yarn start.

I get no errors client/server-side thus leaving me in the dark.

I suspect that it has to do with domain configuration but I am unable to find the problem. I tested with another NextJs/NextAuth project using a AWS Cognito provider. This also had problems as when I clicked the sign in button I got an "Unexpected token" error due to the underlying signIn(...) function (from the NextAuth library) trying to parse the fetched page as JSON, which turned out to be the sign-in-page. Thus my suspicion of something domain-related.


问:
how do I implement in .net core Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1"); Response.Charset = "ISO-8859-1"; Response.Write(html);
```<code>        Response.Clear();
        Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
        Response.HeaderEncoding = Encoding.GetEncoding("ISO-8859-1");
        Response.Charset = "ISO-8859-1";
        Response.Write(html);
</code>```

How do I Implement these things in .net core

Body:
        Response.Clear();
        Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
        Response.HeaderEncoding = Encoding.GetEncoding("ISO-8859-1");
        Response.Charset = "ISO-8859-1";
        Response.Write(html);

How do I Implement these things in .net core


问:
FastAPI's jsonanble_encoder raises ValueError when consuming dict from other endpoint
I have a very simple FastAPI app. Directly calling endpoint "b/{id}", correctly returns the JSON object. However, calling endpoint endpoint "a/{id}"—which returns the response of method b(id)—results in the following error:

```<code>jsonable_encoder raise ValueError(errors) from e
ValueError: [TypeError("'coroutine' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
</code>```

Here is my sample code

@app.post("/a/{id}", response_class=JSONResponse)
def a(id):
    return b(id)

@app.get("/b/{id}", response_class=JSONResponse)
def b(id):
    return {"id":id}
```

Somehow the jsonable_encoder is having problems but I don't know why.

Body:
I have a very simple FastAPI app. Directly calling endpoint "b/{id}", correctly returns the JSON object. However, calling endpoint endpoint "a/{id}"—which returns the response of method b(id)—results in the following error:

jsonable_encoder raise ValueError(errors) from e
ValueError: [TypeError("'coroutine' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]

Here is my sample code

@app.post("/a/{id}", response_class=JSONResponse)
def a(id):
    return b(id)

@app.get("/b/{id}", response_class=JSONResponse)
def b(id):
    return {"id":id}

Somehow the jsonable_encoder is having problems but I don't know why.


问:
Strange bug - Some elements are visible when I run app from Xcode, but not if I start running the app from device
Context: Native iOS app developed with Swift which manages external control units via bluetooth. I use Xcode Version 14.2, but it used to happen with older versions as well. Tested on devices with iOS 15 and 16.

In a specific section what the app has to do is:

take the data through the Bluetooth input and output

go to the outputs screen and present the outputs

from the outputs screen go to the inputs screen and show them

The problem is as follows.
If I take a physical iPhone and connect it to the Mac, then start the app from Xcode, everything works fine.
If, with the same iPhone, I start the app not from Xcode but with a tap from the iPhone screen, the app starts correctly, connects via Bluetooth, shows all the outputs correct, while for the inputs they are all correct except the last. The last one is never displayed, all the others are.

The main problem is that I don't know how to debug since it only happens when the app starts unlinked from Xcode. Does anyone know of other ways to troubleshoot the problem or have had similar problems and know of possible solutions?


问:
Flutter background job for access token
I want to implement a background job that will run in the background for the access token and refresh token. If the application is closed or not used, will still count the time of the access token and if the user opens the application again to have access if the token is not expired. My access token has 1 hour timer. I hope I explained it good. Thanks in advance any help will be appreciated.

I use flutter_secure_storage to store my access token and refresh token values.

Title: Flutter background job for access token


问:
not getting serial data
not getting serial data means sometime UART_FIFO_OVF event occurs

here we can see when data is on uart at the second instant data length is showing 225bytes but when we print the data buffer its not showing the full data and UART_FIFO_OVF event occurs

do you have any suggestions on this to avoid this situation?

curr_data_len :225
uart data:$1,211,172,0,SENDDATA,1,1,1,G,HTTPGET,HTTPGET,SaveTicket?data=tkt|50609012023151839|506|195|1|3|6|1|1|3|257|1|0|0|0|0|24.00|0.00|0.00|0.00|0.00|0.00|0|24.00|09/01/2023|15:18:39|2|E261706111||0.00|0.00|0|0|50|552|10163|,14883
$0,OK,0,0,0,0,0,0,0,798*
curr_data_len :225
uart data:|0.00|0.00|0.00|0.00|0|24.00|09/01/2023|15:18:39|2|E261706111||0.00|0.00|0|0|50|552|10164|,14885
UART_FIFO_OVF

Title: not getting serial data


问:
What is the best way to make persistent in-app notifications with Firebase?
I learned how to use push notifications at Firebase. It works. As the next step, I want to add persistent in-app notifications, similar to Stackoverflow, Facebook, Instagram, etc

Currently we're using at Firestore and Real-Time database.

We have several use cases:

Users' content is viewed

Users receive a message from another user

Some system update about a new feature

Where should we keep these notification messages? Should it be in the same place where all original messages are stored? Or should each user have notification collections? Or are there some other ways to solve it?

I found a lot of stuff about push notifications, but I can't find anything how to handle regular persistent notifications.


问:
Cookie is not being set - Nodejs and express
I'm trying to set a cookie on the browser via httponly but is not being set. I deployed the server and the client on different hosts, and I think is maybe that but I can't find a solution.

That's how I configure the cookie object when it comes to sending the cookie to the browser:

```<code>res.cookie('refreshtoken', token, {
    httpOnly: true,
    secure: true,
    sameSite: "none"
})
</code>```

How can I solve this problem?

Body:
I'm trying to set a cookie on the browser via httponly but is not being set. I deployed the server and the client on different hosts, and I think is maybe that but I can't find a solution.

That's how I configure the cookie object when it comes to sending the cookie to the browser:

res.cookie('refreshtoken', token, {
    httpOnly: true,
    secure: true,
    sameSite: "none"
})

How can I solve this problem?


问:
Can not enter subscript via console (lost before System.in)

Problem

In short, if you try out the following snippet:

Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine(); // enter ₂

System.out.println(text); // 2, not ₂
```
<p>and <strong>enter a subscript number</strong>, like <code>₂</code>, <code>text</code> is actually <code>2</code>, <strong>without subscript</strong>.</p>
<h3>Tests</h3>
<p>Now, I tried to factor out some classic reasons here.</p>
<h4>Printing?</h4>
<p>You can also compare the string instead of printing it, and it is still incorrect:</p>
<pre class="lang-java prettyprint-override"><code>Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine(); // enter ₂

System.out.println(text.equals("₂")); // false
System.out.println(text.equals("2")); // true
</code>```

Scanner?

Scanner is capable of doing it correctly, for example if the input is given as String:

Scanner scanner = new Scanner("₂");
String text = scanner.nextLine();

System.out.println(text); // now prints ₂
```
<h4>System.in?</h4>
<p>The issue is still present if factoring out <code>Scanner</code> completely, for example:</p>
<pre class="lang-java prettyprint-override"><code>byte[] data = System.in.readAllBytes(); // enter ₂
String text = new String(data, StandardCharsets.UTF_8).trim();

System.out.println(text);  // 2, not ₂
</code>```

Encoding?

It does not seem to be a general problem with Unicode/encoding. When entering another character, such as , it works as expected.

Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine(); // enter

System.out.println(text); //
```

Hypothesis

It seems that the subscript is lost between the console input and System.in, possibly even before reaching Java at all.

Maybe this is a console specific quirk I am not aware of? I tried it with VSC and Windows CMD (Java 18).

Body:
Problem

In short, if you try out the following snippet:

Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine(); // enter ₂

System.out.println(text); // 2, not ₂

and enter a subscript number, like ₂, text is actually 2, without subscript.

Tests

Now, I tried to factor out some classic reasons here.

Printing?

You can also compare the string instead of printing it, and it is still incorrect:

Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine(); // enter ₂

System.out.println(text.equals("₂")); // false
System.out.println(text.equals("2")); // true

Scanner?

Scanner is capable of doing it correctly, for example if the input is given as String:

Scanner scanner = new Scanner("₂");
String text = scanner.nextLine();

System.out.println(text); // now prints ₂

System.in?

The issue is still present if factoring out Scanner completely, for example:

byte[] data = System.in.readAllBytes(); // enter ₂
String text = new String(data, StandardCharsets.UTF_8).trim();

System.out.println(text);  // 2, not ₂

Encoding?

It does not seem to be a general problem with Unicode/encoding. When entering another character, such as , it works as expected.

Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine(); // enter

System.out.println(text); //

Hypothesis

It seems that the subscript is lost between the console input and System.in, possibly even before reaching Java at all.

Maybe this is a console specific quirk I am not aware of? I tried it with VSC and Windows CMD (Java 18).


问:
Method that will be executed before every Route method call in ASPNET Core MVC WebApi
Is there a way to define method that will be executed before every Route method call.

```<code>public class ExampleController : ControllerBase
{
    private static int i;

    private void funcToCall()
    {
        i++;
    }

    [HttpGet]
    public IActionResult Ping()
    {
        return Ok("Pong")
    }
}
</code>```

I want to call funcToCall whenever Ping Route is called. I also cannot do it in constructor, because lifetime of controller is Singleton.

I was wondering if overriding [HttpGet], [HttpPost] etc... attributes will work, but I also belive it may be simpler solution.

Body:
Is there a way to define method that will be executed before every Route method call.

public class ExampleController : ControllerBase
{
    private static int i;

    private void funcToCall()
    {
        i++;
    }

    [HttpGet]
    public IActionResult Ping()
    {
        return Ok("Pong")
    }
}

I want to call funcToCall whenever Ping Route is called. I also cannot do it in constructor, because lifetime of controller is Singleton.

I was wondering if overriding [HttpGet], [HttpPost] etc... attributes will work, but I also belive it may be simpler solution.


问:
How to use MockMvc and Mockito(?) to make my stub return status code 500 or 400?
I'm testing spring controller that sends requests to 3rd party API and I would also like to write a JUnit test that stubs / mocks the API sending back HTTP 500 and 400 responses to see how it handles error answers. Being new to spring and autotesting, it is tough for me to see what I have to do to stub these HTTP 500 responses.
Here is my class with positive test method.

```<code>@ExtendWith(SpringExtension.class)
@WebMvcTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-cloud-stub.properties")
@ContextConfiguration(classes = {...})
public class ControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private BisTechnicalChecksClient client;

    @Test
    public void TestMethod() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
        ObjectReader reader = mapper.reader().forType(new TypeReference<List<ClientsByAddrWithStartDateResponse>>() {
        });
        ClientsByAddrWithStartDateRequest request =
                mapper.readValue(new File("request_controller.json"),
                        ClientsByAddrWithStartDateRequest.class);

        List<ClientsByAddrWithStartDateResponse> response = reader.readValue(new File(
                "response_controller.json"));

        when(client.getClientsByAddrWithStartDate(any(ClientsByAddrWithStartDateRequest.class)))
                .thenReturn(response);

        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders
                        .post("get-clients-by-addr-with-start-date")
                        .contentType(MediaType.APPLICATION_JSON_VALUE)
                        .header("param1", "value1")
                        .content(mapper
                                .writer()
                                .withDefaultPrettyPrinter()
                                .writeValueAsString(request)))
                .andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
                .andReturn();

        String stringResponse = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
        List<ClientsByAddrWithStartDateResponse> actualResponse = reader.readValue(stringResponse);

        List<ClientsByAddrWithStartDateResponse> expectResponse = reader.readValue(new File(
                "response_controller.json"));

        Assertions.assertThat(actualResponse).isEqualTo(expectResponse);
    }

}
</code>```

I've been trying to find a way to return preset MockHttpServletResponse when stubbed method is called but to no avail so far.
What do I need to change for my stub to return 500 / 400 statuses and work properly?

Body:
I'm testing spring controller that sends requests to 3rd party API and I would also like to write a JUnit test that stubs / mocks the API sending back HTTP 500 and 400 responses to see how it handles error answers. Being new to spring and autotesting, it is tough for me to see what I have to do to stub these HTTP 500 responses.
Here is my class with positive test method.

@ExtendWith(SpringExtension.class)
@WebMvcTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-cloud-stub.properties")
@ContextConfiguration(classes = {...})
public class ControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private BisTechnicalChecksClient client;

    @Test
    public void TestMethod() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
        ObjectReader reader = mapper.reader().forType(new TypeReference<List<ClientsByAddrWithStartDateResponse>>() {
        });
        ClientsByAddrWithStartDateRequest request =
                mapper.readValue(new File("request_controller.json"),
                        ClientsByAddrWithStartDateRequest.class);

        List<ClientsByAddrWithStartDateResponse> response = reader.readValue(new File(
                "response_controller.json"));

        when(client.getClientsByAddrWithStartDate(any(ClientsByAddrWithStartDateRequest.class)))
                .thenReturn(response);

        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders
                        .post("get-clients-by-addr-with-start-date")
                        .contentType(MediaType.APPLICATION_JSON_VALUE)
                        .header("param1", "value1")
                        .content(mapper
                                .writer()
                                .withDefaultPrettyPrinter()
                                .writeValueAsString(request)))
                .andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
                .andReturn();

        String stringResponse = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
        List<ClientsByAddrWithStartDateResponse> actualResponse = reader.readValue(stringResponse);

        List<ClientsByAddrWithStartDateResponse> expectResponse = reader.readValue(new File(
                "response_controller.json"));

        Assertions.assertThat(actualResponse).isEqualTo(expectResponse);
    }

}

I've been trying to find a way to return preset MockHttpServletResponse when stubbed method is called but to no avail so far.
What do I need to change for my stub to return 500 / 400 statuses and work properly?


问:
Tabified QDockWidget does not save its layout

Problem

I'm creating the main window with multiple dock widgets. My current goal is to save the whole layout on exit. Everything works fine until I try to tabify some of my dock widgets using the tabifyDockWidget() method. And now the tabified widgets don't save their positions for some reason.

Example

Here is the minimal reproducible example.
You can check the described behavior by (un)commenting the tabifyDockWidget() line and resizing the dock widgets.
Of course, don't forget to remove the saved settings file to reset the layout to its initial state.

```<code>#include "mainwindow.h"
#include <QDockWidget>
#include <QLabel>
#include <QSettings>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    resize(800, 320);

    auto centralWidget = new QLabel("Central Widget", this);
    centralWidget->setAlignment(Qt::AlignCenter);
    centralWidget->setStyleSheet("border: 2px solid black");
    setCentralWidget(centralWidget);

    auto dockLeft1 = new QDockWidget(this);
    auto dockLeft2 = new QDockWidget(this);
    auto dockRight = new QDockWidget(this);

    dockLeft1->setObjectName("dockLeft1");
    dockLeft2->setObjectName("dockLeft2");
    dockRight->setObjectName("dockRight");

    dockLeft1->setWindowTitle(tr("Left Dock 1"));
    dockLeft2->setWindowTitle(tr("Left Dock 2"));
    dockRight->setWindowTitle(tr("Right Dock"));

    addDockWidget(Qt::LeftDockWidgetArea, dockLeft1);
    addDockWidget(Qt::LeftDockWidgetArea, dockLeft2);
    addDockWidget(Qt::RightDockWidgetArea, dockRight);

    tabifyDockWidget(dockLeft1, dockLeft2);

    QSettings settings("foo", "bar");
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("state").toByteArray());
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    QSettings settings("foo", "bar");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("state", saveState());

    QMainWindow::closeEvent(event);
}
</code>```

Behavior without tabifyDockWidget()

Resize left and right dock widget.

Close and reopen the application.

The layout settings are properly restored.

Behavior with tabifyDockWidget()

Resize left and right dock widget.

Close and reopen the application.

The restored layout settings are wrong for the left (tabified) dock.

What's the reason?

Is there any proper workaround?

Body:
Problem

I'm creating the main window with multiple dock widgets. My current goal is to save the whole layout on exit. Everything works fine until I try to tabify some of my dock widgets using the tabifyDockWidget() method. And now the tabified widgets don't save their positions for some reason.

Example

Here is the minimal reproducible example.
You can check the described behavior by (un)commenting the tabifyDockWidget() line and resizing the dock widgets.
Of course, don't forget to remove the saved settings file to reset the layout to its initial state.

#include "mainwindow.h"
#include <QDockWidget>
#include <QLabel>
#include <QSettings>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    resize(800, 320);

    auto centralWidget = new QLabel("Central Widget", this);
    centralWidget->setAlignment(Qt::AlignCenter);
    centralWidget->setStyleSheet("border: 2px solid black");
    setCentralWidget(centralWidget);

    auto dockLeft1 = new QDockWidget(this);
    auto dockLeft2 = new QDockWidget(this);
    auto dockRight = new QDockWidget(this);

    dockLeft1->setObjectName("dockLeft1");
    dockLeft2->setObjectName("dockLeft2");
    dockRight->setObjectName("dockRight");

    dockLeft1->setWindowTitle(tr("Left Dock 1"));
    dockLeft2->setWindowTitle(tr("Left Dock 2"));
    dockRight->setWindowTitle(tr("Right Dock"));

    addDockWidget(Qt::LeftDockWidgetArea, dockLeft1);
    addDockWidget(Qt::LeftDockWidgetArea, dockLeft2);
    addDockWidget(Qt::RightDockWidgetArea, dockRight);

    tabifyDockWidget(dockLeft1, dockLeft2);

    QSettings settings("foo", "bar");
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("state").toByteArray());
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    QSettings settings("foo", "bar");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("state", saveState());

    QMainWindow::closeEvent(event);
}

Behavior without tabifyDockWidget()

Resize left and right dock widget.

Close and reopen the application.

The layout settings are properly restored.

Behavior with tabifyDockWidget()

Resize left and right dock widget.

Close and reopen the application.

The restored layout settings are wrong for the left (tabified) dock.

What's the reason?

Is there any proper workaround?


问:
Springboot Gradle : PKIX path building failed
I am trying to build some services in my local. But while building I am getting following error

```<code>A problem occurred configuring root project 'MyService'.
> Could not resolve all artifacts for configuration ':classpath'.

> Could not resolve org.springframework.boot:spring-boot-gradle-plugin:2.2.7.RELEASE.
     Required by:
         project :
      > Could not resolve org.springframework.boot:spring-boot-gradle-plugin:2.2.7.RELEASE.
         > Could not get resource 'https://plugins.gradle.org/m2/org/springframework/boot/spring-boot-gradle-plugin/2.2.7.RELEASE/spring-boot-gradle-plugin-2.2.7.RELEASE.pom'.
            > Could not HEAD 'https://plugins.gradle.org/m2/org/springframework/boot/spring-boot-gradle-plugin/2.2.7.RELEASE/spring-boot-gradle-plugin-2.2.7.RELEASE.pom'.
               > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

Similar PKIX issue I am facing with all the services.

I am using IntelliJ and project uses Gradle.
This is also a new system, but I have installed JDK in the macOS. And JDK path shows correctly in the project.

When I open the dependency URL I am able to access in my chrome browser.

Most solution given seems to be for windows.
Anything differently do I have to do for macOS?

Body:
I am trying to build some services in my local. But while building I am getting following error

A problem occurred configuring root project 'MyService'.
> Could not resolve all artifacts for configuration ':classpath'.

> Could not resolve org.springframework.boot:spring-boot-gradle-plugin:2.2.7.RELEASE.
     Required by:
         project :
      > Could not resolve org.springframework.boot:spring-boot-gradle-plugin:2.2.7.RELEASE.
         > Could not get resource 'https://plugins.gradle.org/m2/org/springframework/boot/spring-boot-gradle-plugin/2.2.7.RELEASE/spring-boot-gradle-plugin-2.2.7.RELEASE.pom'.
            > Could not HEAD 'https://plugins.gradle.org/m2/org/springframework/boot/spring-boot-gradle-plugin/2.2.7.RELEASE/spring-boot-gradle-plugin-2.2.7.RELEASE.pom'.
               > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Similar PKIX issue I am facing with all the services.

I am using IntelliJ and project uses Gradle.
This is also a new system, but I have installed JDK in the macOS. And JDK path shows correctly in the project.

When I open the dependency URL I am able to access in my chrome browser.

Most solution given seems to be for windows.
Anything differently do I have to do for macOS?


问:
How to Run Selenium Script in multiple test environments by Page Objects Model
enter image description hereI have 3 property files and I want to get properties value on behalf of the environment

Currently, I am using 1 properties file for reading URLs but now I want to fetch URLs on behalf of environments like Dev, UAT, Staging

```<code>public Base_Pace()  {

    try {

        prop = new Properties();
        String projectRootPath = TC_TestUtil.getProjectDirectory();
        FileInputStream ip = null;
         if(TC_TestUtil.isWindows()) {
             ip = new FileInputStream(projectRootPath + "\\" + "test.properties");
          }else {
             ip = new FileInputStream(projectRootPath + "/" + "test.properties");
          }
        prop.load(ip);

        }
    catch (FileNotFoundException e) {
    e.printStackTrace();
    }

    catch (IOException e) {
        e.printStackTrace();
    }
</code>```

Body:
enter image description hereI have 3 property files and I want to get properties value on behalf of the environment

Currently, I am using 1 properties file for reading URLs but now I want to fetch URLs on behalf of environments like Dev, UAT, Staging

public Base_Pace()  {

    try {

        prop = new Properties();
        String projectRootPath = TC_TestUtil.getProjectDirectory();
        FileInputStream ip = null;
         if(TC_TestUtil.isWindows()) {
             ip = new FileInputStream(projectRootPath + "\\" + "test.properties");
          }else {
             ip = new FileInputStream(projectRootPath + "/" + "test.properties");
          }
        prop.load(ip);

        }
    catch (FileNotFoundException e) {
    e.printStackTrace();
    }

    catch (IOException e) {
        e.printStackTrace();
    }


问:
cv2 warpAffine, matrix transformation
The problem in this link: Group multiple barcodes on a single sticker together from an image with multiple stickers using python

```<code>H = np.eye(3)

H[0:2,2] = tl # origin
H[:2,0] = vx / lx
H[:2,1] = vy / ly

dst = cv.warpAffine(src=image,
    M=H[:2], dsize=(int(lx), int(ly)),
    flags=cv.INTER_LINEAR | cv.WARP_INVERSE_MAP)
</code>```

Could anyone can explain this part of code? What I understand on warpAffine, the M value is matrix transformation, but why it uses the top left origin coordinate and the ratio of dividing the width by length?

Title: cv2 warpAffine, matrix transformation

Body:
The problem in this link: Group multiple barcodes on a single sticker together from an image with multiple stickers using python

H = np.eye(3)

H[0:2,2] = tl # origin
H[:2,0] = vx / lx
H[:2,1] = vy / ly

dst = cv.warpAffine(src=image,
    M=H[:2], dsize=(int(lx), int(ly)),
    flags=cv.INTER_LINEAR | cv.WARP_INVERSE_MAP)

Could anyone can explain this part of code? What I understand on warpAffine, the M value is matrix transformation, but why it uses the top left origin coordinate and the ratio of dividing the width by length?


问:
Can processes which are in sleep states creates deadlocks in mysql server?
I'am using nodeJs createpool to connect to database and pool.query to execute a sql statement.
Sometime My data base server is taking a lot of time to execute queries.
It shows deadlock and sleep queries 'waiting for handler commit'. After killing those sleep query deadlocks gets resolved everything start running smooth what might be the reason behind this please help me guy.
I'am sharing the screen shot of process list below.

I tried using start transaction; commit;
Tried using routines procedures,


问:
What does ConnectionProviderError means in Amplify AppSync in Flutter SDK
We are using Flutter SDK for Amplify AppSync for using Real Time Subscription.

https://pub.dev/packages/amplify_api

Sometime we receive error on AppSync subscription. As mentioned below

Error thrown ApiException(message: Subscription item event failed with error: Unauthorized, recoverySuggestion: , underlyingException: The operation couldn’t be completed. (AppSyncRealTimeClient.ConnectionProviderError error 5.)).

Error thrown ApiException(message: Subscription item event failed with error, recoverySuggestion: , underlyingException: The operation couldn’t be completed. (AppSyncRealTimeClient.ConnectionProviderError error 4.)).

I tried to figure out what does the error 4 and error 5 means, but was unable to do so.

I checked their swift SDK for ConnectionProvider

https://github.com/aws-amplify/aws-appsync-realtime-client-ios/tree/main/AppSyncRealTimeClient/ConnectionProvider

https://github.com/aws-amplify/aws-appsync-realtime-client-ios/blob/main/AppSyncRealTimeClient/ConnectionProvider/ConnectionProviderError.swift

But I could not figure out the cause for error. Can someone please help to identify when those error will be thrown. Thanks


问:
AWS ServerlessV2 CPU usage is always high
I've been running a test stack: WordPress on ECS with a ServerlessV2 database with MinCapacity=0.5 and MaxCapacity=2 for a few weeks. This is a test site with nobody accessing it except me.

The load balancer's health check points to a dumb PHP script that only echos "pong" without ever connecting to the database.

To my surprise, the Aurora ServerlessV2 server was almost always between 1.5 and 2 ACUs. I changed the max to 1, and it's almost always at 1.

I killed the web servers. The DB instance has 0 connections, no queries, but still: it's at 1 ACU most of the time, and the CPU averages 55%-65% steadily.

All CloudWatch log exports are disabled; enhanced monitoring is disabled; performance insights are disabled. I'm running the latest 3.02.2 version.

Yet, my totally idle Aurora ServerlessV2 has 55%+ CPU with no connections and no queries and requires 1 ACU to do nothing because 0.5 ACU isn't enough.

I tested the same with a single t3.medium instance, and the CPU hovers between 2% and 8%.

Anyone has idea why ServerlessV2 needs so much CPU and ACU for doing absolutely nothing?

I would be expecting ServerlessV2 to use less than 20% of CPU and be steadily at 0.5 ACU when idle with no options (enhanced monitoring, performance insights) enabled.


问:
compressed sparse row and Jacobi iterative method
I've tried implementing Jacobi method for compressed sparse row format. But i couldnt obtain the output correctly. Below is the coding i tried. I'm trying with a 4 by 4 sparse matrix which is a tridiagonal matrix stored in compressed form before implementing Jacobi iterative method. Please help.

```<code>clear all;
close all;
clc;

H=4;
a=2;
b=-1;
c=-1;
A = diag(a*ones(1,H)) + diag(b*ones(1,H-1),1) + diag(c*ones(1,H-1),-1);%Matrix A
n = size(A,1); % no of rows
m = size(A,2); % no of columns

V = [];
C = [];
R = [];

counter=1;
R= [counter];
for i=1:n
  for j=1:m
    if (A(i,j) ~= 0)
      V = [V A(i,j)];
      C = [C j];
      counter=counter+1;
    end
    R(i+1)=counter;
  end
end

b = [9,18,24,3];
x_new = [1 ; 1 ; 1 ; 1];

eps = 1e-5;  % 1 x 10^(-10).
error = 1000; % use any large value greater than eps to make sure that the loop can work

counter2=1;
while (error > eps)

  x_old = x_new;

  for i=1:length(R)-1  %modified
    t = 0;
    for j=R(i):R(i+1)-1 %modified
      if (C(j)~=i)   %not equal

        t = t + x_old(C(j))*A(i,C(j)); %modified
      end
    end
    x_new(i,1) = (b(i) - t)/A(i,C(j)); % is a row vector
  end
  error = norm(x_new-x_old);
  counter2=counter2+1;
  end

x_new % print x

Expected output is
[28.1987   47.3978   48.5979   25.7986]
</code>```

this is the coding i tried and the expected output is above. Thank you for your time and consideration.

Body:
I've tried implementing Jacobi method for compressed sparse row format. But i couldnt obtain the output correctly. Below is the coding i tried. I'm trying with a 4 by 4 sparse matrix which is a tridiagonal matrix stored in compressed form before implementing Jacobi iterative method. Please help.

clear all;
close all;
clc;

H=4;
a=2;
b=-1;
c=-1;
A = diag(a*ones(1,H)) + diag(b*ones(1,H-1),1) + diag(c*ones(1,H-1),-1);%Matrix A
n = size(A,1); % no of rows
m = size(A,2); % no of columns

V = [];
C = [];
R = [];

counter=1;
R= [counter];
for i=1:n
  for j=1:m
    if (A(i,j) ~= 0)
      V = [V A(i,j)];
      C = [C j];
      counter=counter+1;
    end
    R(i+1)=counter;
  end
end

b = [9,18,24,3];
x_new = [1 ; 1 ; 1 ; 1];

eps = 1e-5;  % 1 x 10^(-10).
error = 1000; % use any large value greater than eps to make sure that the loop can work

counter2=1;
while (error > eps)

  x_old = x_new;

  for i=1:length(R)-1  %modified
    t = 0;
    for j=R(i):R(i+1)-1 %modified
      if (C(j)~=i)   %not equal

        t = t + x_old(C(j))*A(i,C(j)); %modified
      end
    end
    x_new(i,1) = (b(i) - t)/A(i,C(j)); % is a row vector
  end
  error = norm(x_new-x_old);
  counter2=counter2+1;
  end

x_new % print x

Expected output is
[28.1987   47.3978   48.5979   25.7986]

this is the coding i tried and the expected output is above. Thank you for your time and consideration.


问:
Measurement Protocol to GA4 - no Event report
I sent Even success3 to GA4 via Measurement Protocol.
Why i see this Event only in Realtime report?

I sent more than 300 event success3 every month.
I started to send this event from 10 december 2022.

I need to see this Event in usual Report. Its very important Event for me.

Screenshots:
Realtime report
Event report

```<code>(
    [client_id] => 1362433930.1668150326
    [non_personalized_ads] =>
    [events] => Array
        (
            [0] => stdClass Object
                (
                    [name] => success3
                    [params] => stdClass Object
                        (
                            [laen] => Väikelaen
                            [summa] => 500
                            [lang] => et
                        )

                )

        )

)
</code>```

Google Analytics support said:

This could be because of issues with the event configuration via
Measurement Protocol (event shows in Realtime report but is not fully
matched). As Measurement Protocol involves custom code that we are not
able to check, we don't offer any support for it unfortunately, but I
can share you the reference page.

Also you have to bear in mind that the Custom events that you have
created will take some time to be processed in Analytics before they
show up as Existing events.

Finally, the events report has a data threshold to protect the privacy
of the users, so if you have a low user count, it will not appear in
the report.

Body:
I sent Even success3 to GA4 via Measurement Protocol.
Why i see this Event only in Realtime report?

I sent more than 300 event success3 every month.
I started to send this event from 10 december 2022.

I need to see this Event in usual Report. Its very important Event for me.

Screenshots:
Realtime report
Event report

(
    [client_id] => 1362433930.1668150326
    [non_personalized_ads] =>
    [events] => Array
        (
            [0] => stdClass Object
                (
                    [name] => success3
                    [params] => stdClass Object
                        (
                            [laen] => Väikelaen
                            [summa] => 500
                            [lang] => et
                        )

                )

        )

)

Google Analytics support said:

This could be because of issues with the event configuration via
Measurement Protocol (event shows in Realtime report but is not fully
matched). As Measurement Protocol involves custom code that we are not
able to check, we don't offer any support for it unfortunately, but I
can share you the reference page.

Also you have to bear in mind that the Custom events that you have
created will take some time to be processed in Analytics before they
show up as Existing events.

Finally, the events report has a data threshold to protect the privacy
of the users, so if you have a low user count, it will not appear in
the report.


问:
google sheets checkbox increment counter
I am making a checkbox inventory counter that auto increments

I have tried many if then statements to increase a cell value when a box or multiple boxes is check. The best I could do was display a number but it disappears once the checkboxes are unchecked. So I would like and cell to auto increase by 1 after the last or all boxes are checked


问:
Error: "pyflink.fn_execution.coder_impl_fast.IntCoderImpl.encode_to_stream TypeError: an integer is required" when not using print

Version:

Python: 3.8.13

PyFlink: 1.16

Java: 11.0.17

Summary:

I get error when I not using print DataStream.

Code:

```<code>ds = stream_env.add_source(kafka_source, 'Kafka_Source')

ds = ds.map(transform_user_event_data,
            BaseEventSchema().get_type_info()).name('Transform_Data')

# ds.print()

stream_env.execute(cfg.JOB_NAME)

</code>```

Error:

```<code>  File "apache_beam/runners/worker/operations.py", line 346, in apache_beam.runners.worker.operations.Operation.output
  File "apache_beam/runners/worker/operations.py", line 348, in apache_beam.runners.worker.operations.Operation.output
  File "apache_beam/runners/worker/operations.py", line 215, in apache_beam.runners.worker.operations.SingletonConsumerSet.receive
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 169, in pyflink.fn_execution.beam.beam_operations_fast.FunctionOperation.process
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 194, in pyflink.fn_execution.beam.beam_operations_fast.FunctionOperation.process
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 104, in pyflink.fn_execution.beam.beam_operations_fast.IntermediateOutputProcessor.process_outputs
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 169, in pyflink.fn_execution.beam.beam_operations_fast.FunctionOperation.process
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 194, in pyflink.fn_execution.beam.beam_operations_fast.FunctionOperation.process
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 92, in pyflink.fn_execution.beam.beam_operations_fast.NetworkOutputProcessor.process_outputs
  File "pyflink/fn_execution/beam/beam_coder_impl_fast.pyx", line 101, in pyflink.fn_execution.beam.beam_coder_impl_fast.FlinkLengthPrefixCoderBeamWrapper.encode_to_stream
  File "pyflink/fn_execution/coder_impl_fast.pyx", line 273, in pyflink.fn_execution.coder_impl_fast.IterableCoderImpl.encode_to_stream
  File "pyflink/fn_execution/coder_impl_fast.pyx", line 401, in pyflink.fn_execution.coder_impl_fast.RowCoderImpl.encode_to_stream
  File "pyflink/fn_execution/coder_impl_fast.pyx", line 401, in pyflink.fn_execution.coder_impl_fast.RowCoderImpl.encode_to_stream
  File "pyflink/fn_execution/coder_impl_fast.pyx", line 528, in pyflink.fn_execution.coder_impl_fast.IntCoderImpl.encode_to_stream
TypeError: an integer is required
</code>```

If I not comment ds.print() then not error.

Body:
Version:

Python: 3.8.13

PyFlink: 1.16

Java: 11.0.17

Summary:

I get error when I not using print DataStream.

Code:

ds = stream_env.add_source(kafka_source, 'Kafka_Source')

ds = ds.map(transform_user_event_data,
            BaseEventSchema().get_type_info()).name('Transform_Data')

# ds.print()

stream_env.execute(cfg.JOB_NAME)

Error:

  File "apache_beam/runners/worker/operations.py", line 346, in apache_beam.runners.worker.operations.Operation.output
  File "apache_beam/runners/worker/operations.py", line 348, in apache_beam.runners.worker.operations.Operation.output
  File "apache_beam/runners/worker/operations.py", line 215, in apache_beam.runners.worker.operations.SingletonConsumerSet.receive
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 169, in pyflink.fn_execution.beam.beam_operations_fast.FunctionOperation.process
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 194, in pyflink.fn_execution.beam.beam_operations_fast.FunctionOperation.process
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 104, in pyflink.fn_execution.beam.beam_operations_fast.IntermediateOutputProcessor.process_outputs
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 169, in pyflink.fn_execution.beam.beam_operations_fast.FunctionOperation.process
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 194, in pyflink.fn_execution.beam.beam_operations_fast.FunctionOperation.process
  File "pyflink/fn_execution/beam/beam_operations_fast.pyx", line 92, in pyflink.fn_execution.beam.beam_operations_fast.NetworkOutputProcessor.process_outputs
  File "pyflink/fn_execution/beam/beam_coder_impl_fast.pyx", line 101, in pyflink.fn_execution.beam.beam_coder_impl_fast.FlinkLengthPrefixCoderBeamWrapper.encode_to_stream
  File "pyflink/fn_execution/coder_impl_fast.pyx", line 273, in pyflink.fn_execution.coder_impl_fast.IterableCoderImpl.encode_to_stream
  File "pyflink/fn_execution/coder_impl_fast.pyx", line 401, in pyflink.fn_execution.coder_impl_fast.RowCoderImpl.encode_to_stream
  File "pyflink/fn_execution/coder_impl_fast.pyx", line 401, in pyflink.fn_execution.coder_impl_fast.RowCoderImpl.encode_to_stream
  File "pyflink/fn_execution/coder_impl_fast.pyx", line 528, in pyflink.fn_execution.coder_impl_fast.IntCoderImpl.encode_to_stream
TypeError: an integer is required

If I not comment ds.print() then not error.


问:
html audio player in ios
My problem is in the sound player code on Apple phones and it gives an error message if it works correctly on PC and Android.
<audio controls>   <source src="horse.mp3" type="audio/mpeg"> </audio>

I expected the file to be executed like all devices, but I have an error message on the Apple device and I did not find a solution

Title: html audio player in ios


问:
Catching errors listed in openssl/cert_vfy.h after calling SSL_CTX_use_certificate()
Parsing pem certificates with OpenSSL can fail for various reasons after calling SSL_CTX_use_certificate(), listed as constants in openssl/x509_vfy.h, for instance X509_V_ERR_CA_MD_TOO_WEAK. In this case however, ERR_get_error() only returns 0x0A00018E, and SSL_get_error() doesn't apply to error handling of SSL_CTX_use_certificate() according to the documentation.

Calling ERR_print_error_fp(stderr) however prints X509_V_ERR_CA_MD_TOO_WEAK as the main problem in this case.

How can I catch individual errors as listed in openssl/err_vfy.h without parsing the text returned by ERR_print_error_fp()  (which I consider inelegant and non portable)?


问:
Retrieving images/video from Aitwit camera
We have an Aiwit camera that connects to our wifi. I would like to connect to it (in this case using C#) and retrieve data from the camera.

Anyone who was experience with these cameras that can help me out. Also with determining the camera's portnumber.

Some code I'm working with rn:

```<code>TcpClient client = new TcpClient("Camera IP", Camera Port);
        NetworkStream stream = client.GetStream();

        // Request an image
        byte[] request = Encoding.ASCII.GetBytes("GET /image.jpg HTTP/1.1\r\n\r\n");
        stream.Write(request, 0, request.Length);

        // Read the image
        byte[] imageData = new byte[1024*1024]; // buffer to store image data
        int bytesRead = stream.Read(imageData, 0, imageData.Length);

        // Display the image
        Image image = Image.FromStream(new MemoryStream(imageData, 0, bytesRead));
</code>```

Body:
We have an Aiwit camera that connects to our wifi. I would like to connect to it (in this case using C#) and retrieve data from the camera.

Anyone who was experience with these cameras that can help me out. Also with determining the camera's portnumber.

Some code I'm working with rn:

TcpClient client = new TcpClient("Camera IP", Camera Port);
        NetworkStream stream = client.GetStream();

        // Request an image
        byte[] request = Encoding.ASCII.GetBytes("GET /image.jpg HTTP/1.1\r\n\r\n");
        stream.Write(request, 0, request.Length);

        // Read the image
        byte[] imageData = new byte[1024*1024]; // buffer to store image data
        int bytesRead = stream.Read(imageData, 0, imageData.Length);

        // Display the image
        Image image = Image.FromStream(new MemoryStream(imageData, 0, bytesRead));


问:
Unable to load mod_spatialite extension into sqlite connection on .NET 7 (win)
I am trying to load spatialite to sqlite connection (in memory db) and it is failing with strange error without any message: Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 1: ''.'

I isolated the problem to this short console app example:

```<code>using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore.Infrastructure;

var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
connection.EnableExtensions();

SpatialiteLoader.Load(connection);

Console.ReadKey();
</code>```

Project file looks like this:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Data.Sqlite.Core" Version="7.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" />
  </ItemGroup>

</Project>
</code>```

Downgrade of packages did not help.
I tried the workaround mentioned here but I am not able to get it work.

Body:
I am trying to load spatialite to sqlite connection (in memory db) and it is failing with strange error without any message: Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 1: ''.'

I isolated the problem to this short console app example:

using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore.Infrastructure;

var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
connection.EnableExtensions();

SpatialiteLoader.Load(connection);

Console.ReadKey();

Project file looks like this:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Data.Sqlite.Core" Version="7.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" />
  </ItemGroup>

</Project>

Downgrade of packages did not help.
I tried the workaround mentioned here but I am not able to get it work.


问:
Unable to create quarkus project on intellij
Getting the following error:

Initialization failed for 'https://code.quarkus.io' Please check URL, network and proxy settings.  Error message: Cannot download 'https://code.quarkus.io/api/extensions': code.quarkus.io

Can't figure out where to start with this issue


问:
Is it possible to run yolov5 on raspberry pi 2 (32 bit) in real time?
The main issue i get is that pytorch cannot be compatible with 32 bit raspberry pi 2

I've seen some pytorch implementations for ARMv7 and failed to compile/run it


问:
I need clarity regarding 'normalization' that is the first step in SRT division algorithm radix-4
I am trying to implement SRT division algorithm with radix-4, in all the papers and books that I have referred to, the first thing is to normalized the divisor and dividend in range [0.5,1) and [-0.5, 0.5). I want to use it for fixed point numbers, I do understand the normalization for floating point numbers in IEEE standard. But how does it work for fixed point numbers, How can I ensure my number falls in this range if I try to code it in python. Some books say to move the radix point from the right most to the left most or some right or left shift are needed. It would be helpful if I get an example in binary string or some basic rule laid out for this sort of normalization. I can provide any material links if needed. Also in one book there was this division operation 69/10 (100 0101/1010) (z/d) And this is how they normalized them, z for dividend, d for divisor

0.0100 0101 z is in [-1/2,1/2)---0.1010 d is in [1/2,1)

I just feel confused about how to ensure this normalization and to code it in python. The reason for this is that in all the materials I referred to, I feel like I didn't get proper guidelines, and the process of normalization sometimes is varied from one text to other or they are using it on floating point numbers.


问:
Flutter, cannot show correct character while browser does
I am try to get data from a web server which include some Chinese words, the json is already in UTF8 format.  However, the character can correctly be displayed but not in Flutter.

Here is the result from browser:
[ { "ID" : 1140, "ENGLISHNAME" : "Test Name", "CHINESENAME" : "中國", "COMPANYTEL" : "", "E_ADDRESS1" : "", "E_ADDRESS2" : "", "E_ADDRESS3" : "", "C_ADDRESS1" : "", "C_ADDRESS2" : "", "C_ADDRESS3" : "" } ]

and here is the result from flutter:

```<code>void loadData() async {
  final response = await http.get(
    Uri.parse('http://192.168.0.8:88/searchcustomer'),
    headers: {
      "Content-type": "application/json",
      "Accept": "application/json",
      "Connection": "Keep-Alive",
    },
  );
  print(response.body);
}

List<dataRecord> parseJson(String responseBody) {
  final parsed =
  convert.jsonDecode(responseBody).cast<Map<String, dynamic>>();
  return parsed.map<dataRecord>((json) => dataRecord.fromJson(json)).toList();
}

</code>```

Body:
I am try to get data from a web server which include some Chinese words, the json is already in UTF8 format.  However, the character can correctly be displayed but not in Flutter.

Here is the result from browser:
[ { "ID" : 1140, "ENGLISHNAME" : "Test Name", "CHINESENAME" : "中國", "COMPANYTEL" : "", "E_ADDRESS1" : "", "E_ADDRESS2" : "", "E_ADDRESS3" : "", "C_ADDRESS1" : "", "C_ADDRESS2" : "", "C_ADDRESS3" : "" } ]

and here is the result from flutter:

void loadData() async {
  final response = await http.get(
    Uri.parse('http://192.168.0.8:88/searchcustomer'),
    headers: {
      "Content-type": "application/json",
      "Accept": "application/json",
      "Connection": "Keep-Alive",
    },
  );
  print(response.body);
}

List<dataRecord> parseJson(String responseBody) {
  final parsed =
  convert.jsonDecode(responseBody).cast<Map<String, dynamic>>();
  return parsed.map<dataRecord>((json) => dataRecord.fromJson(json)).toList();
}


问:
i can't import .aar file to create package in dependencies on flutter
i can't import .aar file to create package in dependencies on flutter

The path './android/libs/libraryCore_v1.0.8.aar' doesn't exist.
Try creating the referenced path or using a path that exists.

```<code>dependencies:
  flutter:
    sdk: flutter
  libraryCore_v1.0.8:
    path: ./android/libs/libraryCore_v1.0.8.aar
</code>```

Body:
i can't import .aar file to create package in dependencies on flutter

The path './android/libs/libraryCore_v1.0.8.aar' doesn't exist.
Try creating the referenced path or using a path that exists.

dependencies:
  flutter:
    sdk: flutter
  libraryCore_v1.0.8:
    path: ./android/libs/libraryCore_v1.0.8.aar


问:
C# Webbrowser AutoLogin Application Issue
First, when the website is loaded into the webbrowser, I programmatically click on the login with the e-token button. The problem occurs after this stage. At this stage, this process takes 3-5 seconds as the information on the usb token device is read and the username on the token device is automatically entered in the username field on the website. So the username comes from e token, only the password is entered manually. But since my program clicks on the e-token login button first, then types the password , and then clicks the logmein button, it progresses very quickly and clicks the login button before the username isn't loaded. Before clicking the Logmein button, it is necessary to make sure that the username is uploaded to the website, otherwise I get an error. How can I overcome such a problem?</p>
```<code> private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
  webBrowser1.Document.GetElementById("etokenbutton").InvokeMember("click");
  webBrowser1.Document.GetElementById("pinedit").InnerText="mypassword";
  May I wait here five seconds?
  webBrowser1.Document.GetElementById("logmein").InvokeMember("click");
    }
</code>```

Body:
First, when the website is loaded into the webbrowser, I programmatically click on the login with the e-token button. The problem occurs after this stage. At this stage, this process takes 3-5 seconds as the information on the usb token device is read and the username on the token device is automatically entered in the username field on the website. So the username comes from e token, only the password is entered manually. But since my program clicks on the e-token login button first, then types the password , and then clicks the logmein button, it progresses very quickly and clicks the login button before the username isn't loaded. Before clicking the Logmein button, it is necessary to make sure that the username is uploaded to the website, otherwise I get an error. How can I overcome such a problem?

 private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
  webBrowser1.Document.GetElementById("etokenbutton").InvokeMember("click");
  webBrowser1.Document.GetElementById("pinedit").InnerText="mypassword";
  May I wait here five seconds?
  webBrowser1.Document.GetElementById("logmein").InvokeMember("click");
    }


问:
Toogle Light/Dark Mode Programmatically in Windows 11
I would like to toggle light / dark mode on Windows 11 programmatically.

Existing solutions are unsatisfactory:

use the Registry values "AppsUseLightTheme" and "SystemUsesLightTheme". This worked perfectly in Windows 10. However, in Windows 11 the change is not applied in all places. For example, when switching to dark mode, Explorer windows are still light. And the clock text in the right corner of the Taskbar is still black, so now the clock cannot be read anymore.

select a different Theme programmatically - however, this changes my Desktop background. I'd really just like to change the dark/light mode and keep everything else the same.

What's the best way to accomplish this?


问:
Triggering Mechanisms of Devops REST APIs
I am referring to the below MSFT doc for Devops REST API:
https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/get?view=azure-devops-rest-7.0

As per the doc, one can trigger the API only via PAT as seen below:

Can someone confirm whether there is no other way possible other than PAT?

Also, is it possible to provide access tp an App/service principal to an Azure Devops  Project ?
I can only see users/groups:

Because we would like to leverage service principal PAT rather than individual/service account.


问:
image upload using multer but image came from postman form-data via array of object
```<code>{
"step":"services",
"servicesDescription": [
        { "serviceTitle":"aaaaaaaaaaaaaaaaaaa",
         "serviceIcon": abc.jpg },
        { "serviceTitle":"bbbbbbbbbbbbbbbbbb"
          "serviceIcon": abc.jpg }
      ],
"_id":"63b7c15f06501c1ea0729f24"
}
</code>```

here my ques is how i pick serviceicon image and upload via multer????and store path again with serviceicon .please help me

Body:
{
"step":"services",
"servicesDescription": [
        { "serviceTitle":"aaaaaaaaaaaaaaaaaaa",
         "serviceIcon": abc.jpg },
        { "serviceTitle":"bbbbbbbbbbbbbbbbbb"
          "serviceIcon": abc.jpg }
      ],
"_id":"63b7c15f06501c1ea0729f24"
}

here my ques is how i pick serviceicon image and upload via multer????and store path again with serviceicon .please help me


问:
Spring Mongo criteria querying data which are present and not present in database
I want to query all data which are present in my database by comparing with while loop data and if this data is available I want to update it and if not I want to insert it as a new record into the database.

The problem is I'm only getting data that is present in the database these missing I'm not able to get them from the fetched result

This is what I have so far

```<code>            while(result.next()) {
            Query query = new Query();
            query.addCriteria(Criteria.where("customerId").is(result.getString(1))
                 .andOperator(Criteria.where("orderDate").is(result.getString(2)),
                              Criteria.where("Location").is(baseLocation)));

            var dbData = mongoTemplate.find(query, Customer.class);

            if(dbData == null || dbData.isEmpty()) {

            Customer customer = new Customer();
            customer.setCustomerId(result.getString(1));
            customer.setOrderDate(result.getString(2));
            customer.setOrderWeight(result.getString(3));
            customer.setCustomerCode(result.getString(9));
            customer.setDateAdded(LocalDateTime.now());
            customer.setCustomerLocation(baseLocation);
            customerList.add(customer);

            }else {

            for (Customer customerData: dbData) {

            if(customerData.getOrderDate().equals(result.getString(2)) == true) {
            customerData.setCustomerId(result.getString(1));
            customerData.setOrderDate(result.getString(2));
            customerData.setOrderWeight(result.getString(3));
            customerData.setCustomerCode(result.getString(9));
            customerData.setDateAdded(LocalDateTime.now());
            customerData.setCustomerLocation(baseLocation);
            customerList.add(customerData);

            }else {
            Customer customer = new Customer();
            customer.setCustomerId(result.getString(1));
            customer.setOrderDate(result.getString(2));
            customer.setWeight(result.getString(3));
            customer.setCustomerCode(result.getString(9));
            customer.setDateAdded(LocalDateTime.now());
            customer.setCustomerLocation(basename);
            customerList.add(customer);
            }

            }

            }

            }
</code>```

Any help will be much appreciated!

Body:
I want to query all data which are present in my database by comparing with while loop data and if this data is available I want to update it and if not I want to insert it as a new record into the database.

The problem is I'm only getting data that is present in the database these missing I'm not able to get them from the fetched result

This is what I have so far

            while(result.next()) {
            Query query = new Query();
            query.addCriteria(Criteria.where("customerId").is(result.getString(1))
                 .andOperator(Criteria.where("orderDate").is(result.getString(2)),
                              Criteria.where("Location").is(baseLocation)));

            var dbData = mongoTemplate.find(query, Customer.class);

            if(dbData == null || dbData.isEmpty()) {

            Customer customer = new Customer();
            customer.setCustomerId(result.getString(1));
            customer.setOrderDate(result.getString(2));
            customer.setOrderWeight(result.getString(3));
            customer.setCustomerCode(result.getString(9));
            customer.setDateAdded(LocalDateTime.now());
            customer.setCustomerLocation(baseLocation);
            customerList.add(customer);

            }else {

            for (Customer customerData: dbData) {

            if(customerData.getOrderDate().equals(result.getString(2)) == true) {
            customerData.setCustomerId(result.getString(1));
            customerData.setOrderDate(result.getString(2));
            customerData.setOrderWeight(result.getString(3));
            customerData.setCustomerCode(result.getString(9));
            customerData.setDateAdded(LocalDateTime.now());
            customerData.setCustomerLocation(baseLocation);
            customerList.add(customerData);

            }else {
            Customer customer = new Customer();
            customer.setCustomerId(result.getString(1));
            customer.setOrderDate(result.getString(2));
            customer.setWeight(result.getString(3));
            customer.setCustomerCode(result.getString(9));
            customer.setDateAdded(LocalDateTime.now());
            customer.setCustomerLocation(basename);
            customerList.add(customer);
            }

            }

            }

            }

Any help will be much appreciated!


问:
Need trusted and reliable way to test on ios and android devices using selenium ,but dont want to do on actual devices need simulator
Hi need list of trusted website/app/platform where i can test in a reliable way((should be confident after using the platform)) on ios and android devices using selenium ,dont want to do test on actual physical  devices need simulator for the following reasons firstly with the cost involved and secondly dont want to maintain the OS versions.
I came across this resource but have no idea about any of the listed ones there.
https://www.guru99.com/top-10-cross-browser-testing-tools.html</p>


问:
Get value from certain cell in row/column match from another excel file
I have multiple excel files that should "report" to a single one.
Imagine this example:

Excel 1)

Excel 1 is the one that receives the whole information from the other files. In that cell with the green circle, it should get the value which has row="6" and column="JAN" on other excel (Excel 2).

Excel 2)

In this excel there is a cell that has exactly the row="6" and column="JAN". The value does not match the cell number of each excel (in this example, the cell I want to fill in Excel 1 is E21 and in Excel 2 is E20).
Plus, I want this to be dynamic. If I now understand that the KPI I want to show in number 6 is another one I should change the number in Excel 2 and it should be getting that new value in Excel 1.

Was this clear? I'm sorry, English is not my primary language and I understand if it is a little bit confusing.
Thank you.

I was using the index function but that is not perfect for my case because if I change the KPI to another row it won't work anymore.


问:
Is it possible to run a function after the app is killed?

Hi there!

I have read a lot of forums etc. about this topic and I have gained some knowlegde, but I still don't know weather it is at all possible.

Info

I'm using the Ionic Framework

Problem

I have an app which controls a IOT device using a network request (http/https).
Since the IOT device does not have functionality to automatically turn off after a specific time setting, I want the app to send this command after approx. 120 min. (2 hours).

So the user, when the app is opened, press a button to power down the device after 120 min. and then closes the app (kills completely, not in background).
Now I want the app to automatically send this power down command to the IOT device after 120 min.

I'm using Ionic Framework but can implement Native functionality and modules if it is possible this way.

What I think I know:

This should be possible on Android implementing a 'service' natively which I understand is a sort of deamon thread or resembles a Windows service. (exactly what I need).

iOS seems to be the problem, with a lot of restrictions on code execution after the app has been closed, or even stopped by the operating system. I've read on this thread (https://developer.apple.com/forums/thread/685525) that some cases are possible (music playing in background, fetching big files from the internet, etc.).
They also provide something they call PushKit https://developer.apple.com/documentation/pushkit. But that seems to only be able to notify the user, and auto power down is not smart if I have to send a request to the user that the 120 min. are up, now you can turn of your device yourself xD

Question

So my question is, will this be possible at all on either operating system (Android, iOS) or will I have to implement a server that will send the request to the IOT device instead?

TLDR

Is it at all possible to send a HTTP request after 120 min. on iOS and Android after the user has manually closed the app (killed the app)?

I have looked through a lot of forums and has not found a definitive answer to this question.
I expect that it will not be possible on iOS but only on Android.

Many threads on this topic is approx. 8-12 years old, so maybe some new possibilities has come to light?


问:
why the python code is only taking a particular type of folder?
I have a folder location where I have two types of folder having below sample names

```<code>- 2009Q1_2022Q4_abc_<timestamp>
- 2022Q4_abc_<timestamp>
</code>```

I have written below code to fetch both types of folder as per the user input. i.e. if user gives the input as 2009Q1_2022Q4, then the first folder should be picked up, and if the user just gives 2022Q4, then the 2nd type of the folder should be picked.

But as far as I can see, even if I give just 2022Q4, it is still picking up the first folder only, i.e. 2009Q1_2022Q4_abc_.

Below are the code snippets

```<code>def get_latest_modified_file(Ppath, folder_or_file, key): 1169
    """ For a given path to a directory in the data lake, return the file that was last modified. \n
        Usage: get_latest_modified_file('/<path_to>','folder or file',)
    Args:
        Ppath (String): Path to a directory
        folder_or_file (String):This is a folder name or file name
    Returns:
        String: It returns full  file name path with latest file in the directory.
    """
    try:
        dir_list = []
        new_dir_list = []
        for dir_path in dbutils.fs.ls(Ppath):
            if folder_or_file == 'folder' and dir_path.isDir():
                dir_list.append(get_modified_time(dir_path.path))
            elif folder_or_file == 'file' and dir_path.isFile():
                dir_list.append(get_modified_time(dir_path.path))
        dir_list = [list[0] for list in dir_list]
        for fdpath in dir_list:
            if key in fdpath[0]:
                new_dir_list.append(fdpath)
        df = spark.createDataFrame(
            new_dir_list, ['FullFilePath', 'LastModifiedDateTime'])
        max_latest_modified_datetime = df.agg(
            {"LastModifiedDateTime": "max"}).collect()[0][0]
        df_filtered = df.filter(df.LastModifiedDateTime ==
                                max_latest_modified_datetime)
        full_path = df_filtered.first()['FullFilePath']
        return full_path
</code>```

The get_latest_modified_file function is calling upon two different functions that follows it as shown below

```<code>def get_modified_time(dir_path):
    """ For a given path to a directory in the data lake, returns the last modified time. \n
        Usage: get_modification_time('/<path_to>')
    Args:
        dir_path (String): Path to a directory in the data lake
    Returns:
        Timestamp:Returns the modified timestamp of files in the given path.
    """
    return [(dir_path, get_file_status(dir_path).getModificationTime())]

def get_file_status(dir_path):
    """ For a given path to a directory in the data lake, returns the File status with info like (owner, group, file permission, modified time etc). \n
        Usage: getFileStatus('/mnt/path')
    Args:
        dir_path (String): Path to a directory in the data lake
    Returns:
        String: Returns the  directory and it's content information.
    """
    fs = spark._jvm.org.apache.hadoop.fs.FileSystem.get(
        spark._jsc.hadoopConfiguration())

    def fs_path(p): return spark._jvm.org.apache.hadoop.fs.Path(dir_path)
    return fs.getFileStatus(fs_path(dir_path))
</code>```

Note:

```<code>single quarter input might vary from 2022Q1 to 2022Q4. But for user input for 2009Q1_2022Q4 will always remain same.

In other word if a user is giving folder input for YYYYQQ, then it should only pick the 2nd folder structure.
</code>```

Please suggest.

Body:
I have a folder location where I have two types of folder having below sample names

- 2009Q1_2022Q4_abc_<timestamp>
- 2022Q4_abc_<timestamp>

I have written below code to fetch both types of folder as per the user input. i.e. if user gives the input as 2009Q1_2022Q4, then the first folder should be picked up, and if the user just gives 2022Q4, then the 2nd type of the folder should be picked.

But as far as I can see, even if I give just 2022Q4, it is still picking up the first folder only, i.e. 2009Q1_2022Q4_abc_.

Below are the code snippets

def get_latest_modified_file(Ppath, folder_or_file, key): 1169
    """ For a given path to a directory in the data lake, return the file that was last modified. \n
        Usage: get_latest_modified_file('/<path_to>','folder or file',)
    Args:
        Ppath (String): Path to a directory
        folder_or_file (String):This is a folder name or file name
    Returns:
        String: It returns full  file name path with latest file in the directory.
    """
    try:
        dir_list = []
        new_dir_list = []
        for dir_path in dbutils.fs.ls(Ppath):
            if folder_or_file == 'folder' and dir_path.isDir():
                dir_list.append(get_modified_time(dir_path.path))
            elif folder_or_file == 'file' and dir_path.isFile():
                dir_list.append(get_modified_time(dir_path.path))
        dir_list = [list[0] for list in dir_list]
        for fdpath in dir_list:
            if key in fdpath[0]:
                new_dir_list.append(fdpath)
        df = spark.createDataFrame(
            new_dir_list, ['FullFilePath', 'LastModifiedDateTime'])
        max_latest_modified_datetime = df.agg(
            {"LastModifiedDateTime": "max"}).collect()[0][0]
        df_filtered = df.filter(df.LastModifiedDateTime ==
                                max_latest_modified_datetime)
        full_path = df_filtered.first()['FullFilePath']
        return full_path

The get_latest_modified_file function is calling upon two different functions that follows it as shown below

def get_modified_time(dir_path):
    """ For a given path to a directory in the data lake, returns the last modified time. \n
        Usage: get_modification_time('/<path_to>')
    Args:
        dir_path (String): Path to a directory in the data lake
    Returns:
        Timestamp:Returns the modified timestamp of files in the given path.
    """
    return [(dir_path, get_file_status(dir_path).getModificationTime())]

def get_file_status(dir_path):
    """ For a given path to a directory in the data lake, returns the File status with info like (owner, group, file permission, modified time etc). \n
        Usage: getFileStatus('/mnt/path')
    Args:
        dir_path (String): Path to a directory in the data lake
    Returns:
        String: Returns the  directory and it's content information.
    """
    fs = spark._jvm.org.apache.hadoop.fs.FileSystem.get(
        spark._jsc.hadoopConfiguration())

    def fs_path(p): return spark._jvm.org.apache.hadoop.fs.Path(dir_path)
    return fs.getFileStatus(fs_path(dir_path))

Note:

single quarter input might vary from 2022Q1 to 2022Q4. But for user input for 2009Q1_2022Q4 will always remain same.

In other word if a user is giving folder input for YYYYQQ, then it should only pick the 2nd folder structure.

Please suggest.


问:
How to make an age verification pop-up on page load next.js?
I have no idea where to start. I know how to make popup modals on onClick events and the like but I don't know which tools I would need to do an easy yes/no age-verification for a website on the initial page load. I'm using Next.JS... Any guidance would be greatly appreciated.

I haven't tried anything because I truly don't know where to start. I'm guessing some kind of cookie.


问:
Trying to understand read write lock and the need for two mutex instead of one
I have been reading this wiki article about read/write lock and it says to implement it we need two mutexes but why can't we do it with one mutex? I am wondering if my understanding is correct.

we need to make sure one write is happening at any moment

we need to make sure no one is reading while it's being written to

many reads can happen concurrently and its completely fine

Write:

```<code>// wait until no one is reading concurrently
if (wait(write_lock))
{
  acquire(write_lock)

  // Do the write operation

  release(write_lock)
}
</code>```

Read:

```<code>// wait until no one is currently writing
if (wait(write_lock))
{
  // Do the read operation atomically
}
</code>```

Body:
I have been reading this wiki article about read/write lock and it says to implement it we need two mutexes but why can't we do it with one mutex? I am wondering if my understanding is correct.

we need to make sure one write is happening at any moment

we need to make sure no one is reading while it's being written to

many reads can happen concurrently and its completely fine

Write:

// wait until no one is reading concurrently
if (wait(write_lock))
{
  acquire(write_lock)

  // Do the write operation

  release(write_lock)
}

Read:

// wait until no one is currently writing
if (wait(write_lock))
{
  // Do the read operation atomically
}


问:
usememo and useeffect in customhooks
I've tried to use useMemo and useEffect in my custom hooks to prevent that from re-rendering ( doing cpu heavy job) which is parsing the JWT and returning the user permissions.
But it re-renders eveerytime that my menu items re-render and runs the usememo too.
Is there a way to avoid it from re-calculating ?

The code:

```<code>const usePermission = (controller?: string) => {
    const [permoactions, setPermoactions] = React.useState([]);

    const fetchPermoactions = () => {
        try {
            // parse jwt token and return permissions
        } catch (error: any) {
            throw new Error(error.message);
        }
    };

    useMemo(() => {
        fetchPermoactions();
        console.count("memo");
    }, [1]);

    const access = React.useMemo(() => {
        // make an permissions object tree
    }, [permoactions]);

    return controller ? access[controller] : access;
};
export default usePermission;
</code>```

The usePermission hook is used in the pages where I need to validate for example if a user should see a button or have the ability to delete a line like this:

```<code>                    {permissions?.Create && (
                        <Grid item xs={2} sx={{ textAlign: "left" }}>
                            <Button
                                variant="contained"
                                onClick={handleAddClick}
                                endIcon={<AddIcon sx={{ marginRight: 2 }} />}
                            >
                                افزودن
                            </Button>
                        </Grid>
                    )}
</code>```

It's also used in the sidebar to not show the menus that the user doesn't have access to like:

```<code>    children = children.filter((child: any) => {
        let AccessList: string[] = child.name.split(",");
        let hasAccess = false;
        AccessList.forEach((Access) => {
            if (userAccess[Access]?.View) {
                hasAccess = true;
            } else {
                hasAccess = false;
                return;
            }

            return hasAccess && children;
        });

        return hasAccess ? child : null;
    });
</code>```

Title: usememo and useeffect in customhooks

Body:
I've tried to use useMemo and useEffect in my custom hooks to prevent that from re-rendering ( doing cpu heavy job) which is parsing the JWT and returning the user permissions.
But it re-renders eveerytime that my menu items re-render and runs the usememo too.
Is there a way to avoid it from re-calculating ?

The code:

const usePermission = (controller?: string) => {
    const [permoactions, setPermoactions] = React.useState([]);

    const fetchPermoactions = () => {
        try {
            // parse jwt token and return permissions
        } catch (error: any) {
            throw new Error(error.message);
        }
    };

    useMemo(() => {
        fetchPermoactions();
        console.count("memo");
    }, [1]);

    const access = React.useMemo(() => {
        // make an permissions object tree
    }, [permoactions]);

    return controller ? access[controller] : access;
};
export default usePermission;

The usePermission hook is used in the pages where I need to validate for example if a user should see a button or have the ability to delete a line like this:

                    {permissions?.Create && (
                        <Grid item xs={2} sx={{ textAlign: "left" }}>
                            <Button
                                variant="contained"
                                onClick={handleAddClick}
                                endIcon={<AddIcon sx={{ marginRight: 2 }} />}
                            >
                                افزودن
                            </Button>
                        </Grid>
                    )}

It's also used in the sidebar to not show the menus that the user doesn't have access to like:

    children = children.filter((child: any) => {
        let AccessList: string[] = child.name.split(",");
        let hasAccess = false;
        AccessList.forEach((Access) => {
            if (userAccess[Access]?.View) {
                hasAccess = true;
            } else {
                hasAccess = false;
                return;
            }

            return hasAccess && children;
        });

        return hasAccess ? child : null;
    });


问:
How to check if a property exists in a multidimensional object using variables to compose the name?
I have a javascript object like this, let's call it store:

```<code>{
  area1: {my product name: 'red'}
}
</code>```

I want to check if a specific value exists in store, using hasOwnProperty.
Assuming that I have all these values already defined in properties, like area, productName and color, how can I check if store has a area property ans this one also has a productName property?

I basically would like to do something like

```<code>const res = store.hasOwnProperty(area[productName]) && store[area][productName]=== color;
</code>```

which seems not to work.

Body:
I have a javascript object like this, let's call it store:

{
  area1: {my product name: 'red'}
}

I want to check if a specific value exists in store, using hasOwnProperty.
Assuming that I have all these values already defined in properties, like area, productName and color, how can I check if store has a area property ans this one also has a productName property?

I basically would like to do something like

const res = store.hasOwnProperty(area[productName]) && store[area][productName]=== color;

which seems not to work.


问:
How to write the unit test for 'fs unlink' using vitest for the follow function?

deleteDuplicatedImage.ts

```<code>import { unlink, PathLike } from "fs";
import { logger } from "../libraries";

export const deleteDuplicatedImage = (imagePath: PathLike) => {
  unlink(imagePath, function (error) {
    if (error) {
      throw error;
    }

    // if no error is thrown, file has been deleted successfully
    logger.info("File was deleted as it already exists in the db!");
  });
};

</code>```

This is the function for which I'm writing test case using vitest framework.
Though, I tried to write the test for it in the following way

deleteDuplicatedImage.spec.ts

```<code>require("dotenv").config();
import { nanoid } from "nanoid";
import { afterEach, describe, expect, it, vi } from "vitest";
import * as deleteDuplicatedImage from "../../src/lib/utilities/deleteDuplicatedImage";

const testImagePath: string = `${nanoid()}-testImagePath`;

describe("utilities -> deleteDuplicatedImage", () => {
  afterEach(() => {
    vi.restoreAllMocks();
  });

  it("it should throw an error", async () => {
    const mockedDeleteDuplicatedImage = vi
      .spyOn(deleteDuplicatedImage, "deleteDuplicatedImage")
      .mockImplementation((_imagePath: any) => {});

    deleteDuplicatedImage.deleteDuplicatedImage(testImagePath);
    expect(mockedDeleteDuplicatedImage).toBeCalledWith(testImagePath);
    expect(
      deleteDuplicatedImage.deleteDuplicatedImage(testImagePath)
    ).toBeUndefined();
  });
});

</code>```

It is also passed but not including the coverage of the code!!

It should have 100% test coverage

Body:
deleteDuplicatedImage.ts

import { unlink, PathLike } from "fs";
import { logger } from "../libraries";

export const deleteDuplicatedImage = (imagePath: PathLike) => {
  unlink(imagePath, function (error) {
    if (error) {
      throw error;
    }

    // if no error is thrown, file has been deleted successfully
    logger.info("File was deleted as it already exists in the db!");
  });
};

This is the function for which I'm writing test case using vitest framework.
Though, I tried to write the test for it in the following way

deleteDuplicatedImage.spec.ts

require("dotenv").config();
import { nanoid } from "nanoid";
import { afterEach, describe, expect, it, vi } from "vitest";
import * as deleteDuplicatedImage from "../../src/lib/utilities/deleteDuplicatedImage";

const testImagePath: string = `${nanoid()}-testImagePath`;

describe("utilities -> deleteDuplicatedImage", () => {
  afterEach(() => {
    vi.restoreAllMocks();
  });

  it("it should throw an error", async () => {
    const mockedDeleteDuplicatedImage = vi
      .spyOn(deleteDuplicatedImage, "deleteDuplicatedImage")
      .mockImplementation((_imagePath: any) => {});

    deleteDuplicatedImage.deleteDuplicatedImage(testImagePath);
    expect(mockedDeleteDuplicatedImage).toBeCalledWith(testImagePath);
    expect(
      deleteDuplicatedImage.deleteDuplicatedImage(testImagePath)
    ).toBeUndefined();
  });
});

It is also passed but not including the coverage of the code!!

It should have 100% test coverage