问:
Insert column(s) in the middle of a csv file with header
I have a file similar to the following:

```<code>FName, LName, City, ST, Zip
Dave, Henderson, Peterson, TX, 73131
Gelda, Thomas, Arlington, FL, 49102
Jason, , Georgetown, CA, 99515
</code>```

I need to add Phone after LName but Null or " " needs to go in the data. and understand the data cleansing happens later, so the missing last name after Jason is just empty.

I am not great with bash scripts, but this is what I have now, and it's not working:

```<code>#!/bin/bash

#Set path
Path="File1.csv"
Path2="File2.csv"

echo "Set path"

#Insert Phone
awk d="" -F="," 'BEGIN {OFS = ","} {printf("%s%s",$0,FNR>1 FS ?d : FS "Phone" $3)}' $Path > $Path2
</code>```

trying to get this result: (Preferably with Null for phone values)

```<code>FName, LName, Phone, City, ST, Zip
Dave, Henderson, , Peterson, TX, 73131
Gelda, Thomas, , Arlington, FL, 49102
Jason, , ,Georgetown, CA, 99515
</code>```

Body:
I have a file similar to the following:

FName, LName, City, ST, Zip
Dave, Henderson, Peterson, TX, 73131
Gelda, Thomas, Arlington, FL, 49102
Jason, , Georgetown, CA, 99515

I need to add Phone after LName but Null or " " needs to go in the data. and understand the data cleansing happens later, so the missing last name after Jason is just empty.

I am not great with bash scripts, but this is what I have now, and it's not working:

#!/bin/bash

#Set path
Path="File1.csv"
Path2="File2.csv"

echo "Set path"

#Insert Phone
awk d="" -F="," 'BEGIN {OFS = ","} {printf("%s%s",$0,FNR>1 FS ?d : FS "Phone" $3)}' $Path > $Path2

trying to get this result: (Preferably with Null for phone values)

FName, LName, Phone, City, ST, Zip
Dave, Henderson, , Peterson, TX, 73131
Gelda, Thomas, , Arlington, FL, 49102
Jason, , ,Georgetown, CA, 99515


来源: stackexchange

问:
Issue retrieving data from MongoDB using mongoose (MERN stack)
I will start with the weird issue I am having, and in the end I will just explain my code.

When I try creating a GET request via postman to my localhost:3000, it doesn't matter which endpoint I pass to the request, I continuously  receive a status of 200.

Now, when I run the program itself, I'm getting a 404 error.

My program is supposed to do a simple action of retrieving all the documents of a collection. which I wrote in the following way:

```<code>import express, { Express } from "express";
import mongoose from "mongoose";
import cors from "cors";
var issueRoutes = require("./src/routes/issueRoutes");

const app = express();
const uri: string = `mongodb+srv://MyUsernameHere:MyPwHere@cluster0.n2k7xvu.mongodb.net/issuesReporter?retryWrites=true&w=majority`;

app.use(cors());
app.use(issueRoutes);

mongoose
  .connect(uri)
  .then(() =>
    app.listen(3000, () => console.log("connected on PORT " + process.env.PORT))
  )
  .catch((err) => {
    throw err;
  });
</code>```

and my route, given to the app.use() as middleware is of the following:

```<code>import React from "react";
import { Router } from "express";
import {
  getAllIssues,
  updateIssueById,
} from "../controllers/issueController";

const router: Router = Router();
router.route("/issues").get(getAllIssues);
module.exports = router;
</code>```

while my getAllIssues method is:

```<code>export const getAllIssues = async (req: Request, res: Response): Promise<void> => {
    try {
        const issues: IssueInterface[] = await Issue.find({});
        res.status(200).json({ issues })
    }
    catch (err) {
        console.log("error in getallissues: " + err)
        throw err;
    }
}
</code>```

My attempt of initiating a GET request:

```<code> const [issues, setIssues] = useState<IssueInterface[]>([])

  useEffect(() => {
    fetchIssues();
    console.log("issues: " + issues)
  }, [])

  const fetchIssues = (): void => {
    getIssues() // functioin in APIrequests
      // then(({ data: { issues } }: IssueInterface[] | any) => setIssues(issues)) ## tried in this form as well
      .then((data: IssueInterface[] | any) => setIssues(data))
      .catch((err: Error) => console.log(err))
  }
</code>```

and getIssues called in fetchIssues, which is the one to use Axios when entering the page:

```<code>export const getIssues = async (): Promise<
  AxiosResponse<IssueApiDataType> | undefined
> => {
  try {
    const issues: AxiosResponse<IssueApiDataType> = await axios.get(
      baseUrl + "/issues"
    );
    return issues;
  } catch (error) {
    // throw new Error(error);
    console.log("we're on the error: " + error);
  }
};
</code>```

Regards and thanks for anyone putting any effort in trying to help out. :_)

ContentLicense: CC BY-SA 4.0

Body:
I will start with the weird issue I am having, and in the end I will just explain my code.

When I try creating a GET request via postman to my localhost:3000, it doesn't matter which endpoint I pass to the request, I continuously  receive a status of 200.

Now, when I run the program itself, I'm getting a 404 error.

My program is supposed to do a simple action of retrieving all the documents of a collection. which I wrote in the following way:

import express, { Express } from "express";
import mongoose from "mongoose";
import cors from "cors";
var issueRoutes = require("./src/routes/issueRoutes");

const app = express();
const uri: string = `mongodb+srv://MyUsernameHere:MyPwHere@cluster0.n2k7xvu.mongodb.net/issuesReporter?retryWrites=true&w=majority`;

app.use(cors());
app.use(issueRoutes);

mongoose
  .connect(uri)
  .then(() =>
    app.listen(3000, () => console.log("connected on PORT " + process.env.PORT))
  )
  .catch((err) => {
    throw err;
  });

and my route, given to the app.use() as middleware is of the following:

import React from "react";
import { Router } from "express";
import {
  getAllIssues,
  updateIssueById,
} from "../controllers/issueController";

const router: Router = Router();
router.route("/issues").get(getAllIssues);
module.exports = router;

while my getAllIssues method is:

export const getAllIssues = async (req: Request, res: Response): Promise<void> => {
    try {
        const issues: IssueInterface[] = await Issue.find({});
        res.status(200).json({ issues })
    }
    catch (err) {
        console.log("error in getallissues: " + err)
        throw err;
    }
}

My attempt of initiating a GET request:

 const [issues, setIssues] = useState<IssueInterface[]>([])

  useEffect(() => {
    fetchIssues();
    console.log("issues: " + issues)
  }, [])

  const fetchIssues = (): void => {
    getIssues() // functioin in APIrequests
      // then(({ data: { issues } }: IssueInterface[] | any) => setIssues(issues)) ## tried in this form as well
      .then((data: IssueInterface[] | any) => setIssues(data))
      .catch((err: Error) => console.log(err))
  }

and getIssues called in fetchIssues, which is the one to use Axios when entering the page:

export const getIssues = async (): Promise<
  AxiosResponse<IssueApiDataType> | undefined
> => {
  try {
    const issues: AxiosResponse<IssueApiDataType> = await axios.get(
      baseUrl + "/issues"
    );
    return issues;
  } catch (error) {
    // throw new Error(error);
    console.log("we're on the error: " + error);
  }
};

Regards and thanks for anyone putting any effort in trying to help out. :_)


问:
how to implement a popper menu like vscode intellisense in react js?
i want to create a popper menu in a contenteditable div with text suggestions. Tried with Tippyjs, Popper js but did not work well. here is a sampe picture from vscode:


问:
How to obtain a promise result in js?
I am making a GET api call to a url in Drupal. I want to obtain the PromiseResult and place it in a variable to be used in another api call.

Here is my code:

```<code>   fetch('/session/token')
  .then(res => res.text())
  .then(text => console.log(text))
</code>```

Basically, this code goes to the /session/token url and it retrieves a token to be used in the X-CSRF-token header for another api call.

This is what the result of the console.log(text) looks like:

```<code><This is the actual token which is a string of characters>
</code>```

How would I put the value of this token in a variable?

Title: How to obtain a promise result in js?

Body:
I am making a GET api call to a url in Drupal. I want to obtain the PromiseResult and place it in a variable to be used in another api call.

Here is my code:

   fetch('/session/token')
  .then(res => res.text())
  .then(text => console.log(text))

Basically, this code goes to the /session/token url and it retrieves a token to be used in the X-CSRF-token header for another api call.

This is what the result of the console.log(text) looks like:

<This is the actual token which is a string of characters>

How would I put the value of this token in a variable?


问:
Unique variable naming patterns in deep learning code
Need help on understanding some naming patterns I see so far.

Reading The Annotated Diffusion Model source code, notice the camel case of some of the functions:

```<code>    def Upsample(dim, dim_out=None):
        return nn.Sequential(
            nn.Upsample(scale_factor=2, mode="nearest"),
            nn.Conv2d(dim, default(dim_out, dim), 3, padding=1),
        )
</code>```

I wonder if it is because it returns an object. The function is used like a constructor?

It somehow reminds me import torch.nn.functional as F which must have seen millions of times. But couldn't recollect why the capital F here. Google search did not turn out any good answers.

Body:
Need help on understanding some naming patterns I see so far.

Reading The Annotated Diffusion Model source code, notice the camel case of some of the functions:

    def Upsample(dim, dim_out=None):
        return nn.Sequential(
            nn.Upsample(scale_factor=2, mode="nearest"),
            nn.Conv2d(dim, default(dim_out, dim), 3, padding=1),
        )

I wonder if it is because it returns an object. The function is used like a constructor?

It somehow reminds me import torch.nn.functional as F which must have seen millions of times. But couldn't recollect why the capital F here. Google search did not turn out any good answers.


问:
NVDA reads the first letter of the word, then the word from the autocomplete dropdown list
I am working on .NET MVC project and I have problem with NVDA and JAWS reader on the dropdown list. It is the dropdown autocomplete list, and when I am navigating with the keyboard, it was reading double values from the dropdown list.

Then I have added aria-hidden="true", and now it is reading the first alphabet of the value, then the value. For example, this dropdown list:

```<code>car
apple
watch
</code>```

It is reading this:

```<code>c
car
a
apple
w
watch
</code>```

What should I do to read only values?

Code from cshtml:

```<code> <input id="client" aria-hidden="true" type="text" class="form-control" data-html="true"  placeholder="Enter @Model.ClientTitle">
</code>```

Code from JS:

```<code>     $('#client').autocomplete({
                    source: function (request, response) {
                        response($.map(clients, function (item, key) {
                                return {
                                    label: item.Name + " (" + item.ClientId + ")",
                                    value: item.Name + " (" + item.ClientId + ")",
                                }
                            }
                        }));
                    },
                    select: function (event, ui) {
                        event.preventDefault();
                        if (ui.item.value === "") {
                            $('#client').val(null);
                            return false;
                        }
                        $('#client').val(ui.item.label);
                    },
                    response: function (event, ui) {
                        if (!ui.content.length) {
                            var noResult = { value: "", label: "No matches found." };
                            ui.content.push(noResult);
                        }
                    },
                    minLength: 3,
                    delay: 500
                });
</code>```

Body:
I am working on .NET MVC project and I have problem with NVDA and JAWS reader on the dropdown list. It is the dropdown autocomplete list, and when I am navigating with the keyboard, it was reading double values from the dropdown list.

Then I have added aria-hidden="true", and now it is reading the first alphabet of the value, then the value. For example, this dropdown list:

car
apple
watch

It is reading this:

c
car
a
apple
w
watch

What should I do to read only values?

Code from cshtml:

 <input id="client" aria-hidden="true" type="text" class="form-control" data-html="true"  placeholder="Enter @Model.ClientTitle">

Code from JS:

     $('#client').autocomplete({
                    source: function (request, response) {
                        response($.map(clients, function (item, key) {
                                return {
                                    label: item.Name + " (" + item.ClientId + ")",
                                    value: item.Name + " (" + item.ClientId + ")",
                                }
                            }
                        }));
                    },
                    select: function (event, ui) {
                        event.preventDefault();
                        if (ui.item.value === "") {
                            $('#client').val(null);
                            return false;
                        }
                        $('#client').val(ui.item.label);
                    },
                    response: function (event, ui) {
                        if (!ui.content.length) {
                            var noResult = { value: "", label: "No matches found." };
                            ui.content.push(noResult);
                        }
                    },
                    minLength: 3,
                    delay: 500
                });


问:
How can I add another prefix to the bot run by the following code?
I'm making a discord bot but I'm trying to use 2 prefix's (G! and g!) as its case sensitive but I cant figure out how to make a 2nd prefix for it to work.

I have tried to separate strings with a comma between 2 strings but I got error codes.

DETECTS WETHER MESSAGE HAS PREFIX (IN DIFFERENT FILE)

```<code>module.exports = (client, message) => {
    // Ignore all bots
    if (message.author.bot) return;

    // Ignore messages not starting with the prefix (in config.json)
    if (message.content.indexOf(client.config.prefix) !== 0) return;

</code>```

CONFIG FILE

```<code>{
  "token": "xxx",
  "prefix": "G!",
  "prefix2": "g!",
  "everyoneMention": true,
  "hostedBy": true
}

</code>```

Body:
I'm making a discord bot but I'm trying to use 2 prefix's (G! and g!) as its case sensitive but I cant figure out how to make a 2nd prefix for it to work.

I have tried to separate strings with a comma between 2 strings but I got error codes.

DETECTS WETHER MESSAGE HAS PREFIX (IN DIFFERENT FILE)

module.exports = (client, message) => {
    // Ignore all bots
    if (message.author.bot) return;

    // Ignore messages not starting with the prefix (in config.json)
    if (message.content.indexOf(client.config.prefix) !== 0) return;

CONFIG FILE

{
  "token": "xxx",
  "prefix": "G!",
  "prefix2": "g!",
  "everyoneMention": true,
  "hostedBy": true
}


问:
How to read just one character on a text File (or few characters) without using readLine() method?
I need to read only one character in a text File. Inside my method I've already have the BufferedReader object with the resource inside.

I can't read the line because my text file is ebcdic and it has more than 2GB on the same line.
There's no another line.
The object String doesn't support more than 2GB.

I need to check the first characters.

Can anybody help me?
Thanks!

I've tried to use the Scanner object and its methods but it didn't work.


问:
Redis Python Pipeline with repeated scores in the same batch just pushes last one
Suppose a batch of data in mapping format (string: int) for pushing to ordered set in redis.

```<code>mapping =

 {'{"t": 86810627, "p": "0.00422400", "q": "5.61700000", "b": 1004555074, "a": 1004555241,"T": 1671122467322, "m": true, "M": true}': 1671122467322,
  '{"t": 86810628, "p": "0.00422400", "q": "1.00000000", "b": 1004555157, "a": 1004555241, "T": 1671122467322, "m": true, "M": true}': 1671122467322,
  '{"t": 86810629, "p": "0.00422400", "q": "2.95800000", "b": 1004555220, "a": 1004555241, "T": 1671122467322, "m": true, "M": true}': 1671122467322}
</code>```

These are 3 sell operations done at the exact same timestamp: 1671122467322, which I would like to use as score to fetch by timestamps ranges.

When I put this mapping to redis ordered set using a pipe, just the last mapping is pushed to redis, but redis docs says that the required unique object is the member, not the score (redis_docs)

¿How can be pushed in pipes mappings with repeated scores (different members)?

```<code># params used
pipeline.zadd(name=key, mapping=mapping, lt=False, xx=False, nx=False, gt=False, ch=True, incr=False)
pipeline.execute()
</code>```

But, in my redis server, just last map from blocks with same scoring is saved.

Body:
Suppose a batch of data in mapping format (string: int) for pushing to ordered set in redis.

mapping =

 {'{"t": 86810627, "p": "0.00422400", "q": "5.61700000", "b": 1004555074, "a": 1004555241,"T": 1671122467322, "m": true, "M": true}': 1671122467322,
  '{"t": 86810628, "p": "0.00422400", "q": "1.00000000", "b": 1004555157, "a": 1004555241, "T": 1671122467322, "m": true, "M": true}': 1671122467322,
  '{"t": 86810629, "p": "0.00422400", "q": "2.95800000", "b": 1004555220, "a": 1004555241, "T": 1671122467322, "m": true, "M": true}': 1671122467322}

These are 3 sell operations done at the exact same timestamp: 1671122467322, which I would like to use as score to fetch by timestamps ranges.

When I put this mapping to redis ordered set using a pipe, just the last mapping is pushed to redis, but redis docs says that the required unique object is the member, not the score (redis_docs)

¿How can be pushed in pipes mappings with repeated scores (different members)?

# params used
pipeline.zadd(name=key, mapping=mapping, lt=False, xx=False, nx=False, gt=False, ch=True, incr=False)
pipeline.execute()

But, in my redis server, just last map from blocks with same scoring is saved.


问:
ECR image push fails
I'm trying to push a new image to my repository, and I get a wierd fail.

I did this action in the past from the same user with the same permissions, but it keeps failing. Any idea why?

```<code>aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/l4s5v1w9
</code>```
```<code>Error: Cannot perform an interactive login from a non TTY device
</code>```

Title: ECR image push fails

Body:
I'm trying to push a new image to my repository, and I get a wierd fail.

I did this action in the past from the same user with the same permissions, but it keeps failing. Any idea why?

aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/l4s5v1w9

Error: Cannot perform an interactive login from a non TTY device


问:
Creating path based on geometry Points received using websocket
I am creating a node js server which is fetching real-time data from websocket
I get 1 row of json string every second when it is triggered

I wanted to create a path from each row which also contains geometrical Point

```<code>For example, here's the data that we got:

[1] {"tag":"a", "areaName": "areaEntrance", "geomPoint": 0x00000000010CD9CEF753E3A5E33F6F1283C0CAA1D53F, "time": 2022-12-09 14:03:27}
[2] {"tag":"a", "areaName": "areaEntrance", "geomPoint": 0x00000000010C0C022B8716D9F43F666666666666EE3F, "time": 2022-12-09 14:03:28}
[3] {"tag":"b", "areaName": "areaEntrance", "geomPoint": 0x00000000010CF0A7C64B3789F73F9CC420B07268FF3F, "time": 2022-12-09 14:03:29}
[4] {"tag":"b", "areaName": "areaEntrance", "geomPoint": 0x00000000010C14AE47E17A14F83FC74B37894160F73F, "time": 2022-12-09 14:03:30}
[5] {"tag":"b", "areaName": "areaA", "geomPoint": 0x00000000010C23DBF97E6ABCF83FB0726891ED7C0040, "time": 2022-12-09 14:03:27.270}
[6] {"tag":"a", "areaName": "areaA", "geomPoint": 0x00000000010C273108AC1C5AFA3FA245B6F3FDD4F63F, "time": 2022-12-09 14:03:27.270}
[7] {"tag":"a", "areaName": "areaB", "geomPoint": 0x00000000010CA8C64B378941FC3F068195438B6CE73F, "time": 2022-12-09 14:03:27.270}
[8] {"tag":"a", "areaName": "areaExit", "geomPoint": 0x00000000010C643BDF4F8D9702403108AC1C5A640440, "time": 2022-12-09 14:03:31}
[9] {"tag":"a", "areaName": "areaExit", "geomPoint": 0x00000000010C48E17A14AE470540BC74931804560A40, "time": 2022-12-09 14:03:32}
[10] {"tag":"b", "areaName": "areaExit", "geomPoint": 0x00000000010CC976BE9F1A2F0C40F4FDD478E9260640, "time": 2022-12-09 14:03:33}
[11] {"tag":"b", "areaName": "areaExit", "geomPoint": 0x00000000010C54E3A59BC4200C40643BDF4F8D970940, "time": 2022-12-09 14:03:34}
...
</code>```

**here are the things that we have to pay attention when creating a path:

It will start when a tag has at least two rows of data when entering areaEntrance

It will end when a tag has at least two rows of data when entering areaExit

A tag can go to the areaEntrance after it enters areaExit (tag can be reused, meaning, one tag can have multiple paths)**

```<code> The goal is to have data like:

 [1] {"idPath": 1, "tag":"a", "areaName": "areaEntrance", "geomPoint": 0x00000000010CD9CEF753E3A5E33F6F1283C0CAA1D53F, "time": 2022-12-09 14:03:27}
 [2] {"idPath": 1, "tag":"a", "areaName": "areaEntrance", "geomPoint": 0x00000000010C0C022B8716D9F43F666666666666EE3F, "time": 2022-12-09 14:03:28}
 [3] {"idPath": 2, "tag":"b", "areaName": "areaEntrance", "geomPoint": 0x00000000010CF0A7C64B3789F73F9CC420B07268FF3F, "time": 2022-12-09 14:03:29}
 [4] {"idPath": 2, "tag":"b", "areaName": "areaEntrance", "geomPoint": 0x00000000010C14AE47E17A14F83FC74B37894160F73F, "time": 2022-12-09 14:03:30}
 [5] {"idPath": 2, "tag":"b", "areaName": "areaA", "geomPoint": 0x00000000010C23DBF97E6ABCF83FB0726891ED7C0040, "time": 2022-12-09 14:03:27.270}
 [6] {"idPath": 1, "tag":"a", "areaName": "areaA", "geomPoint": 0x00000000010C273108AC1C5AFA3FA245B6F3FDD4F63F, "time": 2022-12-09 14:03:27.270}
 [7] {"idPath": 1, "tag":"a", "areaName": "areaB", "geomPoint": 0x00000000010CA8C64B378941FC3F068195438B6CE73F, "time": 2022-12-09 14:03:27.270}
 [8] {"idPath": 1, "tag":"a", "areaName": "areaExit", "geomPoint": 0x00000000010C643BDF4F8D9702403108AC1C5A640440, "time": 2022-12-09 14:03:31}
 [9] {"idPath": 1, "tag":"a", "areaName": "areaExit", "geomPoint": 0x00000000010C48E17A14AE470540BC74931804560A40, "time": 2022-12-09 14:03:32}
 [10] {"idPath": 2, "tag":"b", "areaName": "areaExit", "geomPoint": 0x00000000010CC976BE9F1A2F0C40F4FDD478E9260640, "time": 2022-12-09 14:03:33}
 [11] {"idPath": 2, "tag":"b", "areaName": "areaExit", "geomPoint": 0x00000000010C54E3A59BC4200C40643BDF4F8D970940, "time": 2022-12-09 14:03:34}
 [12] {"idPath": 3, "tag":"a", "areaName": "areaEntrance", "geomPoint": 0x00000000010CD9CEF753E3A5E33F6F1283C0CAA1D53F, "time": 2022-12-09 14:04:35}
 [13] {"idPath": 4, "tag":"b", "areaName": "areaEntrance", "geomPoint": 0x00000000010CD9CEF753E3A5E33F6F1283C0CAA1D53F, "time": 2022-12-09 14:04:36}
</code>```

...

notes:
idPath is used to verify where the tags belong to

Anyone has any idea how to do it?
It can be done in javascript or SQL

I tried to do it in javascript and SQL but none of this is working

I have no idea how to set the value on real-time data

Body:
I am creating a node js server which is fetching real-time data from websocket
I get 1 row of json string every second when it is triggered

I wanted to create a path from each row which also contains geometrical Point

For example, here's the data that we got:

[1] {"tag":"a", "areaName": "areaEntrance", "geomPoint": 0x00000000010CD9CEF753E3A5E33F6F1283C0CAA1D53F, "time": 2022-12-09 14:03:27}
[2] {"tag":"a", "areaName": "areaEntrance", "geomPoint": 0x00000000010C0C022B8716D9F43F666666666666EE3F, "time": 2022-12-09 14:03:28}
[3] {"tag":"b", "areaName": "areaEntrance", "geomPoint": 0x00000000010CF0A7C64B3789F73F9CC420B07268FF3F, "time": 2022-12-09 14:03:29}
[4] {"tag":"b", "areaName": "areaEntrance", "geomPoint": 0x00000000010C14AE47E17A14F83FC74B37894160F73F, "time": 2022-12-09 14:03:30}
[5] {"tag":"b", "areaName": "areaA", "geomPoint": 0x00000000010C23DBF97E6ABCF83FB0726891ED7C0040, "time": 2022-12-09 14:03:27.270}
[6] {"tag":"a", "areaName": "areaA", "geomPoint": 0x00000000010C273108AC1C5AFA3FA245B6F3FDD4F63F, "time": 2022-12-09 14:03:27.270}
[7] {"tag":"a", "areaName": "areaB", "geomPoint": 0x00000000010CA8C64B378941FC3F068195438B6CE73F, "time": 2022-12-09 14:03:27.270}
[8] {"tag":"a", "areaName": "areaExit", "geomPoint": 0x00000000010C643BDF4F8D9702403108AC1C5A640440, "time": 2022-12-09 14:03:31}
[9] {"tag":"a", "areaName": "areaExit", "geomPoint": 0x00000000010C48E17A14AE470540BC74931804560A40, "time": 2022-12-09 14:03:32}
[10] {"tag":"b", "areaName": "areaExit", "geomPoint": 0x00000000010CC976BE9F1A2F0C40F4FDD478E9260640, "time": 2022-12-09 14:03:33}
[11] {"tag":"b", "areaName": "areaExit", "geomPoint": 0x00000000010C54E3A59BC4200C40643BDF4F8D970940, "time": 2022-12-09 14:03:34}
...

**here are the things that we have to pay attention when creating a path:

It will start when a tag has at least two rows of data when entering areaEntrance

It will end when a tag has at least two rows of data when entering areaExit

A tag can go to the areaEntrance after it enters areaExit (tag can be reused, meaning, one tag can have multiple paths)**

 The goal is to have data like:

 [1] {"idPath": 1, "tag":"a", "areaName": "areaEntrance", "geomPoint": 0x00000000010CD9CEF753E3A5E33F6F1283C0CAA1D53F, "time": 2022-12-09 14:03:27}
 [2] {"idPath": 1, "tag":"a", "areaName": "areaEntrance", "geomPoint": 0x00000000010C0C022B8716D9F43F666666666666EE3F, "time": 2022-12-09 14:03:28}
 [3] {"idPath": 2, "tag":"b", "areaName": "areaEntrance", "geomPoint": 0x00000000010CF0A7C64B3789F73F9CC420B07268FF3F, "time": 2022-12-09 14:03:29}
 [4] {"idPath": 2, "tag":"b", "areaName": "areaEntrance", "geomPoint": 0x00000000010C14AE47E17A14F83FC74B37894160F73F, "time": 2022-12-09 14:03:30}
 [5] {"idPath": 2, "tag":"b", "areaName": "areaA", "geomPoint": 0x00000000010C23DBF97E6ABCF83FB0726891ED7C0040, "time": 2022-12-09 14:03:27.270}
 [6] {"idPath": 1, "tag":"a", "areaName": "areaA", "geomPoint": 0x00000000010C273108AC1C5AFA3FA245B6F3FDD4F63F, "time": 2022-12-09 14:03:27.270}
 [7] {"idPath": 1, "tag":"a", "areaName": "areaB", "geomPoint": 0x00000000010CA8C64B378941FC3F068195438B6CE73F, "time": 2022-12-09 14:03:27.270}
 [8] {"idPath": 1, "tag":"a", "areaName": "areaExit", "geomPoint": 0x00000000010C643BDF4F8D9702403108AC1C5A640440, "time": 2022-12-09 14:03:31}
 [9] {"idPath": 1, "tag":"a", "areaName": "areaExit", "geomPoint": 0x00000000010C48E17A14AE470540BC74931804560A40, "time": 2022-12-09 14:03:32}
 [10] {"idPath": 2, "tag":"b", "areaName": "areaExit", "geomPoint": 0x00000000010CC976BE9F1A2F0C40F4FDD478E9260640, "time": 2022-12-09 14:03:33}
 [11] {"idPath": 2, "tag":"b", "areaName": "areaExit", "geomPoint": 0x00000000010C54E3A59BC4200C40643BDF4F8D970940, "time": 2022-12-09 14:03:34}
 [12] {"idPath": 3, "tag":"a", "areaName": "areaEntrance", "geomPoint": 0x00000000010CD9CEF753E3A5E33F6F1283C0CAA1D53F, "time": 2022-12-09 14:04:35}
 [13] {"idPath": 4, "tag":"b", "areaName": "areaEntrance", "geomPoint": 0x00000000010CD9CEF753E3A5E33F6F1283C0CAA1D53F, "time": 2022-12-09 14:04:36}

...

notes:
idPath is used to verify where the tags belong to

Anyone has any idea how to do it?
It can be done in javascript or SQL

I tried to do it in javascript and SQL but none of this is working

I have no idea how to set the value on real-time data


问:
Imbalanced classes in a graph classification problem
Graph Classification Problem Input Data Size: (1280,32,16) --> 32 EEG channels , 16 features for each channel Labels Size : (1280) -> 2 classes

I want to classify 1280 data with features size : (1280,32,16) through a graph convolution neural network but on the validation stage, I didn't get a good f1-score because of classes imbalance. Is there any way to use something like ADASYN (on machine learning similar problems) but for graph type data?


问:
GCOV Profiling: ".gcda:Version mismatch"
I'm currently compiling sources using --coverage, with GCC. The generated .gcno files (and the instrumented libraries) are to be packed in a RPM and the code coverage evaluated on another, target platform.

Now, I'm having a problem getting the coverage data, because when I run the programs calling the instrumented code, I get messages telling me that I have a version mismatch. They look like:

".gcda:Version mismatch - expected A85R got B12R"

Now, I've seen this question: GCOV Version mismatch - expected 700e got 408R which says I must use the same toolchain when compiling and when executing the code.

I'm compiling using gcc 11.2.1, and gcov --version says the same thing, on the source platform.
On the target platform, gcc --version and gcov --version both give that very same version number.

The compiling and the testing is done on the same "physical" machine, but on different Docker containers. On both of them, the GCC version and gcov version are the same

I've done further testing: even on the Docker container where we compile, we cannot run the coverage, and get the same error. Or, to be more precise, when compiled using gcc 11, it will say "version mismatch". However, when compiled using gcc 8.5, it works.

The setup is that we have the GCC 11 toolset, which requires gcc 8.5 to install. By default, gcc 8.5 is enabled, and you have to use a script (provided by the gcc 11 toolset) to enable the later. That script updates different variables, like the PATH, LIBRARY_PATH, etc., to look at GCC 11 first.

However, I'm pretty sure it doesn't upgrade the libc.so library, and that it's the cause of the problem: I compiled two of our simplest libs (each of them having no dependencies whatsoever, except libc) with gcc 11, in coverage mode. Then I compiled a simple test program, without coverage, calling some functions from the two instrumented libs. I checked (with elfread -d), the program only links to these two libs (and libc).

Calling this test program while on the compilation container results in the Version mismatch error, which would lead me to conclude that our libc.so isn't compatible with gcc 11.

I wonder if there is a way to get a "native" gcc 11, instead of a "toolkit" package which has to be installed over a gcc 8.5 (my colleague in charge of creating the Docker containers tells me that for gcc 9 and above, there are only "toolkit" packages, requiring gcc 8.5 to install).

Our target architecture runs on Rocky Linux, and I think our development architecture is a Redhat, if it has any importance here.


问:
FastAPI API Versioning - specifying deprecated version in Header
I am using a Header named Accept-Version to handle API versioning in my FastAPI project at the function level. Following fastapi documentation, a sub-class that inherits from str and from Enum is used to predefine the version that the header can accept.

As the project goes on, I want to mark the old versions as deprecated without removing it. The code is as follows.

from enum import Enum
from typing import Union
from fastapi import FastAPI, Header
from pydantic import BaseModel

app = FastAPI()

class VersionNumber(str, Enum):
    _1_1 = "1.1 (deprecated)"
    _1_2 = "1.2"
    _1_3 = "1.3"

class Item(BaseModel):
    name: str
    price: float

@app.post("/items")
async def update_item(item: Union[Item, None], accept_version: VersionNumber=Header(VersionNumber._1_2)):
    accept_version = accept_version.replace('(deprecated)', '')
    accept_version = float(accept_version)
    if accept_version == 1.1:
        return item
    elif accept_version >= 1.2 and accept_version < 1.3:
        return item.dict()["name"], item.dict()["price"]
    else:
        return item.dict()["name"]

```

Based on the code above, the Swagger UI is able to show version 1.1 as deprecated, which looks like this.

However, when sending the request, it is accepting 1.1 (deprecated) instead of 1.1 as a value for Accept-Version header, which is not desirable. Is there a way to elegantly mark version 1.1 as deprecated and keep the header as 1.1?

Body:
I am using a Header named Accept-Version to handle API versioning in my FastAPI project at the function level. Following fastapi documentation, a sub-class that inherits from str and from Enum is used to predefine the version that the header can accept.

As the project goes on, I want to mark the old versions as deprecated without removing it. The code is as follows.

from enum import Enum
from typing import Union
from fastapi import FastAPI, Header
from pydantic import BaseModel

app = FastAPI()

class VersionNumber(str, Enum):
    _1_1 = "1.1 (deprecated)"
    _1_2 = "1.2"
    _1_3 = "1.3"

class Item(BaseModel):
    name: str
    price: float

@app.post("/items")
async def update_item(item: Union[Item, None], accept_version: VersionNumber=Header(VersionNumber._1_2)):
    accept_version = accept_version.replace('(deprecated)', '')
    accept_version = float(accept_version)
    if accept_version == 1.1:
        return item
    elif accept_version >= 1.2 and accept_version < 1.3:
        return item.dict()["name"], item.dict()["price"]
    else:
        return item.dict()["name"]

Based on the code above, the Swagger UI is able to show version 1.1 as deprecated, which looks like this.

However, when sending the request, it is accepting 1.1 (deprecated) instead of 1.1 as a value for Accept-Version header, which is not desirable. Is there a way to elegantly mark version 1.1 as deprecated and keep the header as 1.1?


问:
How to use the alchemy web3 library in kotlin (android studio)
I was wondering how I can program an android app in android studio using the web3 library alchemy which is programmed for javascript.
Within kotlin android studio, I want to perform the alchemy javascript call and get the return values in kotlin again.

I would be very happy for some input.
Do you recommend using kotlin android studio at all or do you have a better web3 library for kotlin in mind?

I have tried calling the alchemy library in both kotlin (androidx.javascriptengine) and javascript (though the WebView class), but I am unable to execute the function and return the values.
I have also tried switching to java instead of kotlin, which was also unsuccessful.


问:
Issue with Rendering Custom module Terms and Conditions field
I would like to move the jQuery code to a separate file like you can see in the second code but if I do this the functionality of the code does not display on the page. The first code works properly and the second code does not work?

I turned off the caching plugin and still nothing.

There are other modules in this custom-woocommerce.js file and those work fine only code from this example shows some problems.

First Code

```<code>add_action('woocommerce_review_order_before_submit', 'cart_privacy_policy_checkbox', 5);
function cart_privacy_policy_checkbox()
{
    woocommerce_form_field('privacy_policy', array(
        'type' => 'checkbox',
        'class' => array('form-row privacy'),
        'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
        'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
        'required' => true,
        'label' => sprintf(
            __('<span class="woocommerce-terms-and-conditions-checkbox-text">Przeczytałem/am i akceptuję <a href="#/regulamin-serwisu/" target="_blank"><strong>Regulamin</strong></a></span>'),
        ),
    ));

    if (is_checkout()) {
        wp_enqueue_script('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2@11.6.15/dist/sweetalert2.all.min.js', array(), '11.6.15', false);
        wp_enqueue_script('promise-polyfill', 'https://cdnjs.cloudflare.com/ajax/libs/promise-polyfill/8.2.3/polyfill.min.js', array(), '8.2.3', false);
        ?>
<script type="text/javascript">
jQuery(function($) {
    var a = '#place_order',
        b = '#privacy_policy',
        c = '<?php echo wc_get_checkout_url(); ?>',
        d = 'disabled';

    // Set disable button state
    $(a).addClass(d).prop('href', '#');

    // On button click event
    $('body').on('click', a, function(e) {
        if (!$(b).prop('checked')) {
            // Disable "Proceed to checkout" button
            e.preventDefault();
            // disabling button state
            if (!$(a).hasClass(d)) {
                $(a).addClass(d).prop('href', '#');
            }
            // Sweet alert 2
            Swal.fire({
                background: '#fff',
                toast: false,
                width: 'auto',
                icon: 'error',
                position: 'center',
                title: 'Wystąpił błąd',
                html: '<strong>Zaakceptowanie regulaminu jest wymagane,</strong> ' +
                    'aby kontynuować składanie zamówienia',
                // text: ' ',
                timer: 5000,
                timerProgressBar: true,
                showConfirmButton: false
            });
        }
    });
    // On checkbox change event
    $(b).change(function() {
        if ($(this).prop('checked')) {
            if ($(a).hasClass(d)) {
                $(a).removeClass(d).prop('href', c);
            }
        } else {
            if (!$(a).hasClass(d)) {
                $(a).addClass(d).prop('href', '#');
            }
        }
    });

    $('#privacy_policy').click(function() {
        if ($(this).is(":checked")) {
            $('.custom-download-info').fadeIn('300');
        } else {
            $('.custom-download-info').fadeOut('300');
        }
    })

});
</script>
<?php
}
}
</code>```

Second code

```<code>add_action('woocommerce_review_order_before_submit', 'cart_privacy_policy_checkbox', 5);
function cart_privacy_policy_checkbox()
{
    woocommerce_form_field('privacy_policy', array(
        'type' => 'checkbox',
        'class' => array('form-row privacy'),
        'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
        'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
        'required' => true,
        'label' => sprintf(
            __('<span class="woocommerce-terms-and-conditions-checkbox-text">Przeczytałem/am i akceptuję <a href="https://sprawdziany.pl/regulamin-serwisu/" target="_blank"><strong>Regulamin</strong></a></span>'),
        ),
    ));

    if (is_checkout()) {
        wp_enqueue_script('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2@11.6.15/dist/sweetalert2.all.min.js', array(), '11.6.15', false);
        wp_enqueue_script('promise-polyfill', 'https://cdnjs.cloudflare.com/ajax/libs/promise-polyfill/8.2.3/polyfill.min.js', array(), '8.2.3', false);
        wp_enqueue_script('custom-woocommerce', '/path/to/custom-woocommerce.js', array(), '1.0.0.' . time(), false);
}
}
</code>```

Body:
I would like to move the jQuery code to a separate file like you can see in the second code but if I do this the functionality of the code does not display on the page. The first code works properly and the second code does not work?

I turned off the caching plugin and still nothing.

There are other modules in this custom-woocommerce.js file and those work fine only code from this example shows some problems.

First Code

add_action('woocommerce_review_order_before_submit', 'cart_privacy_policy_checkbox', 5);
function cart_privacy_policy_checkbox()
{
    woocommerce_form_field('privacy_policy', array(
        'type' => 'checkbox',
        'class' => array('form-row privacy'),
        'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
        'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
        'required' => true,
        'label' => sprintf(
            __('Przeczytałem/am i akceptuję Regulamin'),
        ),
    ));

    if (is_checkout()) {
        wp_enqueue_script('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2@11.6.15/dist/sweetalert2.all.min.js', array(), '11.6.15', false);
        wp_enqueue_script('promise-polyfill', 'https://cdnjs.cloudflare.com/ajax/libs/promise-polyfill/8.2.3/polyfill.min.js', array(), '8.2.3', false);
        ?>

<?php
}
}

Second code

add_action('woocommerce_review_order_before_submit', 'cart_privacy_policy_checkbox', 5);
function cart_privacy_policy_checkbox()
{
    woocommerce_form_field('privacy_policy', array(
        'type' => 'checkbox',
        'class' => array('form-row privacy'),
        'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
        'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
        'required' => true,
        'label' => sprintf(
            __('Przeczytałem/am i akceptuję Regulamin'),
        ),
    ));

    if (is_checkout()) {
        wp_enqueue_script('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2@11.6.15/dist/sweetalert2.all.min.js', array(), '11.6.15', false);
        wp_enqueue_script('promise-polyfill', 'https://cdnjs.cloudflare.com/ajax/libs/promise-polyfill/8.2.3/polyfill.min.js', array(), '8.2.3', false);
        wp_enqueue_script('custom-woocommerce', '/path/to/custom-woocommerce.js', array(), '1.0.0.' . time(), false);
}
}


问:
Symfony fosRouter js in handlebars
Is possible to push

```<code>Routing.generate()
</code>```

to handlebars template ?

Title: Symfony fosRouter js in handlebars

Body:
Is possible to push

Routing.generate()

to handlebars template ?


问:
How to make a treeview recursive menu in Vue.js but every branch is filled by an API request via Axios?
I need to make a treeview recursive menu in vue.js and i want every branch to be filled with a spefic array collected by an API call with Axios. I found already on the web some examples of this specific menu but i didnt manage put in the data the response from the axios call.

Here there is an example of the aformentioned menu

Menu.vue component

<template>

    <MenuItem
      v-for="(item, index) in menuTree"
      :key="index"
      :data="item.children"
      :label="item.label"
      :icon="item.icon"
      :depth="0"
      :smallMenu="smallMenu"
    />
    menu

</template>
```
<pre class="lang-js prettyprint-override"><code><script>
import MenuItem from './MenuItem.vue';
export default {
  name: 'recursive-menu',
  data: () => ({
    smallMenu: false,
    menuTree: [
      {
        label: "Home",
        icon: "home",
        children: [
          {
            label: "level 1.1",
            children: [
              {
                label: "level 1.1.1",
                children: [
                  {
                    label: "level 1.1.1.1"
                  }
                ]
              }
            ]
          },
          {
            label: "level 1.2"
          }
        ]
      },
      {
        label: "Dashboard",
        icon: "dashboard",
        children: [
          {
            label: "level 2.1",
          },
          {
            label: "level 2.2"
          },
          {
            label: "level 2.3"
          }
        ]
      },
      {
        label: "Settings",
        icon: "settings"
      }
    ]
  }),
  components: {
    MenuItem
  }
}
</script>
</code>```

```
<p>Here is the response from the API</p>
<pre class="lang-json prettyprint-override"><code>{
    "success": 1,
    "numElements": 6,
    "data": [
        {
            "id": "1",
            "categoryName": "Fatturato",
            "fkParent": null,
            "hasChild": "1"
        },
        {
            "id": "2",
            "categoryName": "Fatturato Clienti",
            "fkParent": "1",
            "hasChild": "0"
        },
        {
            "id": "3",
            "categoryName": "Fatturato Fornitori",
            "fkParent": "1",
            "hasChild": "0"
        },
        {
            "id": "4",
            "categoryName": "Scaduto",
            "fkParent": null,
            "hasChild": "1"
        },
        {
            "id": "5",
            "categoryName": "Scaduto Clienti",
            "fkParent": "4",
            "hasChild": "0"
        },
        {
            "id": "6",
            "categoryName": "Scaduto Fornitori",
            "fkParent": "4",
            "hasChild": "0"
        }
    ]
}
</code>```

Body:
I need to make a treeview recursive menu in vue.js and i want every branch to be filled with a spefic array collected by an API call with Axios. I found already on the web some examples of this specific menu but i didnt manage put in the data the response from the axios call.

Here there is an example of the aformentioned menu

Menu.vue component

<template>

    <MenuItem
      v-for="(item, index) in menuTree"
      :key="index"
      :data="item.children"
      :label="item.label"
      :icon="item.icon"
      :depth="0"
      :smallMenu="smallMenu"
    />
    menu

</template>

Here is the response from the API

{
    "success": 1,
    "numElements": 6,
    "data": [
        {
            "id": "1",
            "categoryName": "Fatturato",
            "fkParent": null,
            "hasChild": "1"
        },
        {
            "id": "2",
            "categoryName": "Fatturato Clienti",
            "fkParent": "1",
            "hasChild": "0"
        },
        {
            "id": "3",
            "categoryName": "Fatturato Fornitori",
            "fkParent": "1",
            "hasChild": "0"
        },
        {
            "id": "4",
            "categoryName": "Scaduto",
            "fkParent": null,
            "hasChild": "1"
        },
        {
            "id": "5",
            "categoryName": "Scaduto Clienti",
            "fkParent": "4",
            "hasChild": "0"
        },
        {
            "id": "6",
            "categoryName": "Scaduto Fornitori",
            "fkParent": "4",
            "hasChild": "0"
        }
    ]
}


问:
HTTP GET request from bingx api endpoint not working: Full authentication is required to access this resource
I'm trying to obtain the current market value of a coin from the bingx exchange, and I'm doing an http get request on what I believe is the correct api endpoint. after acquiring an access token it's still not allowing me to access the resource, is my logic flawed or am I just querying the wrong endpoint?</p>
```<code>// get the current market value of a coin on Bingx - not working
func getBingxPriceWithAuth(currency string) {
    // set API endpoint
    url := "https://api.bingx.com/api/v3/ticker/price?symbol=" + currency

    // create HTTP client
    client := &http.Client{
        Timeout: time.Second * 10,
    }

    // create HTTP GET request
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
    }

    // add the API credentials
    req.Header.Add("Bingx-API-Key", MYKEY)
    req.Header.Add("Bingx-API-Secret", MYSECRET)

    // HTTP GET request
    resp, err := client.Do(req)
    if err != nil {
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
    }

    fmt.Println()
    // parse the JSON
    var data map[string]interface{}
    err = json.Unmarshal(body, &data)
    if err != nil {
    }

    fmt.Println(data)t
    //return data["price"].(float64)
}
</code>```

Body:
I'm trying to obtain the current market value of a coin from the bingx exchange, and I'm doing an http get request on what I believe is the correct api endpoint. after acquiring an access token it's still not allowing me to access the resource, is my logic flawed or am I just querying the wrong endpoint?

// get the current market value of a coin on Bingx - not working
func getBingxPriceWithAuth(currency string) {
    // set API endpoint
    url := "https://api.bingx.com/api/v3/ticker/price?symbol=" + currency

    // create HTTP client
    client := &http.Client{
        Timeout: time.Second * 10,
    }

    // create HTTP GET request
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
    }

    // add the API credentials
    req.Header.Add("Bingx-API-Key", MYKEY)
    req.Header.Add("Bingx-API-Secret", MYSECRET)

    // HTTP GET request
    resp, err := client.Do(req)
    if err != nil {
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
    }

    fmt.Println()
    // parse the JSON
    var data map[string]interface{}
    err = json.Unmarshal(body, &data)
    if err != nil {
    }

    fmt.Println(data)t
    //return data["price"].(float64)
}


问:
Qwidget - Image Zoom in And Zoom Out Using Mouse Scroll
Currently, I use the class as below and promote it to graphics view to Zoom in and zoom out image. but how to stop zoom out when the resolution of image equals the original resolution of image and how to use press and hold scroll mouse to move picture when the resolution of image bigger than original resolution of image instead of use left mouse.

This is my code:

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

Custom_View::Custom_View(QWidget *parent) : QGraphicsView(parent)
{

}

void Custom_View::wheelEvent(QWheelEvent *_wheelEvent)
{
    setTransformationAnchor(AnchorUnderMouse);
    setDragMode(ScrollHandDrag);

    double scaleFactor = 1.2;
    if (_wheelEvent->delta()>0){
        scale(scaleFactor,scaleFactor);
    }
    else
    {
        scale(1/scaleFactor,1/scaleFactor);
    }
}
</code>```

My Question:

How to stop zoom out when the resolution of image equals the original resolution of image ? and how to use press and hold scroll mouse to move picture when the resolution of image bigger than original resolution of image instead of use left mouse.

Body:
Currently, I use the class as below and promote it to graphics view to Zoom in and zoom out image. but how to stop zoom out when the resolution of image equals the original resolution of image and how to use press and hold scroll mouse to move picture when the resolution of image bigger than original resolution of image instead of use left mouse.

This is my code:

#include "custom_view.h"

Custom_View::Custom_View(QWidget *parent) : QGraphicsView(parent)
{

}

void Custom_View::wheelEvent(QWheelEvent *_wheelEvent)
{
    setTransformationAnchor(AnchorUnderMouse);
    setDragMode(ScrollHandDrag);

    double scaleFactor = 1.2;
    if (_wheelEvent->delta()>0){
        scale(scaleFactor,scaleFactor);
    }
    else
    {
        scale(1/scaleFactor,1/scaleFactor);
    }
}

My Question:

How to stop zoom out when the resolution of image equals the original resolution of image ? and how to use press and hold scroll mouse to move picture when the resolution of image bigger than original resolution of image instead of use left mouse.


问:
T-distributed Stochastic Neighbor Embedding (t-SNE)
I am trying to run T-distributed Stochastic Neighbor Embedding (t-SNE) in Jupyter but always facing a issue with

```<code>ValueError: could not convert string to float: '<Null>'
</code>```

Code:
enter image description here

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler

# Reading the data using pandas
df = pd.read_csv("E:\\Field data\Output\\Pixel values7.csv")

# print first five rows of df
print(df.head(9))
# save the labels into a variable l.
l = df['label']

# Drop the label feature and store the pixel data in d.
d = df.drop("label", axis = 1)

I got error after this line
# Data-preprocessing: Standardizing the data
from sklearn.preprocessing import StandardScaler
standardized_data = StandardScaler().fit_transform(df)
print(standardized_data.shape)

# TSNE
# Picking the top 1000 points as TSNE
# takes a lot of time for 15K points
data_1000 = standardized_data[0:1000, :]
labels_1000 = labels[0:1000]

model = TSNE(n_components = 2, random_state = 0)
# configuring the parameters
# the number of components = 2
# default perplexity = 30
# default learning rate = 200
# default Maximum number of iterations
# for the optimization = 1000

tsne_data = model.fit_transform(data_1000)

# creating a new data frame which
# help us in plotting the result data
tsne_data = np.vstack((tsne_data.T, labels_1000)).T
tsne_df = pd.DataFrame(data = tsne_data,
     columns =("Dim_1", "Dim_2", "label"))

# Plotting the result of tsne
sn.FacetGrid(tsne_df, hue ="label", size = 6).map(
       plt.scatter, 'Dim_1', 'Dim_2').add_legend()

plt.show()
</code>```

I got this link from somewhere, I am not expert in python. I request you to kindly help me out.

I am trying to run this program for my data but always getting a error

```<code>
ValueError: could not convert string to float: '<Null>'
</code>```

If there is any other code for T-distributed Stochastic Neighbor Embedding (t-SNE). Please let me know.

My data look like this

Body:
I am trying to run T-distributed Stochastic Neighbor Embedding (t-SNE) in Jupyter but always facing a issue with

ValueError: could not convert string to float: '<Null>'

Code:
enter image description here

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler

# Reading the data using pandas
df = pd.read_csv("E:\\Field data\Output\\Pixel values7.csv")

# print first five rows of df
print(df.head(9))
# save the labels into a variable l.
l = df['label']

# Drop the label feature and store the pixel data in d.
d = df.drop("label", axis = 1)

I got error after this line
# Data-preprocessing: Standardizing the data
from sklearn.preprocessing import StandardScaler
standardized_data = StandardScaler().fit_transform(df)
print(standardized_data.shape)

# TSNE
# Picking the top 1000 points as TSNE
# takes a lot of time for 15K points
data_1000 = standardized_data[0:1000, :]
labels_1000 = labels[0:1000]

model = TSNE(n_components = 2, random_state = 0)
# configuring the parameters
# the number of components = 2
# default perplexity = 30
# default learning rate = 200
# default Maximum number of iterations
# for the optimization = 1000

tsne_data = model.fit_transform(data_1000)

# creating a new data frame which
# help us in plotting the result data
tsne_data = np.vstack((tsne_data.T, labels_1000)).T
tsne_df = pd.DataFrame(data = tsne_data,
     columns =("Dim_1", "Dim_2", "label"))

# Plotting the result of tsne
sn.FacetGrid(tsne_df, hue ="label", size = 6).map(
       plt.scatter, 'Dim_1', 'Dim_2').add_legend()

plt.show()

I got this link from somewhere, I am not expert in python. I request you to kindly help me out.

I am trying to run this program for my data but always getting a error

ValueError: could not convert string to float: '<Null>'

If there is any other code for T-distributed Stochastic Neighbor Embedding (t-SNE). Please let me know.

My data look like this


问:
Why does zero - zero become nan in risc-v?
As it is shown in the following picture, I subtract fa0 (i.e. f10) register from itself to set it to zero. The register was already zero, but after subtraction, it became NaN. So, can anyone explain why zero - zero = NaN?

Update: I am using qemu-riscv32-static for simulation.


问:
Can we call POM from cypress custom command
I was wondering if we could call a page object model from a cypress custom commands. If this can happen then it could make cypress automated test more powerful</p>


问:
REACT - Scroll to image loaded when component is re-rendered (happens only on IOS)
I've done some research before come here to ask help, but this issue it's so weird that I can barely describe it to find for some help. Well, I coded pagination logic on my own using React. After finishing I've tested it on Windows using chrome, working fine, on Android using chrome and samsung browser, also working fine...but on IOS using both safari and chrome, when moving through pagination, it scrolls to the new image that is loaded breaking the scroll to the top that I implemented, this video sums up everything:

https://www.youtube.com/shorts/o3aDHOvDIto

You can see that everytime I change pagination it jumps to the image and then scroll to the top, after I cycle between all the posts, this behavior stops and the pagination do what I originally intended, scroll to the top after user select position of the pagination.

You can check it by yourself on you ios device (I was using iPhone 13)
https://hosana.dev/blog.html

Also here is my source code
https://github.com/diegodiego1989/hosana.dev-blog

What I'm doing wrong? Thanks in advance.

To be honest I have no idea on why this is happening.


问:
What style of object orienting programming causes Visual Studio Code to always highlighting existing method names?
I have to run a method (named "top") at several objects. So the reference to the object is a parameter of "top". Inside "top" I call a method "down" of the object. Of course this works. But as Visual Studio Code does not know, if the objects selected by the parameter have a method named "down", it cannot highlight the method name "down" at the line where it is called (in my environment the string "down" of "ref.down()", see example code, stays white instead of getting yellow). So my questions are: Am I working in a wrong way? Is there any better style of programming, which enables Visual Studio Code to highlight always any existing method?

This is my example python code:

```<code>class myclass_top:
    def __init__(self):
        ref1 = myclass_bottom()
        ref2 = myclass_bottom()
        self.top(ref1)
        self.top(ref2)

    def top(self, ref):
        ref.down()                  # <---- The string "down" is not highlighted.

class myclass_bottom:
    def __init__(self):
        self.var = 0

    def down(self):
        self.var -= 1

</code>```

Body:
I have to run a method (named "top") at several objects. So the reference to the object is a parameter of "top". Inside "top" I call a method "down" of the object. Of course this works. But as Visual Studio Code does not know, if the objects selected by the parameter have a method named "down", it cannot highlight the method name "down" at the line where it is called (in my environment the string "down" of "ref.down()", see example code, stays white instead of getting yellow). So my questions are: Am I working in a wrong way? Is there any better style of programming, which enables Visual Studio Code to highlight always any existing method?

This is my example python code:

class myclass_top:
    def __init__(self):
        ref1 = myclass_bottom()
        ref2 = myclass_bottom()
        self.top(ref1)
        self.top(ref2)

    def top(self, ref):
        ref.down()                  # <---- The string "down" is not highlighted.

class myclass_bottom:
    def __init__(self):
        self.var = 0

    def down(self):
        self.var -= 1


问:
sessionStorage data loss on page reload in angular13
I am encountering a situation where sessionStorage data loss on page reload in angular,
i also checked in browser application tab session storage ,that data saves when i navigate freshly on page, but once page reload all sessionStorage data loss.

below is code

```<code> constructor(private apiServ: ApiserviceService,
private dataServ: DataService,
private router: Router,
private route: ActivatedRoute) { }

ngOnInit(): void {

this.quiz = new Quiz();

this.browserRefresh = browserRefresh;
if (this.browserRefresh) {

  var tutname = sessionStorage.getItem("tutname");
  if (tutname) {
    this.tutorialName = tutname;
  }
  var testname = sessionStorage.getItem("testname");
  if (testname) {
    this.testName = testname;
  }

} else {

  this.route.params.subscribe((prams: Params) => {
    if (prams) {
      this.tutorialName = prams['tutorialName'];
      this.testName = prams['testName'];
      sessionStorage.setItem("tutname", this.tutorialName);
      sessionStorage.setItem("testname", this.testName);

    }
  })

}
</code>```

}

Firstly I thought its due to Lazyload component but not if i put sessionStorage outside else block the data survives on page reload i am not getting where is issue

Body:
I am encountering a situation where sessionStorage data loss on page reload in angular,
i also checked in browser application tab session storage ,that data saves when i navigate freshly on page, but once page reload all sessionStorage data loss.

below is code

 constructor(private apiServ: ApiserviceService,
private dataServ: DataService,
private router: Router,
private route: ActivatedRoute) { }

ngOnInit(): void {

this.quiz = new Quiz();

this.browserRefresh = browserRefresh;
if (this.browserRefresh) {

  var tutname = sessionStorage.getItem("tutname");
  if (tutname) {
    this.tutorialName = tutname;
  }
  var testname = sessionStorage.getItem("testname");
  if (testname) {
    this.testName = testname;
  }

} else {

  this.route.params.subscribe((prams: Params) => {
    if (prams) {
      this.tutorialName = prams['tutorialName'];
      this.testName = prams['testName'];
      sessionStorage.setItem("tutname", this.tutorialName);
      sessionStorage.setItem("testname", this.testName);

    }
  })

}

}

Firstly I thought its due to Lazyload component but not if i put sessionStorage outside else block the data survives on page reload i am not getting where is issue


问:
Retrofit requests in a specific order
So I have this UI, where I'm loading user data. First and last name, date of birth, address, postal code, and city.

For the city, I have an AutoCompleteTextView that I'm filling in by sending a GET request to the server and then using the response to create an Adapter:

```<code> val mContext = if (context is ViewComponentManager.FragmentContextWrapper)
                    (context as ViewComponentManager.FragmentContextWrapper).baseContext
                else
                    context

                mContext?.let { ctx ->
                    val cityAdapter =
                        WilayaAdapter(
                            ctx,
                            R.layout.wilaya_dropdown_item,
                            it?.data?.toList()!!
                        )
                    personalDetailsBinding.autoCompleteTextView.setAdapter(
                        cityAdapter
                    )

                    personalDetailsBinding.autoCompleteTextView.setOnItemClickListener { parent, _, position, _ ->
                        val city = cityAdapter.getItem(position) as WilayaItem?
                        personalDetailsBinding.autoCompleteTextView.setText(city?.WilayaName.toString());

                    }
                }
</code>```

Everything seems to be working fine so far, except when I try to change the selected city programmatically.

For some reason, the results are not consistent. 1 out of 5 times (or so), the app will crash and return a NullPointerException on this line (getItem):

```<code>val selectedWilaya = personalDetailsBinding.autoCompleteTextView.adapter.getItem(personalDetailsViewModel.userResponseLiveData.value?.data!!.Wilaya) as WilayaItem?
                    personalDetailsBinding.autoCompleteTextView.setText(selectedWilaya?.WilayaName, false)
</code>```

Meaning that (and for some reason) the Cities are sometimes loaded before the UserProfile, although I'm running them in a coroutine:

```<code> GlobalScope.launch {

        withContext(Dispatchers.IO)
        {
            personalDetailsViewModel.retrieveProfileData() // load the user Profile
            personalDetailsViewModel.retrieveWilayas() //load the Cities

        }
        withContext(Dispatchers.Main)
        {
            bindObservers() //UI update
        }

    }
</code>```

I even tried to split bindObservers into two functions, and call bindObserverCities whenever bindObserverUserProfile return Success, but that's not doing much either.

Title: Retrofit requests in a specific order

Body:
So I have this UI, where I'm loading user data. First and last name, date of birth, address, postal code, and city.

For the city, I have an AutoCompleteTextView that I'm filling in by sending a GET request to the server and then using the response to create an Adapter:

 val mContext = if (context is ViewComponentManager.FragmentContextWrapper)
                    (context as ViewComponentManager.FragmentContextWrapper).baseContext
                else
                    context

                mContext?.let { ctx ->
                    val cityAdapter =
                        WilayaAdapter(
                            ctx,
                            R.layout.wilaya_dropdown_item,
                            it?.data?.toList()!!
                        )
                    personalDetailsBinding.autoCompleteTextView.setAdapter(
                        cityAdapter
                    )

                    personalDetailsBinding.autoCompleteTextView.setOnItemClickListener { parent, _, position, _ ->
                        val city = cityAdapter.getItem(position) as WilayaItem?
                        personalDetailsBinding.autoCompleteTextView.setText(city?.WilayaName.toString());

                    }
                }

Everything seems to be working fine so far, except when I try to change the selected city programmatically.

For some reason, the results are not consistent. 1 out of 5 times (or so), the app will crash and return a NullPointerException on this line (getItem):

val selectedWilaya = personalDetailsBinding.autoCompleteTextView.adapter.getItem(personalDetailsViewModel.userResponseLiveData.value?.data!!.Wilaya) as WilayaItem?
                    personalDetailsBinding.autoCompleteTextView.setText(selectedWilaya?.WilayaName, false)

Meaning that (and for some reason) the Cities are sometimes loaded before the UserProfile, although I'm running them in a coroutine:

 GlobalScope.launch {

        withContext(Dispatchers.IO)
        {
            personalDetailsViewModel.retrieveProfileData() // load the user Profile
            personalDetailsViewModel.retrieveWilayas() //load the Cities

        }
        withContext(Dispatchers.Main)
        {
            bindObservers() //UI update
        }

    }

I even tried to split bindObservers into two functions, and call bindObserverCities whenever bindObserverUserProfile return Success, but that's not doing much either.


问:
Why is an extra login required to use AppTransaction with iOS 16.0?
In the app I am working on I have the need to check what version the user purchased the app first at. It seems that Apple's AppTransaction (available starting in iOS 16.0 as part of StoreKit) is made just for that purpose. But I noticed that when I first call "AppTransaction.shared", a "Sign in with Apple ID" prompt is coming up that asks for Apple ID and password.

While the documentation refers to the fact that the user must be authenticated with the App Store, I don't see any reference to throwing up this dialog box.

On my device I have already authenticated to the App Store, and have downloaded apps to verify this.

If only password was asked for security purposes then this dialog might make sense, but allowing the user to enter in another Apple ID (different from the one they are actually signed up via the device's Settings) seems like a bad idea. Furthermore, this is a pretty bad experience to users to have them authenticate again.

If anyone has any idea why this dialog is being shown, and if there is any way to get the version the app was first downloaded at w/o such a popup, that would be great.


问:
List comprehension to condense multi-level column index
I am attempting to use list comprehension in order to condense two tiers of column index into one.

My data currently looks as follows:

```<code>      Value
-----+-----------
Year |Jan|Feb|Mar
-----+---+---+---
2010 | 1 | 2 | 3
2011 | 1 | 2 | 6
2012 | 3 | 4 | 1
</code>```

Note that this is a condensed version for visualisation purpose and all months are represented in the true dataset. My goal is to change the formatting of the table so that I can have single column titles made up of both tiers at present. I think list comprehension is the best way to do this but am having trouble working out the logistics.

Ideally the headers for the columns will read Value_Jan, Value_Feb etc. once the transformation is complete.

Currently my code reads as follows:

```<code>cols = pd.MultiIndex.from_tuples[("Value", "April"),
                                  ("Value", "August"),
                                  ("Value", "December"),
                                  ("Value", "February"),
                                  ("Value", "January"),
                                  ("Value", "July"),
                                  ("Value", "June"),
                                  ("Value", "March"),
                                  ("Value", "May"),
                                  ("Value", "November"),
                                  ("Value", "October"),
                                  ("Value", "September")]
df = pd.df(columns=cols)
df.head()
</code>```

When this code is run I get the following error:

TypeError: 'method' object is not subscriptable

Any better ways to go about this or troubleshooting help would be greatly appreciated!

Body:
I am attempting to use list comprehension in order to condense two tiers of column index into one.

My data currently looks as follows:

      Value
-----+-----------
Year |Jan|Feb|Mar
-----+---+---+---
2010 | 1 | 2 | 3
2011 | 1 | 2 | 6
2012 | 3 | 4 | 1

Note that this is a condensed version for visualisation purpose and all months are represented in the true dataset. My goal is to change the formatting of the table so that I can have single column titles made up of both tiers at present. I think list comprehension is the best way to do this but am having trouble working out the logistics.

Ideally the headers for the columns will read Value_Jan, Value_Feb etc. once the transformation is complete.

Currently my code reads as follows:

cols = pd.MultiIndex.from_tuples[("Value", "April"),
                                  ("Value", "August"),
                                  ("Value", "December"),
                                  ("Value", "February"),
                                  ("Value", "January"),
                                  ("Value", "July"),
                                  ("Value", "June"),
                                  ("Value", "March"),
                                  ("Value", "May"),
                                  ("Value", "November"),
                                  ("Value", "October"),
                                  ("Value", "September")]
df = pd.df(columns=cols)
df.head()

When this code is run I get the following error:

TypeError: 'method' object is not subscriptable

Any better ways to go about this or troubleshooting help would be greatly appreciated!


问:
Write only certain headers into a csv file via openpyxl
I want to only write certain headered row into a csv file, provided i got the data from an excel file via openpyxl. For example, for the headers 'name', 'branch', 'year', 'cgpa' i only want to write values of name and year into the csv file. Can anyoe suggest me how can i do that?

Currently my code looks like this:

```<code>DFIT_FILE = r'C:\Users\xyz1.xlsx'

wb = openpyxl.load_workbook(DFIT_FILE)
ws = wb['sheet1']

with open('C:\\Users\data\\test.csv', 'w', newline="") as file_handle:
    csv_writer = csv.writer(file_handle)
    for row in ws.iter_rows(): # generator; was sh.rows

        csv_writer.writerow([cell.value for cell in row])

</code>```

I was trying to write only specific rows, but got all the rows as output

Body:
I want to only write certain headered row into a csv file, provided i got the data from an excel file via openpyxl. For example, for the headers 'name', 'branch', 'year', 'cgpa' i only want to write values of name and year into the csv file. Can anyoe suggest me how can i do that?

Currently my code looks like this:

DFIT_FILE = r'C:\Users\xyz1.xlsx'

wb = openpyxl.load_workbook(DFIT_FILE)
ws = wb['sheet1']

with open('C:\\Users\data\\test.csv', 'w', newline="") as file_handle:
    csv_writer = csv.writer(file_handle)
    for row in ws.iter_rows(): # generator; was sh.rows

        csv_writer.writerow([cell.value for cell in row])

I was trying to write only specific rows, but got all the rows as output


问:
how to use event timer inside loop pygame?
I'm trying to count every 0.1 second inside for loop with event timer

```<code>self.time_interval = 500  # 500 milliseconds == 0.1 seconds
self.timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(self.timer_event, self.time_interval, 1)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.QUIT
                sys.exit()
            if event.type == pygame.MOUSEBUTTONUP:
                for cell in self.groundcells:
                    if cell.collidepoint(pygame.mouse.get_pos()):
                        pygame.time.set_timer(self.timer_event, self.time_interval, 1)
            for i in range(5):
                if event.type == self.timer_event:
                    print('hi')
</code>```

It's just fragments from code, but it's should be enough I think.
So, as a result I've got displayed 5 times 'hi', but its appears at one time, which is not correct. Could be great if somebody can explain me how to fix that. If you can provide code for example as well, please, make so. Thank a lot guys.

Body:
I'm trying to count every 0.1 second inside for loop with event timer

self.time_interval = 500  # 500 milliseconds == 0.1 seconds
self.timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(self.timer_event, self.time_interval, 1)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.QUIT
                sys.exit()
            if event.type == pygame.MOUSEBUTTONUP:
                for cell in self.groundcells:
                    if cell.collidepoint(pygame.mouse.get_pos()):
                        pygame.time.set_timer(self.timer_event, self.time_interval, 1)
            for i in range(5):
                if event.type == self.timer_event:
                    print('hi')

It's just fragments from code, but it's should be enough I think.
So, as a result I've got displayed 5 times 'hi', but its appears at one time, which is not correct. Could be great if somebody can explain me how to fix that. If you can provide code for example as well, please, make so. Thank a lot guys.


问:
Componentdidcatch references only to main.chunk.js instead of real file name while going production mode
So I have used errorboundry that react gives to catch crashes/errors on sites. In debug/development mode everything works correctly. It gives me the error message with the correct file and line stack. I have used this data to save it in my data base so that I can review it later and track down my issues on web. But when the site is deployed the message is fine but the error stack in jibbrish and unreadable. Is there a way that I get correct file and lines like development mode console?


问:
Full database export failing in Oracle 12C
Command executed:

```<code>expdp SHELAZ/SHELAZ full=Y directory=dpump_dir dumpfile=SHELAZ20221215.dmp logfile=logfile.log
</code>```

Facing below error:

```<code>Connected to: Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

ORA-31626: job does not exist
ORA-31633: unable to create master table "SHELAZ.SYS_EXPORT_FULL_90"
ORA-06512: at "SYS.DBMS_SYS_ERROR", line 95
ORA-06512: at "SYS.KUPV$FT", line 1048
ORA-01658: unable to create INITIAL extent for segment in tablespace SHELAZDISTDATA
</code>```

Ran: select * from dba_datapump_jobs

Results: 85 rows with State = NOT RUNNING

Body:
Command executed:

expdp SHELAZ/SHELAZ full=Y directory=dpump_dir dumpfile=SHELAZ20221215.dmp logfile=logfile.log

Facing below error:

Connected to: Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

ORA-31626: job does not exist
ORA-31633: unable to create master table "SHELAZ.SYS_EXPORT_FULL_90"
ORA-06512: at "SYS.DBMS_SYS_ERROR", line 95
ORA-06512: at "SYS.KUPV$FT", line 1048
ORA-01658: unable to create INITIAL extent for segment in tablespace SHELAZDISTDATA

Ran: select * from dba_datapump_jobs

Results: 85 rows with State = NOT RUNNING


问:
I simply want to output my Python results into CSV
I simply want to output my Python results into CSV.

The same which we achieve through this on local.

This is a sample result:

```<code>2022-12-01 , appname, resourcetype , 200 , Amazon Relational Database Service
</code>```

Here is a sample code:

```<code>
def data():

    for result_by_time in results:

        for group in result_by_time['Groups']:

            amount = group['Metrics']['UnblendedCost']['Amount']
            resource_type = 'Amazon Relational Database Service'

            print(
                result_by_time['TimePeriod']['Start'],
                ',',
                ', '.join(group['Keys'])
                    .replace("example$", "").replace("Name$", ""),
                ',',
                amount,
                ',',
                resource_type,
            )
</code>```

Body:
I simply want to output my Python results into CSV.

The same which we achieve through this on local.

This is a sample result:

2022-12-01 , appname, resourcetype , 200 , Amazon Relational Database Service

Here is a sample code:

def data():

    for result_by_time in results:

        for group in result_by_time['Groups']:

            amount = group['Metrics']['UnblendedCost']['Amount']
            resource_type = 'Amazon Relational Database Service'

            print(
                result_by_time['TimePeriod']['Start'],
                ',',
                ', '.join(group['Keys'])
                    .replace("example$", "").replace("Name$", ""),
                ',',
                amount,
                ',',
                resource_type,
            )


问:
How to use OpenCV with .Net MAUI to do a camera preview and video recording
I am currently trying to use OpenCv with .Net Maui to preview a camera and then once a button is pressed record video. I currently have it where the video will record but then the application will freeze (I suspect due to a threading issue) but no matter what I try I am unable to get the camera preview to work.</p>
```<code>using (VideoCapture capture = new VideoCapture(0))
        {
            capture.Set(VideoCaptureProperties.Fps, 30.0);
            OpenCvSharp.Size dsize = new OpenCvSharp.Size(capture.FrameWidth, capture.FrameHeight);
            //Create video writer using values defines earlier.
            using (VideoWriter writer = new VideoWriter("C:/tmp/" + tracking_num + ".avi", four, capture.Fps, dsize, true))
            using (Mat frame = new Mat())
            using (Mat color = new Mat())
            using (Mat canny = new Mat())
            using (Mat image = new Mat()) // Frame image buffer
            {
                using (Mat dst = new Mat())
                {
                    while (recording)
                    {
                        capture.Read(frame);
                        if (frame.Empty())
                            break;
                        //Display video frame as a bitmap to the Video window
                        using (Bitmap bitimg = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame))
                        {
                            using (Stream stream = new MemoryStream())
                            {
                                bitimg.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                                video_display.Source = ImageSource.FromStream(() => { return stream; });
                            }
                        }
                        //Perform write to file for this frame
                        writer.Write(frame);

                        //Magic bullet that waits before running the next frame. Needed for smooth capture
                        if (capture.Fps > 0)
                        {
                            Cv2.WaitKey((1 / (int)capture.Fps) * 1000);
                        }
                        else
                        {
                            Cv2.WaitKey(1);

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

Body:
I am currently trying to use OpenCv with .Net Maui to preview a camera and then once a button is pressed record video. I currently have it where the video will record but then the application will freeze (I suspect due to a threading issue) but no matter what I try I am unable to get the camera preview to work.

using (VideoCapture capture = new VideoCapture(0))
        {
            capture.Set(VideoCaptureProperties.Fps, 30.0);
            OpenCvSharp.Size dsize = new OpenCvSharp.Size(capture.FrameWidth, capture.FrameHeight);
            //Create video writer using values defines earlier.
            using (VideoWriter writer = new VideoWriter("C:/tmp/" + tracking_num + ".avi", four, capture.Fps, dsize, true))
            using (Mat frame = new Mat())
            using (Mat color = new Mat())
            using (Mat canny = new Mat())
            using (Mat image = new Mat()) // Frame image buffer
            {
                using (Mat dst = new Mat())
                {
                    while (recording)
                    {
                        capture.Read(frame);
                        if (frame.Empty())
                            break;
                        //Display video frame as a bitmap to the Video window
                        using (Bitmap bitimg = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame))
                        {
                            using (Stream stream = new MemoryStream())
                            {
                                bitimg.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                                video_display.Source = ImageSource.FromStream(() => { return stream; });
                            }
                        }
                        //Perform write to file for this frame
                        writer.Write(frame);

                        //Magic bullet that waits before running the next frame. Needed for smooth capture
                        if (capture.Fps > 0)
                        {
                            Cv2.WaitKey((1 / (int)capture.Fps) * 1000);
                        }
                        else
                        {
                            Cv2.WaitKey(1);

                        }
                    }
                }
            }
        }


问:
Firebase Functions - why do I still receive unhandled error message after 'response received from function'
I thought that once the response was received from a cloud function that meant that the function terminated. How and why would I still receive 'Your function was killed because it raised an unhandled error.' after the response has been sent?

Response.send is called, but the function still throws an error after. This is happening in the emulator.

```<code>RESPONSE RECEIVED FROM FUNCTION: 200, Got Current Logs
⚠  functions: Your function timed out after ~60s. To configure this timeout, see
      https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation.
⚠  Your function was killed because it raised an unhandled error.
</code>```

Also, the error doesn't take 60 seconds so I don't know why it would say that it timed out after 60 seconds.

Here is the code.

The first part is just getting an array of urls.
It then calls the getLogs function. This is where I am eventually making a request and doing some other logic, but I've deleted that for now just to simulate a resolved promise.

I'm using bluebird promises for the promise.map syntax and here is the documentation for that http://bluebirdjs.com/docs/api/promise.map.html

```<code>import * as functions from 'firebase-functions'

export const handler = (database: any, urlDate: any) => {
  const scheduleRef = database.collection('NBASchedule')

  return functions.https.onRequest(async (req, response) => {
    const Promise = require('bluebird')
    const urlList: any = []

   scheduleRef.get().then((snapshot:any) => {

    snapshot.docs.forEach((doc: any) => {
      const scheduleGame = doc.data()
      if (scheduleGame.urlString.split('_')[1] === urlDate) {
        const boxScoreUrl = scheduleGame.boxScoreURL
        urlList.push('https://' + boxScoreUrl + '/')
      }
    })

    getLogs()
   }).catch((err:any) => {
    console.log(err)
   })

    async function getLogs() {

      //Promises returned by the bluebird mapper function are awaited for and the returned promise doesn't fulfill until all mapped promises have fulfilled as well.

      await Promise.map(urlList, (url: any) => {
        return new Promise(
          (resolve: any, reject: any) => {

            setTimeout(function () {
              resolve(1 + 1)
            }, 500)
          },
          {
            concurrency: 1,
          }
        ).catch(async (err: any) => {
          console.log(err)
        })
      })
      response.send('Got Current Logs')
    }
  })
}
</code>```

Can anyone explain why I still get 'Your function was killed because it raised an unhandled error.'?

Body:
I thought that once the response was received from a cloud function that meant that the function terminated. How and why would I still receive 'Your function was killed because it raised an unhandled error.' after the response has been sent?

Response.send is called, but the function still throws an error after. This is happening in the emulator.

RESPONSE RECEIVED FROM FUNCTION: 200, Got Current Logs
⚠  functions: Your function timed out after ~60s. To configure this timeout, see
      https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation.
⚠  Your function was killed because it raised an unhandled error.

Also, the error doesn't take 60 seconds so I don't know why it would say that it timed out after 60 seconds.

Here is the code.

The first part is just getting an array of urls.
It then calls the getLogs function. This is where I am eventually making a request and doing some other logic, but I've deleted that for now just to simulate a resolved promise.

I'm using bluebird promises for the promise.map syntax and here is the documentation for that http://bluebirdjs.com/docs/api/promise.map.html

import * as functions from 'firebase-functions'

export const handler = (database: any, urlDate: any) => {
  const scheduleRef = database.collection('NBASchedule')

  return functions.https.onRequest(async (req, response) => {
    const Promise = require('bluebird')
    const urlList: any = []

   scheduleRef.get().then((snapshot:any) => {

    snapshot.docs.forEach((doc: any) => {
      const scheduleGame = doc.data()
      if (scheduleGame.urlString.split('_')[1] === urlDate) {
        const boxScoreUrl = scheduleGame.boxScoreURL
        urlList.push('https://' + boxScoreUrl + '/')
      }
    })

    getLogs()
   }).catch((err:any) => {
    console.log(err)
   })

    async function getLogs() {

      //Promises returned by the bluebird mapper function are awaited for and the returned promise doesn't fulfill until all mapped promises have fulfilled as well.

      await Promise.map(urlList, (url: any) => {
        return new Promise(
          (resolve: any, reject: any) => {

            setTimeout(function () {
              resolve(1 + 1)
            }, 500)
          },
          {
            concurrency: 1,
          }
        ).catch(async (err: any) => {
          console.log(err)
        })
      })
      response.send('Got Current Logs')
    }
  })
}

Can anyone explain why I still get 'Your function was killed because it raised an unhandled error.'?


问:
Java 11 environment specific profiling in AWS lambda
I have written AWS lambda using java 11 runtime, not the lambda snippet require to invoke external API, the APIs are different for dev, qa, uat and preprod environment.

There is no framework has been integrating, the pure Java SDK is used to write the lambda handler.

I have created environment specific properties file, dev.properties, qa.properties etc.
I tried to create the jar using maven profile like below

I have added profile section in my pom.xml

```<code><profiles>
    <profile>
        <id></id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <env></env>
        </properties>
    </profile>
    <profile>
        <id>local</id>
        <properties>
            <env>-local</env>
        </properties>
    </profile>
    <profile>
        <id>dev</id>
        <properties>
            <env>-dev</env>
        </properties>
    </profile>
    <profile>
        <id>qa</id>
        <properties>
            <env>-qa</env>
        </properties>
    </profile>
    <profile>
        <id>preprod</id>
        <properties>
            <env>-preprod</env>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <env>-prod</env>
        </properties>
    </profile>
</profiles>

<build>
    <finalName>trv-lambda</finalName>
    <filters>
        <filter>src/main/resources/application${env}.properties</filter>
    </filters>

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>*.properties</include>
            </includes>
        </resource>
    </resources>
</code>```

And then after, I used the below command

```<code>mvn -P dev clean install
</code>```

but it didn't work.

Then I tried to specify the environment variables inside AWS Lambda, but later I realized that it won't work, because I have trigger for every env, but I have single lambda to trigger for all the environment, how do I identify which profile need to pick, for single time, only single jar can be created, so I am stuck here

I want to figure out the way to achieve the profiling just like we used to did in Spring boot.

Body:
I have written AWS lambda using java 11 runtime, not the lambda snippet require to invoke external API, the APIs are different for dev, qa, uat and preprod environment.

There is no framework has been integrating, the pure Java SDK is used to write the lambda handler.

I have created environment specific properties file, dev.properties, qa.properties etc.
I tried to create the jar using maven profile like below

I have added profile section in my pom.xml

<profiles>
    <profile>
        <id></id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <env></env>
        </properties>
    </profile>
    <profile>
        <id>local</id>
        <properties>
            <env>-local</env>
        </properties>
    </profile>
    <profile>
        <id>dev</id>
        <properties>
            <env>-dev</env>
        </properties>
    </profile>
    <profile>
        <id>qa</id>
        <properties>
            <env>-qa</env>
        </properties>
    </profile>
    <profile>
        <id>preprod</id>
        <properties>
            <env>-preprod</env>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <env>-prod</env>
        </properties>
    </profile>
</profiles>

<build>
    <finalName>trv-lambda</finalName>
    <filters>
        <filter>src/main/resources/application${env}.properties</filter>
    </filters>

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>*.properties</include>
            </includes>
        </resource>
    </resources>

And then after, I used the below command

mvn -P dev clean install

but it didn't work.

Then I tried to specify the environment variables inside AWS Lambda, but later I realized that it won't work, because I have trigger for every env, but I have single lambda to trigger for all the environment, how do I identify which profile need to pick, for single time, only single jar can be created, so I am stuck here

I want to figure out the way to achieve the profiling just like we used to did in Spring boot.


问:
Adding Images using Front-end form using Forminator and ACF
i am trying to add user submission post page in the frontend and i'm using a form built in Forminator which contains Text Fields, Select fields, and image upload field, i was able to pass the inputted information from the form to the Post successfully using Advanced Custom Field plugin along with Post Data Field in forminator, the problem is when i upload an image using the form, it doesn't reflect in the image gallery.

to be more clear here is what i am trying to achieve.

This is the Forminator Fields

enter image description here

and this is post Data Field mapped Correctly to image upload field in ACF

enter image description here

and here is the ACF Field Groups

enter image description here

and that's the end result i get,

enter image description here

i did understand that Forminator Sends the images as URL, but the ACF Should expect Image ID or Attachment ID. How Can i get this Done Correctly?


问:
Not able to fetch input data in bar graph
how to take input and make a bar graph using the input in react js

was able to fetch it with static data.but was not able to do it with dynamic data.

I am a bigenner and need some guidence.


问:
Can I use ```this``` at advantage for writing conditions for if statements?
I'd like to condition the hovering of buttons to perform exclusive tasks respective to each button. The if statement does not work as I intended, it still prints mouseover events for all buttons when I want it to print on condition that it's the first button. I will later write separate tasks under conditions for the other buttons.

var items = document.getElementsByClassName('play');
var span = document.getElementById('span');

function clearSpan() {
  span.innerHTML = "";
}

// consolidation attempt for hover on
for (var i = 0; i < items.length; i++) {
  items[i].addEventListener('mouseover', printHoverOn);
}

// consolidation attempt for hover off
for (var i = 0; i < items.length; i++) {
  items[i].addEventListener('mouseout', printHoverOff);
}

function printHoverOn(e) {
  cursor = this.id;
  if (cursor === 'firstButton') {
    span.innerHTML = "January";
    console.log(this.id + " is hovered");
  } else if (cursor === 'secButton') {
    span.innerHTML = "February";
    console.log(this.id + " is hovered");
  } else {
    console.log("nothing to print");
  }

}

function printHoverOff(e) {
  console.log(this.id + " was hovered");
  clearSpan();
  cursor = null;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="firstButton" class="play"></button>
<button id="secButton" class="play"></button>
<button id="thirdButton" class="play"></button>
<button id="fourthButton" class="play"></button>
<button id="fifthButton" class="play"></button>
<button id="sixthButton" class="play"></button>
<button id="seventhButton" class="play"></button>
<span id="span">Change Me</span></code>```

Does anyone have ideas to help enhance my logic here? Thank you

I wrote longer script with an eventlistener for each button but I wish to shorten the code and, in process, began using the script I have now.

Body:
I'd like to condition the hovering of buttons to perform exclusive tasks respective to each button. The if statement does not work as I intended, it still prints mouseover events for all buttons when I want it to print on condition that it's the first button. I will later write separate tasks under conditions for the other buttons.

var items = document.getElementsByClassName('play');
var span = document.getElementById('span');

function clearSpan() {
  span.innerHTML = "";
}

// consolidation attempt for hover on
for (var i = 0; i < items.length; i++) {
  items[i].addEventListener('mouseover', printHoverOn);
}

// consolidation attempt for hover off
for (var i = 0; i < items.length; i++) {
  items[i].addEventListener('mouseout', printHoverOff);
}

function printHoverOn(e) {
  cursor = this.id;
  if (cursor === 'firstButton') {
    span.innerHTML = "January";
    console.log(this.id + " is hovered");
  } else if (cursor === 'secButton') {
    span.innerHTML = "February";
    console.log(this.id + " is hovered");
  } else {
    console.log("nothing to print");
  }

}

function printHoverOff(e) {
  console.log(this.id + " was hovered");
  clearSpan();
  cursor = null;
}

<button id="firstButton" class="play"></button>
<button id="secButton" class="play"></button>
<button id="thirdButton" class="play"></button>
<button id="fourthButton" class="play"></button>
<button id="fifthButton" class="play"></button>
<button id="sixthButton" class="play"></button>
<button id="seventhButton" class="play"></button>
Change Me

Does anyone have ideas to help enhance my logic here? Thank you

I wrote longer script with an eventlistener for each button but I wish to shorten the code and, in process, began using the script I have now.


问:
Kalman filter and state space model
As a beginner to modelling systems, it is a little unclear to me.

A state space model can be described as:

x' = Ax+Bu

In a kalman filter, the state will be described as:

x = Fx+Bu

Is A and F the same ?

I am trying to implement a kalman filter in python on a zero-order system for simplicity.
The best result I get is when F is [1] - does this make sense ?

Assuming I calculated my state space model parameters correctly, F should be bigger than 1.

Can anyone try to explain the theory ?

Title: Kalman filter and state space model


问:
Database hosts close connection after some time of inactivity
Currently I use supabase PostgreSQL hosting for my site and node-postgres to make queries. After some time (about 5-7 min) of inactivity connection is terminated and it's impossible to get/send data to DB. It is not node-Postgres problem, because connection has same behaviour even if you make queries from psql terminal.

I even tried to change hosting provider, but second provider (bit.io) had the same problem.

I came up with idea to make interceptor function that catches connection_error and makes request again. But I don't think that it is the most efficient approach.

How to solve this problem?