问:
Waiting for an external response without consuming resources
I have a simple python program that needs to apply a function to circles based on their radius. My issue is, I need to fetch the radius from a third-party API, which may take up to several hours to send me the radius sizes, as a csv file for instance.

To be clearer:

class Circle():
    def __init__(self, id):
        self.id = id
        self.radius = None

def fetch_radius(circle):
    ''' call an API and retrieve radius based on
        the circle id.
    '''
    radius = fetch_from_api(circle.id) # takes hour to return
    circle.radius = radius

def main():
    circle = Circle(id=2)
    fetch_radius(circle.id)
```

This design seems flawed, because my program and objects hang for hours waiting for an external signal, and consume resources.

How can I improve my design ?

Edit : I thought of pickling the object and closing the program waiting for the answer, but I'm not convinced. Yehven also talked about asyncio. I add both keywords.

Body:
I have a simple python program that needs to apply a function to circles based on their radius. My issue is, I need to fetch the radius from a third-party API, which may take up to several hours to send me the radius sizes, as a csv file for instance.

To be clearer:

class Circle():
    def __init__(self, id):
        self.id = id
        self.radius = None

def fetch_radius(circle):
    ''' call an API and retrieve radius based on
        the circle id.
    '''
    radius = fetch_from_api(circle.id) # takes hour to return
    circle.radius = radius

def main():
    circle = Circle(id=2)
    fetch_radius(circle.id)

This design seems flawed, because my program and objects hang for hours waiting for an external signal, and consume resources.

How can I improve my design ?

Edit : I thought of pickling the object and closing the program waiting for the answer, but I'm not convinced. Yehven also talked about asyncio. I add both keywords.


来源: stackexchange

问:
In the NLP with Pre-Trained project, what the difference of direct installation of libraries and manual installation?
Currently, I am working on this stuff:

NLP

Transformers Pre-trained models (especially the Bert family)

on google colab

Sometimes, When I clone projects from GitHub, I see that the programmers do not use the direct installation from Huggingface Repository, like:

```<code>!pip install transformers
import transformers
</code>```

but instead,  they downloaded the installation files of these libraries manually in the project.

my questions are:

why this approach?

Is this better than installing directly?

How can I do the same in my project?

ContentLicense: CC BY-SA 4.0

Body:
Currently, I am working on this stuff:

NLP

Transformers Pre-trained models (especially the Bert family)

on google colab

Sometimes, When I clone projects from GitHub, I see that the programmers do not use the direct installation from Huggingface Repository, like:

!pip install transformers
import transformers

but instead,  they downloaded the installation files of these libraries manually in the project.

my questions are:

why this approach?

Is this better than installing directly?

How can I do the same in my project?


问:
cross compile openssl-fips-2.0.16 for Linux_aarch64 on Linux_x86_64
Looking to cross compile openssl-fips-2.0.16 for Linux_aarch64 on Linux_x86_64.

I am able to compile openssl-fips-2.0.16 on Linux_aarch64.

I want to use Linux_x86_64 to compile.

Any leads will help me.

Thanks,
Nagaraj


问:
Webpack parallelism feature not actually work in parallel
I implemented Webpack build for multiple configuration work in parallel. the feature gets multiple config bundles, just as described in Webpack docs here. However, the build is not spreading on multiple CPUs, it runs 2+ parallel builds but it multiple the time of build by the number of parallel configurations I set. Also, The memory also multiplied by the number of builds.

does there is any way in Webpack to build multiple on multiple CPUs and not just one, so the build time will shrink?


问:
Why input type id is number, but after graphql it`s returning as an object
so i have model/type user:
prisma:

```<code>model User {
  id       Int    @id @default(autoincrement())
  email    String @unique
  nickname String
  password String
}

</code>```

graphql typedefs:

```<code>  type User {
    id: Int!
    email: String!
    nickname: String!
    password: String!
  }
</code>```

and types.ts:

```<code>export type User = {
  id: number;
  nickname: string;
  email: string;
  password: string;
};
</code>```

and i`m making query to find specific user by his id:

```<code>    async getUser(_: any, id: number): Promise<User | null> {
      const user = await prisma.user.findUnique({
        where: { id },
      });
      return user;
    },
</code>```

but when i`m trying to findunique by id provided in graphql i get error about id type is json and not an integer

my query:
graphl query
and parsed variables:
graphql variable

error: error

i checked user id types in all files,
i checked id type in query and it`s object.
i tried to parseInt id, not working

Body:
so i have model/type user:
prisma:

model User {
  id       Int    @id @default(autoincrement())
  email    String @unique
  nickname String
  password String
}

graphql typedefs:

  type User {
    id: Int!
    email: String!
    nickname: String!
    password: String!
  }

and types.ts:

export type User = {
  id: number;
  nickname: string;
  email: string;
  password: string;
};

and i`m making query to find specific user by his id:

    async getUser(_: any, id: number): Promise<User | null> {
      const user = await prisma.user.findUnique({
        where: { id },
      });
      return user;
    },

but when i`m trying to findunique by id provided in graphql i get error about id type is json and not an integer

my query:
graphl query
and parsed variables:
graphql variable

error: error

i checked user id types in all files,
i checked id type in query and it`s object.
i tried to parseInt id, not working


问:
change specific word page variable in docxtpl template (python)
How I go to next word page in docxtpl? I have template called example.docx. I gave same variables to all pages. I'm going to change variables from specific page with while loop and random.

I found some examples with docx module.

```<code>document = Document()
for section in document.sections:
    print(section.start_type)
</code>```

but it didn't work for docxtemplate

```<code>doc = DocxTemplate(document_path)
</code>```

So anyone know how to go next page with docxtpl?

Body:
How I go to next word page in docxtpl? I have template called example.docx. I gave same variables to all pages. I'm going to change variables from specific page with while loop and random.

I found some examples with docx module.

document = Document()
for section in document.sections:
    print(section.start_type)

but it didn't work for docxtemplate

doc = DocxTemplate(document_path)

So anyone know how to go next page with docxtpl?


问:
Why does shelve module create database with .db extension?
I run the code using the shelve module. I expect to get 3 files as a database: .dir, .dat and .bak. Instead, I have a file with the .db extension. I can't read the created database.

I work on the manaconda environment on a apple m1 chip,
rdkit 2022.03.5, python == 3.9.13.

If someone has encountered a similar problem, what could be the reason that shelve creates a database with the .db extension?

I ran the next simplest code:

import shelve
db = shelve.open('dbs/test', flag='c', protocol=4)
db['a'] = 'A'
db.close()
```
<p>And the output file is:
dbs/test.db</p>
<p>The problem starts when I am working with the created db.
For example, with the simplest database (test.db) I can extract the keys by doing next:</p>
```db = shelve.open('dbs/test', flag='r', protocol=4)
names = db.keys()
print(tuple(names))
```
<p>BUT but the same code run on a bigger database (with the strange for shelve .db extension) that I use for work, next error message appears:</p>
```SystemError                               Traceback (most recent call last)
Cell In [48], line 1
----> 1 tuple(names)

File ~/miniconda3/envs/rd22/lib/python3.9/_collections_abc.py:826, in KeysView.__iter__(self)
    825 def __iter__(self):
--> 826     yield from self._mapping

File ~/miniconda3/envs/rd22/lib/python3.9/shelve.py:95, in Shelf.__iter__(self)
     94 def __iter__(self):
---> 95     for k in self.dict.keys():
     96         yield k.decode(self.keyencoding)

SystemError: Negative size passed to PyBytes_FromStringAndSize
```

I did not have any similar problems when I worked with the usual DBM database format

Body:
I run the code using the shelve module. I expect to get 3 files as a database: .dir, .dat and .bak. Instead, I have a file with the .db extension. I can't read the created database.

I work on the manaconda environment on a apple m1 chip,
rdkit 2022.03.5, python == 3.9.13.

If someone has encountered a similar problem, what could be the reason that shelve creates a database with the .db extension?

I ran the next simplest code:

import shelve
db = shelve.open('dbs/test', flag='c', protocol=4)
db['a'] = 'A'
db.close()

And the output file is:
dbs/test.db

The problem starts when I am working with the created db.
For example, with the simplest database (test.db) I can extract the keys by doing next:

db = shelve.open('dbs/test', flag='r', protocol=4)
names = db.keys()
print(tuple(names))

BUT but the same code run on a bigger database (with the strange for shelve .db extension) that I use for work, next error message appears:

SystemError                               Traceback (most recent call last)
Cell In [48], line 1
----> 1 tuple(names)

File ~/miniconda3/envs/rd22/lib/python3.9/_collections_abc.py:826, in KeysView.__iter__(self)
    825 def __iter__(self):
--> 826     yield from self._mapping

File ~/miniconda3/envs/rd22/lib/python3.9/shelve.py:95, in Shelf.__iter__(self)
     94 def __iter__(self):
---> 95     for k in self.dict.keys():
     96         yield k.decode(self.keyencoding)

SystemError: Negative size passed to PyBytes_FromStringAndSize

I did not have any similar problems when I worked with the usual DBM database format


问:
Connect to Azure MongoDB using Flutter / Dart
I am trying to connect to Microsoft Azure MongoDB from flutter/Dart and trying to establish a connect to it using mongo_dart (https://pub.dev/packages/mongo_dart) package.

The connection string to pass to Azure is as follows:
mongodb://username:password@host:port/[database]?ssl=true
Ex. mongodb://contoso123:0Fc3IolnL12312asdfawejunASDF@asdfYXX2t8a97kghVcUzcDv98hawelufhawefafnoQRGwNj2nMPL1Y9qsIr9Srdw==@contoso123.documents.azure.com:10255/mydatabase?ssl=true

Source: https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/connect-account

Code tried:

import 'package:mongo_dart/mongo_dart.dart';

// URL IS a Dummy one

final url ="mongodb://examplebdname:examplekey==@exaplebdname.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@exampledbname@";

main() async {

Db _db = new Db(url);

await _db.open(secure: true);

print('connected');

}

________________________________________________________

Error:

Unhandled exception:

MongoDart Error: Expected type binData but found string.

#0      ConnectionManager.open

package:mongo_dart/…/network/connection_manager.dart:148

<asynchronous suspension>

#1      Db.open

package:mongo_dart/…/database/db.dart:481

<asynchronous suspension>

#2      main

example\example.dart:8

<asynchronous suspension>

Exited (255)

Currently my entire app is on firebase and it was a breeze, but connecting to Azure as they don't have native support for Flutter is quite challenging.

I only want to connect to Azure DB.

If anyone has experience to connect to the DB. I would be grateful.

Any help or advice is appreciated.


问:
Airflow to export big query table data to Google sheet?
Does anyone know if it's possible to take the contents of a bigquey table and append that data to a Google sheet, using airflow. I have looked through the docs and can only find this: https://airflow.apache.org/docs/apache-airflow-providers-google/stable/operators/transfer/sql_to_sheets.html

Firstly, I'm not sure what a database_conn_id is? And I'm not sure if this supports any Google sheets validations such as drop downs via data validation or append functions.


问:
How to use UIEditMenu with WKWebView in iOS 16?
In iOS 16 UIMenuController is deprecated. Instead, we should use UIEditMenuInteraction. In the WWDC notes I found simple example how to use editMenu in UITextView with native gestures:

```<code>@available(iOS 16.0, *)
class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var myTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        myTextView.delegate = self
    }

    func textView(_ textView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? {

        var additionalActions: [UIMenuElement] = []

        if textView.selectedRange.length > 0 {
            let highlightAction = [UIAction(title: "Highlight") { _ in
                print("Highlight")
            }]
            additionalActions.append(contentsOf:highlightAction)
        }

        let selectAction = [UIAction(title: "Select") { _ in
            print("Select")
        }]
        additionalActions.append(contentsOf:selectAction)

        return UIMenu(children: additionalActions)
    }

}
</code>```

But how to use editMenu for text selections in WKWebView with native gestures?

I started experimenting with WKWebView and wrote this code:

```<code>@available(iOS 16.0, *)
class MenuViewController: UIViewController, UIEditMenuInteractionDelegate, WKNavigationDelegate {

    @IBOutlet weak var myWebView: WKWebView!
    var editMenuInteraction: UIEditMenuInteraction?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupEditMenuInteraction()
        setupWKWebView()
    }

    func setupEditMenuInteraction() {

        editMenuInteraction = UIEditMenuInteraction(delegate: self)
        myWebView.addInteraction(editMenuInteraction!)

        let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
        myWebView.addGestureRecognizer(longPressGestureRecognizer)
    }

    @objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
        guard gestureRecognizer.state == .began else { return }

        let configuration = UIEditMenuConfiguration(
            identifier: "textViewEdit",
            sourcePoint: gestureRecognizer.location(in: myWebView)
        )

        editMenuInteraction?.presentEditMenu(with: configuration)
    }

    func editMenuInteraction(_ interaction: UIEditMenuInteraction, menuFor configuration: UIEditMenuConfiguration, suggestedActions: [UIMenuElement]) -> UIMenu? {

        var actions = suggestedActions

        let customMenu = UIMenu(title: "", options: .displayInline, children: [
            UIAction(title: "menuItem1") { _ in
                print("menuItem1")
            },
            UIAction(title: "menuItem2") { _ in
                print("menuItem2")
            },
            UIAction(title: "menuItem3") { _ in
                print("menuItem3")
            }
        ])

        actions.append(customMenu)

        return UIMenu(children: customMenu.children)
    }

}
</code>```

This code works fine but the problem is that UILongPressGestureRecognizer is not what I need. I need to show editMenu after text is selected like native select gesture. What type of gesture should I use instead of UILongPressGestureRecognizer? Because now in my WKWebView I call editMenu with native text select gesture and my editMenu with long tap gesture. It's not very good solution.

Body:
In iOS 16 UIMenuController is deprecated. Instead, we should use UIEditMenuInteraction. In the WWDC notes I found simple example how to use editMenu in UITextView with native gestures:

@available(iOS 16.0, *)
class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var myTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        myTextView.delegate = self
    }

    func textView(_ textView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? {

        var additionalActions: [UIMenuElement] = []

        if textView.selectedRange.length > 0 {
            let highlightAction = [UIAction(title: "Highlight") { _ in
                print("Highlight")
            }]
            additionalActions.append(contentsOf:highlightAction)
        }

        let selectAction = [UIAction(title: "Select") { _ in
            print("Select")
        }]
        additionalActions.append(contentsOf:selectAction)

        return UIMenu(children: additionalActions)
    }

}

But how to use editMenu for text selections in WKWebView with native gestures?

I started experimenting with WKWebView and wrote this code:

@available(iOS 16.0, *)
class MenuViewController: UIViewController, UIEditMenuInteractionDelegate, WKNavigationDelegate {

    @IBOutlet weak var myWebView: WKWebView!
    var editMenuInteraction: UIEditMenuInteraction?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupEditMenuInteraction()
        setupWKWebView()
    }

    func setupEditMenuInteraction() {

        editMenuInteraction = UIEditMenuInteraction(delegate: self)
        myWebView.addInteraction(editMenuInteraction!)

        let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
        myWebView.addGestureRecognizer(longPressGestureRecognizer)
    }

    @objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
        guard gestureRecognizer.state == .began else { return }

        let configuration = UIEditMenuConfiguration(
            identifier: "textViewEdit",
            sourcePoint: gestureRecognizer.location(in: myWebView)
        )

        editMenuInteraction?.presentEditMenu(with: configuration)
    }

    func editMenuInteraction(_ interaction: UIEditMenuInteraction, menuFor configuration: UIEditMenuConfiguration, suggestedActions: [UIMenuElement]) -> UIMenu? {

        var actions = suggestedActions

        let customMenu = UIMenu(title: "", options: .displayInline, children: [
            UIAction(title: "menuItem1") { _ in
                print("menuItem1")
            },
            UIAction(title: "menuItem2") { _ in
                print("menuItem2")
            },
            UIAction(title: "menuItem3") { _ in
                print("menuItem3")
            }
        ])

        actions.append(customMenu)

        return UIMenu(children: customMenu.children)
    }

}

This code works fine but the problem is that UILongPressGestureRecognizer is not what I need. I need to show editMenu after text is selected like native select gesture. What type of gesture should I use instead of UILongPressGestureRecognizer? Because now in my WKWebView I call editMenu with native text select gesture and my editMenu with long tap gesture. It's not very good solution.


问:
The EC2 user_data script dos not run
Hi i'm stuck with my user_data script because the script is no executed by the ec2 and i don't really understand why

On terraform i have

```<code>resource "aws_instance" "ec2_b" {
    ami = "ami-0c2b8ca1dad447f8a"
    instance_type = "t2.micro"
    subnet_id = aws_subnet.private_b.id
    vpc_security_group_ids = [aws_security_group.main.id]

    tags = {
      Name = "my-ec2-b"
    }

    key_name = "vockey"
    user_data = file("./user_data.sh")
}
</code>```

with the following script

#!/bin/bash
sudo echo "test" > /home/ec2-user/test.txt
sudo yum update -y
sudo yum install httpd -y
sudo systemctl start httpd
sudo systemctl enable httpd
sudo echo "Hello, World" | sudo tee /var/www/html/index.html
```

On aws console i can see that the script is there

However if i try to go on my ec2 with ssh i can see that the script has not been executed

Title: The EC2 user_data script dos not run

Body:
Hi i'm stuck with my user_data script because the script is no executed by the ec2 and i don't really understand why

On terraform i have

resource "aws_instance" "ec2_b" {
    ami = "ami-0c2b8ca1dad447f8a"
    instance_type = "t2.micro"
    subnet_id = aws_subnet.private_b.id
    vpc_security_group_ids = [aws_security_group.main.id]

    tags = {
      Name = "my-ec2-b"
    }

    key_name = "vockey"
    user_data = file("./user_data.sh")
}

with the following script

#!/bin/bash
sudo echo "test" > /home/ec2-user/test.txt
sudo yum update -y
sudo yum install httpd -y
sudo systemctl start httpd
sudo systemctl enable httpd
sudo echo "Hello, World" | sudo tee /var/www/html/index.html

On aws console i can see that the script is there

However if i try to go on my ec2 with ssh i can see that the script has not been executed


问:
Linux rx and tx stats in /proc/tty/driver/serial file is not working
I am trying to echo some string to /dev/ttyS0 and the rx and tx stats in /proc/tty/driver/serial remain 0.
If I change the irq of ttyS0 to 0 and then echo some string to ttyS0, the stats are changing according to the length of the string.
Would anyone be able to help me with this?

output of setserial -g /dev/ttyS[0123]

```<code>/dev/ttyS0, UART: 16550A, Port: 0x03f8, IRQ: 11
/dev/ttyS1, UART: 16550A, Port: 0x02f8, IRQ: 10
/dev/ttyS2, UART: unknown, Port: 0x03e8, IRQ: 4
/dev/ttyS3, UART: unknown, Port: 0x02e8, IRQ: 3
</code>```

output of stty -F /dev/ttyS0 -a

```<code>speed 115200 baud; rows 24; columns 80; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S;
susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; discard = ^O; min = 1; time = 0;
-parenb -parodd -cmspar cs8 hupcl -cstopb cread clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
-isig -icanon -iexten -echo -echoe -echok -echonl -noflsh -xcase -tostop -echoprt -echoctl -echoke -flusho -extproc
</code>```

out put of cat /proc/interrupts for irq 11 with 16 cpu.

```<code>11:          0          0          0          0          0          0          0          0          0          0          0          0          0          0          0          0   IO-APIC  11-edge      ttyS0
</code>```

output of cat /proc/tty/driver/serial:

```<code>0: uart:16550A port:000003F8 irq:11 tx:228 rx:0 RTS|DTR|DSR|CD|RI
1: uart:16550A port:000002F8 irq:10 tx:0 rx:0 CTS|DSR|CD|RI
2: uart:unknown port:000003E8 irq:4
3: uart:unknown port:000002E8 irq:3
</code>```

As i said I have tried to change thee irq to 0 and it worked. But what is wrong with irq 11. There is no deviced registered for irq 11 in /proc/interrupts except ttyS0.

Body:
I am trying to echo some string to /dev/ttyS0 and the rx and tx stats in /proc/tty/driver/serial remain 0.
If I change the irq of ttyS0 to 0 and then echo some string to ttyS0, the stats are changing according to the length of the string.
Would anyone be able to help me with this?

output of setserial -g /dev/ttyS[0123]

/dev/ttyS0, UART: 16550A, Port: 0x03f8, IRQ: 11
/dev/ttyS1, UART: 16550A, Port: 0x02f8, IRQ: 10
/dev/ttyS2, UART: unknown, Port: 0x03e8, IRQ: 4
/dev/ttyS3, UART: unknown, Port: 0x02e8, IRQ: 3

output of stty -F /dev/ttyS0 -a

speed 115200 baud; rows 24; columns 80; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S;
susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; discard = ^O; min = 1; time = 0;
-parenb -parodd -cmspar cs8 hupcl -cstopb cread clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
-isig -icanon -iexten -echo -echoe -echok -echonl -noflsh -xcase -tostop -echoprt -echoctl -echoke -flusho -extproc

out put of cat /proc/interrupts for irq 11 with 16 cpu.

11:          0          0          0          0          0          0          0          0          0          0          0          0          0          0          0          0   IO-APIC  11-edge      ttyS0

output of cat /proc/tty/driver/serial:

0: uart:16550A port:000003F8 irq:11 tx:228 rx:0 RTS|DTR|DSR|CD|RI
1: uart:16550A port:000002F8 irq:10 tx:0 rx:0 CTS|DSR|CD|RI
2: uart:unknown port:000003E8 irq:4
3: uart:unknown port:000002E8 irq:3

As i said I have tried to change thee irq to 0 and it worked. But what is wrong with irq 11. There is no deviced registered for irq 11 in /proc/interrupts except ttyS0.


问:
Unity3D - Is there a XRSocketInteractor alternative in SteamVR plugin?
Is there a snapping mechanism in unity SteamVR plugin?

I've been wanted to grab a object from a desk, for example, and hoping a snap zone would show up and let my object attach into,

plus, i would need a detection mechanism to detect the object in place, but i'm quite stuck on the first step

Using Itempackage won't let me leave item prefab blank
There's no detection mechanism for itempackages

Should i use a OnTriggerEnter() or related to detect a object that goes into it?
Any help would be appreciated.


问:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist
I am trying to pass message from background to content script but it is showing error

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

I have tried too many solutions but nothing work. Here actually I am trying to create side panel in chrome extension for that I am passing message background to content script. My content script file is side-panel.js

background.js

```<code>chrome.action.onClicked.addListener((tab) => {
  chrome.tabs.sendMessage(tab.id, "toggle");
  console.log("message sent");
});

</code>```

content (side-panel.js)

```<code>console.log("side-panel script loaded");

chrome.runtime.onMessage.addListener(function (msg, sender) {
  if (msg == "toggle") {
    console.log("message received");
    toggle();
  }
});

var iframe = document.createElement("iframe");
iframe.style.background = "green";
iframe.style.height = "100%";
iframe.style.width = "0px";
iframe.style.position = "fixed";
iframe.style.top = "0px";
iframe.style.right = "0px";
iframe.style.zIndex = "9000000000000000000";
iframe.style.border = "0px";
iframe.src = chrome.runtime.getURL("popup.html");

document.body.appendChild(iframe);

function toggle() {
  if (iframe.style.width == "0px") {
    iframe.style.width = "400px";
  } else {
    iframe.style.width = "0px";
  }
}

</code>```

manifest.json

```<code>{
    "version": "1.0",
    "manifest_version": 3,
    "name": "test",
    "key": "ahhechlhmhicciahdcegooimkdnhbphh",
    "background": {
        "service_worker": "background.js"
    },
    "action": {},
    "content_scripts": [
        {
            "matches": [
                "https://*/*",
                "http://*/*"
            ],
            "js": [
                "side-panel.js"
            ]
        }
    ],
    "web_accessible_resources": [
        {
            "resources": [
                "popup.html"
            ],
            "matches": [
                "https://*/*",
                "http://*/*"
            ],
            "extension_ids": [
                "ahhechlhmhicciahdcegooimkdnhbphh"
            ]
        }
    ]
}
</code>```

Body:
I am trying to pass message from background to content script but it is showing error

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

I have tried too many solutions but nothing work. Here actually I am trying to create side panel in chrome extension for that I am passing message background to content script. My content script file is side-panel.js

background.js

chrome.action.onClicked.addListener((tab) => {
  chrome.tabs.sendMessage(tab.id, "toggle");
  console.log("message sent");
});

content (side-panel.js)

console.log("side-panel script loaded");

chrome.runtime.onMessage.addListener(function (msg, sender) {
  if (msg == "toggle") {
    console.log("message received");
    toggle();
  }
});

var iframe = document.createElement("iframe");
iframe.style.background = "green";
iframe.style.height = "100%";
iframe.style.width = "0px";
iframe.style.position = "fixed";
iframe.style.top = "0px";
iframe.style.right = "0px";
iframe.style.zIndex = "9000000000000000000";
iframe.style.border = "0px";
iframe.src = chrome.runtime.getURL("popup.html");

document.body.appendChild(iframe);

function toggle() {
  if (iframe.style.width == "0px") {
    iframe.style.width = "400px";
  } else {
    iframe.style.width = "0px";
  }
}

manifest.json

{
    "version": "1.0",
    "manifest_version": 3,
    "name": "test",
    "key": "ahhechlhmhicciahdcegooimkdnhbphh",
    "background": {
        "service_worker": "background.js"
    },
    "action": {},
    "content_scripts": [
        {
            "matches": [
                "https://*/*",
                "http://*/*"
            ],
            "js": [
                "side-panel.js"
            ]
        }
    ],
    "web_accessible_resources": [
        {
            "resources": [
                "popup.html"
            ],
            "matches": [
                "https://*/*",
                "http://*/*"
            ],
            "extension_ids": [
                "ahhechlhmhicciahdcegooimkdnhbphh"
            ]
        }
    ]
}


问:
Pino (pinojs) only logging some HTTP request
I am trying to add logging with pino to an existing node.js web application, that uses express.js and Postgresql. However, some HTTP post request are not being logged. It seems to only happen with HTTP post request responding with a redirect. It also only happens then requesting by Safari. The problem does not occur then using Chrome or curl.

I am produced a minimal example here under, that reproduces the problem. As in my main project it does reproduce the problem when using Safari on my laptop, but not when using Chrome or curl. If I remove the usage of connect-pg-simple the problem disappears.

No error message what so ever is given.

import { default as express } from 'express'
import { default as pinoHttp } from 'pino-http'
import { default as session } from 'express-session';
import { default as sessionStore } from 'connect-pg-simple';

import { default as pg } from 'pg';
const Pool = pg.Pool
const pool = new Pool()

const reqLogger = pinoHttp({
    level: 'info',
    enabled: true
})

const app = express()

app.use(session({
    secret: 'secret',
    name: 'sessionId',
    resave: false,
    rolling: true,
    saveUninitialized: true,
    store: new (sessionStore(session))({
        pool: pool
    }),
    cookie: {
        secure: 'auto',
        maxAge: 30 * 24 * 60 * 60 * 1000
    }
}))

app.use(reqLogger)

app.get('/', (req, res, next) => {
    const html = `
        <form method="POST" action="/">

                Username
                <input name="username" type="text" id="floatingInput">

                Password
                <input name="password" type="password" id="floatingPassword">

            <button type="submit">Log in</button>
        </form>`
    res.send(html)
})

app.post('/', (req, res, next) => {
    res.redirect('/')
})

app.listen(8081, () => {
    console.log('Server running')
})
```


问:
Adding user registration to a DocC Tutorial with assessment
I've created an interactive Swift DocC Tutorial with multiple choice assessments. Now I want to add a user registration so that I can keep tab of who has completed the tutorial. How might I do this? Specifically:

How do I make sure they answer all the assessments?

How can I add a user registration to the tutorial?

Appreciate very much the inputs. Thanks.


问:
Drag an object from one viewController to other viewController
I am just creating a sample split view based iPad app where i am just displaying a list of sample object (e.g triangle,circle )in the left side view and right now i am trying to drag them to right hand side detail view.

So if i have 2 view controller (VC-A,VC-B) then how can i drag an object from View controller A to view controller B.

ContentLicense: CC BY-SA 3.0


问:
Setting 2 ranges in 2 different sheets gives "application-defined or object defined error"
i've been trying to make a vba that would email a range of values to a range of recipients but it gives a "application-defined or object defined error" on setting their ranges as shown in below code

i've noticed that it gives that error when the active sheet isn't the one im trying to set a range in
`

```<code>Sub EmailRange()
'declaring vars
Dim OutApp As Object
Dim OutMail As Object
Dim Count_R, Count_C As Integer
Dim Pop As Range
Dim Str1, Str2 As String
Dim r As Range
Dim Rlist As Range

'setting vars
Set Rlist = Sheets("Market").Range("A6", Range("A6").End(xlDown))

For Each r In Rlist
    If r <> "" Then
Set OutApp = CreateObject("Outlook.application")
Set OutMail = OutApp.createitem(0)

Count_R = WorksheetFunction.CountA(Range("A1", Range("A1").End(xlDown)))
Count_C = WorksheetFunction.CountA(Range("A1", Range("A1").End(xlToRight)))

Set Pop = Sheets("Work").Range(Cells(1, 1), Cells(Count_R, Count_C))
'Body Mail
Str1 = "<Body style = font-size:12pt;font-family:Helvetica>" & _
"Dear Partner,<br><br>Kindly find the below.<br>"

Str2 = "<br>Kind Regards,<br>Test"

On Error Resume Next
    With OutMail
        .to = r
        .cc = ""
        .bcc = ""
        .Subject = "Testing " & r
        .display
        .htmlbody = Str1 & RangetoHTML(Pop) & Str2 & .htmlbody

    End With
    On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing
Else: MsgBox "This is fun"
End If

Next r

End Sub

</code>```

the probelm is with lineSet Rlist = Sheets("Market").Range("A6", Range("A6").End(xlDown))andSet Pop = Sheets("Work").Range(Cells(1, 1), Cells(Count_R, Count_C))`

Body:
i've been trying to make a vba that would email a range of values to a range of recipients but it gives a "application-defined or object defined error" on setting their ranges as shown in below code

i've noticed that it gives that error when the active sheet isn't the one im trying to set a range in
`

Sub EmailRange()
'declaring vars
Dim OutApp As Object
Dim OutMail As Object
Dim Count_R, Count_C As Integer
Dim Pop As Range
Dim Str1, Str2 As String
Dim r As Range
Dim Rlist As Range

'setting vars
Set Rlist = Sheets("Market").Range("A6", Range("A6").End(xlDown))

For Each r In Rlist
    If r <> "" Then
Set OutApp = CreateObject("Outlook.application")
Set OutMail = OutApp.createitem(0)

Count_R = WorksheetFunction.CountA(Range("A1", Range("A1").End(xlDown)))
Count_C = WorksheetFunction.CountA(Range("A1", Range("A1").End(xlToRight)))

Set Pop = Sheets("Work").Range(Cells(1, 1), Cells(Count_R, Count_C))
'Body Mail
Str1 = "" & _
"Dear Partner,

Kindly find the below.
"

Str2 = "
Kind Regards,
Test"

On Error Resume Next
    With OutMail
        .to = r
        .cc = ""
        .bcc = ""
        .Subject = "Testing " & r
        .display
        .htmlbody = Str1 & RangetoHTML(Pop) & Str2 & .htmlbody

    End With
    On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing
Else: MsgBox "This is fun"
End If

Next r

End Sub

the probelm is with lineSet Rlist = Sheets("Market").Range("A6", Range("A6").End(xlDown))andSet Pop = Sheets("Work").Range(Cells(1, 1), Cells(Count_R, Count_C))`


问:
Does kue-dashboard require additional steps to run via VSC on a windows machine?
I am trying to delay some email notification processes on my NodeJS server using Kue. Now, I have set up kue successfully. Here's the config file:

```<code>const kue = require('kue');
const queue = kue.createQueue();
module.exports = queue;
</code>```

The queue is running and the emails are delayed as well. But I am unable to run the kue-dashboard for another VS-code window. The following command:

```<code>./node_modules/kue/bin/kue-dashboard
</code>```

this is the error that i run into:

```<code>PS B:\Files\nodews\rescode> ./node_modules/kue/bin/kue-dashboard
ResourceUnavailable: Program 'kue-dashboard' failed to run: An error occurred trying to start process 'B:\Files\nodews\rescode\node_modules\kue\bin\kue-dashboard' with working directory 'B:\Files\nodews\rescode'. No application is associated with the specified file for this operation.At line:1 char:1
+ ./node_modules/kue/bin/kue-dashboard
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.
</code>```

I am very new to this so unsure about how to go about resolving this. I have redis-server and redis-cli running as suggested by Kue: https://automattic.github.io/kue/, but the program just does not run :).
Suggestions would be welcome, sorry if this is too basic to inquire about.

Body:
I am trying to delay some email notification processes on my NodeJS server using Kue. Now, I have set up kue successfully. Here's the config file:

const kue = require('kue');
const queue = kue.createQueue();
module.exports = queue;

The queue is running and the emails are delayed as well. But I am unable to run the kue-dashboard for another VS-code window. The following command:

./node_modules/kue/bin/kue-dashboard

this is the error that i run into:

PS B:\Files\nodews\rescode> ./node_modules/kue/bin/kue-dashboard
ResourceUnavailable: Program 'kue-dashboard' failed to run: An error occurred trying to start process 'B:\Files\nodews\rescode\node_modules\kue\bin\kue-dashboard' with working directory 'B:\Files\nodews\rescode'. No application is associated with the specified file for this operation.At line:1 char:1
+ ./node_modules/kue/bin/kue-dashboard
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.

I am very new to this so unsure about how to go about resolving this. I have redis-server and redis-cli running as suggested by Kue: https://automattic.github.io/kue/, but the program just does not run :).
Suggestions would be welcome, sorry if this is too basic to inquire about.


问:
How to create an issue in jira for certain conditions
I have a dataframe:

```<code>Vehicle Prod    Overall_stat   EU    EU_variant     status  partnumber  Error
A223    W223    NOT_OK        JLB21  JLB21_variant  NOT_OK  A23321      software not found
C243    E453    NOT_OK        JGG12  JGG12_variant  NOT_OK  A23322      software not found
A223    W223    NOT_OK        JBL25  JBL25_variant      OK  A23323      hardware not found
B321    I992    NOT_OK        L993   L993_variant   OK      A23324      hardware not found
        R365    NOT_OK        L223   L223_variant   NOT_OK  A23325      software not found
        R543    OK            L342   L342_variant   OK      A23326      hardware not found
</code>```

i need to create a jira ticket using rest api for following condition:

for distinct Vehicle if 'Overall_stat'  is NOT_OK then need to check if object is already present in jira, if not create an object with EU details

if distinct vehicle is null in dataframe then check for Prod value.if 'Overall_stat'  is NOT_OK then need to check if object is already present, if not create an object with EU details.

post creating a ticket for each distinct Vehicle/Prod check if EU is NOT_OK or OK, if its NOT_OK then create an issue for that EU and include partnumber and error in description.
link the issue to that vehicle/prod object created

if again we get same vehicle as NOT_OK and this EU is  different then, jira issue should be created and linked to that vehicle object

im currently connecting to Jira using following code:

```<code>url = "https://jira-url/jira/rest/api/2/issue"
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
    payload = json.dumps(
        {
            "fields": {
                "project": {
                    "key": 'project_name'
                },
                "summary": 'summary',
                "description": 'description',
                "issuetype": {
                    "name": "Problem"
                },

                "priority": {
                    "name": "Major"
                }

            }
        }
    )

    response = requests.post(url, headers=headers, data=payload, auth=("username", "password"), cert=('certificates'))

</code>```

how to achieve this scenario

Body:
I have a dataframe:

Vehicle Prod    Overall_stat   EU    EU_variant     status  partnumber  Error
A223    W223    NOT_OK        JLB21  JLB21_variant  NOT_OK  A23321      software not found
C243    E453    NOT_OK        JGG12  JGG12_variant  NOT_OK  A23322      software not found
A223    W223    NOT_OK        JBL25  JBL25_variant      OK  A23323      hardware not found
B321    I992    NOT_OK        L993   L993_variant   OK      A23324      hardware not found
        R365    NOT_OK        L223   L223_variant   NOT_OK  A23325      software not found
        R543    OK            L342   L342_variant   OK      A23326      hardware not found

i need to create a jira ticket using rest api for following condition:

for distinct Vehicle if 'Overall_stat'  is NOT_OK then need to check if object is already present in jira, if not create an object with EU details

if distinct vehicle is null in dataframe then check for Prod value.if 'Overall_stat'  is NOT_OK then need to check if object is already present, if not create an object with EU details.

post creating a ticket for each distinct Vehicle/Prod check if EU is NOT_OK or OK, if its NOT_OK then create an issue for that EU and include partnumber and error in description.
link the issue to that vehicle/prod object created

if again we get same vehicle as NOT_OK and this EU is  different then, jira issue should be created and linked to that vehicle object

im currently connecting to Jira using following code:

url = "https://jira-url/jira/rest/api/2/issue"
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
    payload = json.dumps(
        {
            "fields": {
                "project": {
                    "key": 'project_name'
                },
                "summary": 'summary',
                "description": 'description',
                "issuetype": {
                    "name": "Problem"
                },

                "priority": {
                    "name": "Major"
                }

            }
        }
    )

    response = requests.post(url, headers=headers, data=payload, auth=("username", "password"), cert=('certificates'))

how to achieve this scenario


问:
Invalid return property value in Vue 3
I'm making pagination using Vue, it was working fine yesterday but today it encountered a bug,

I have assigned the totalPage that the api returns but it no longer accepts that value to calculate the totalPage... Here is my code:

View

<template>

</template>

```
<p><strong>Script</strong></p>
<pre class="lang-js prettyprint-override"><code><script setup lang="ts">
const totalPage = ref<number>();
const current = ref(1);
async function getFile(page = 1) {
  try {
    const fileData = await request.get("api/admin/file/list", {
      params: {
        page,
        limit: 7,
        name: searchName.value.trim(),
        status: stateStatus.value,
        mimetype: typeFile.value,
        lte_size: endSize.value,
        gte_size: startSize.value,
      },
    });
    files.value = fileData.data.data;

    totalPage.value = fileData.data.count;
    console.log("Tổng trang:",totalPage.value) //Log the correct results
    loading.value = false;
  } catch (e) {
    console.log(e);
  }

  onMounted(async () => {
    await getFile();
});

//Tính phân trang
async function pagination(pageNumber: number) {
  current.value = pageNumber;
    files.value = [];
    await getFile(pageNumber);
}
</script>

</code>```

Hope to get help from everyone, thanks a lot

Title: Invalid return property value in Vue 3

Body:
I'm making pagination using Vue, it was working fine yesterday but today it encountered a bug,

I have assigned the totalPage that the api returns but it no longer accepts that value to calculate the totalPage... Here is my code:

View

<template>

</template>

Script

Hope to get help from everyone, thanks a lot


问:
How to filter extra points in Gray Code Structured Light?
I'm trying to calculate 3d points with graycode structured light. My setup has one camera and one projector. I project gray code and capture them. However when i was try calculate 3d points, i'm getting extra 3d point as you can see in image. Here is my code to decode graycode images and triangulate them.

```<code>x_index = stripe.decode(x_captures, x_nega_captures)  # thresh=60) #
y_index = stripe.decode(y_captures, y_nega_captures)  # thresh=60) #

# Merge X and Y correspondences
img_correspondence = cv2.merge([0.0 * np.zeros_like(x_index),
                                x_index / CAMERA_RESOLUTION[0],
                                y_index / CAMERA_RESOLUTION[1]])

# Clip correspondences to 8b
img_correspondence = np.clip(img_correspondence * 255, 0, 255)
img_correspondence = img_correspondence.astype(np.uint8)

# Mask correspondences with projectable area to eliminate sprurious points
img_correspondence[~is_projectable] = 0

# Visualize correspondences
plt.figure()
plt.imshow(img_correspondence)
plt.axis('off')
plt.title('Correspondence Map')
#plt.show()

# Construct 2D correspondences
# x_p and y_p are the 2D coordinates in projector image space
x_p = np.expand_dims(x_index[is_projectable].flatten(), -1)
y_p = np.expand_dims(y_index[is_projectable].flatten(), -1)
projector_points = np.hstack((x_p, y_p))

# x and y are the 2D coordinates in camera image space
xx, yy = np.meshgrid(np.arange(CAMERA_RESOLUTION[0]), np.arange(CAMERA_RESOLUTION[1]))
x = np.expand_dims(xx[is_projectable].flatten(), -1)
y = np.expand_dims(yy[is_projectable].flatten(), -1)
camera_points = np.hstack((x, y))

camera_points = np.expand_dims(camera_points, 1).astype(np.float32)
projector_points = np.expand_dims(projector_points, 1).astype(np.float32)

camera_norm_1 = cv2.undistortPoints(camera_points, camera_K, camera_d, P=camera_K)
proj_norm_1 = cv2.undistortPoints(projector_points, projector_K, projector_d, P=camera_K)

P0 = np.dot(camera_K, np.array([[1, 0, 0, 0],
                                [0, 1, 0, 0],
                                [0, 0, 1, 0]]))

P1 = np.concatenate((camera_K @ projector_R, camera_K @ projector_t), axis=1)

triangulated_points = cv2.triangulatePoints(P0, P1, camera_norm_1, proj_norm_1).T

points_3d = (triangulated_points[:, :3] / triangulated_points[:, -1:])

</code>```

Body:
I'm trying to calculate 3d points with graycode structured light. My setup has one camera and one projector. I project gray code and capture them. However when i was try calculate 3d points, i'm getting extra 3d point as you can see in image. Here is my code to decode graycode images and triangulate them.

x_index = stripe.decode(x_captures, x_nega_captures)  # thresh=60) #
y_index = stripe.decode(y_captures, y_nega_captures)  # thresh=60) #

# Merge X and Y correspondences
img_correspondence = cv2.merge([0.0 * np.zeros_like(x_index),
                                x_index / CAMERA_RESOLUTION[0],
                                y_index / CAMERA_RESOLUTION[1]])

# Clip correspondences to 8b
img_correspondence = np.clip(img_correspondence * 255, 0, 255)
img_correspondence = img_correspondence.astype(np.uint8)

# Mask correspondences with projectable area to eliminate sprurious points
img_correspondence[~is_projectable] = 0

# Visualize correspondences
plt.figure()
plt.imshow(img_correspondence)
plt.axis('off')
plt.title('Correspondence Map')
#plt.show()

# Construct 2D correspondences
# x_p and y_p are the 2D coordinates in projector image space
x_p = np.expand_dims(x_index[is_projectable].flatten(), -1)
y_p = np.expand_dims(y_index[is_projectable].flatten(), -1)
projector_points = np.hstack((x_p, y_p))

# x and y are the 2D coordinates in camera image space
xx, yy = np.meshgrid(np.arange(CAMERA_RESOLUTION[0]), np.arange(CAMERA_RESOLUTION[1]))
x = np.expand_dims(xx[is_projectable].flatten(), -1)
y = np.expand_dims(yy[is_projectable].flatten(), -1)
camera_points = np.hstack((x, y))

camera_points = np.expand_dims(camera_points, 1).astype(np.float32)
projector_points = np.expand_dims(projector_points, 1).astype(np.float32)

camera_norm_1 = cv2.undistortPoints(camera_points, camera_K, camera_d, P=camera_K)
proj_norm_1 = cv2.undistortPoints(projector_points, projector_K, projector_d, P=camera_K)

P0 = np.dot(camera_K, np.array([[1, 0, 0, 0],
                                [0, 1, 0, 0],
                                [0, 0, 1, 0]]))

P1 = np.concatenate((camera_K @ projector_R, camera_K @ projector_t), axis=1)

triangulated_points = cv2.triangulatePoints(P0, P1, camera_norm_1, proj_norm_1).T

points_3d = (triangulated_points[:, :3] / triangulated_points[:, -1:])


问:
Server Error in '/' Application in .net mvc
I am working with ASP.NET MVC .
I give the proper url name but error is the resource is not found.

I am click the checkout button and trying to open view but view is not open.

Please see below code.

cartDisplay.cshtml

```<code>
@{
    ViewBag.Title = "cartDisplay";
}

<h2>Add to Cart Details</h2>

<script src="~/kendo/js/kendo.all.min.js"></script>

<div style="display: inline">
    <div class="text-left">
        <button class='btn btn-group-sm btn-success' onclick='submit()'>CheckOut</button>
    </div>
</div>

<div id="example">

    <br />
    <br />

    <div id="grid"></div>

    <script>
        $(document).ready(function () {

        //here other code

      function submit() {
            debugger
            $.ajax({
                url: "/User/addToCartOrderStore",           //here I am giving the proper url but error is resource not found error
                type: 'GET',
                cache: false,
                contentType: false,
                processData: false,

                success: function (response) {
                    window.location.href = response.redirectToUrl;
                }
            });
        }
    </script>

</code>```

UserController.cs

//Shipping Details and order details
[HttpGet]
public ActionResult addToCartOrderStore()
{
    return View();
}

[HttpPost]
public ActionResult addToCartOrderStore(FormCollection sh)
{
    ....
}
```
<p>I am trying to open below view but below view is not open</p>
<p><code>addToCartOrderStore.cshtml</code>:</p>
```@{
    ViewBag.Title = "addToCartOrderStore";
}

AddToCart OrderStore

                @*
@Html.ActionLink("Home", "index")

 @Html.ActionLink("My Cart", "cartdisplay")

 @Html.ActionLink("My Orders", "orderdisplay")
*@

@Html.ActionLink("Logout", "Logout")

<form id="form"></form>

Body:
I am working with ASP.NET MVC .
I give the proper url name but error is the resource is not found.

I am click the checkout button and trying to open view but view is not open.

Please see below code.

cartDisplay.cshtml

@{
    ViewBag.Title = "cartDisplay";
}

Add to Cart Details

        <button class='btn btn-group-sm btn-success' onclick='submit()'>CheckOut</button>

UserController.cs

//Shipping Details and order details
[HttpGet]
public ActionResult addToCartOrderStore()
{
    return View();
}

[HttpPost]
public ActionResult addToCartOrderStore(FormCollection sh)
{
    ....
}

I am trying to open below view but below view is not open

addToCartOrderStore.cshtml:

@{
    ViewBag.Title = "addToCartOrderStore";
}

AddToCart OrderStore

                @*
@Html.ActionLink("Home", "index")

 @Html.ActionLink("My Cart", "cartdisplay")

 @Html.ActionLink("My Orders", "orderdisplay")
*@

@Html.ActionLink("Logout", "Logout")

<form id="form"></form>


问:
Inno Setup 6.2.1 web Download components problem
Having problems when Components section added to Inno Setup 6.2.1 download installation. Compiles ok, but unable to locate temporary file problem when code is run. What extra needs to be done when this download code is used for a components installer?
Simplified to a single custom install option.
Environment: Inno Setup 6.2.1, Windows 7

```<code>[Setup]
PrivilegesRequired=lowest

[Types]
Name: "custom"; Description: "Custom installation"; Flags: iscustom

[Components]
Name: "test";  Description: "Test File";  Types: custom; Flags: exclusive

[Files]
Source: "{tmp}\version.txt";  DestDir: "{userappdata}\wire"; DestName: "test.txt"; Components: "test"; Flags: external ignoreversion
</code>```

[Code]
var
DownloadPage: TDownloadWizardPage;

function OnDownloadProgress(const Url, FileName: String; const Progress, ProgressMax: Int64): Boolean;
begin
  if Progress = ProgressMax then
    Log(Format('Successfully downloaded file to {tmp}: %s', [FileName]));
  Result := True;
end;

procedure InitializeWizard;
begin
  DownloadPage := CreateDownloadPage(SetupMessage(msgWizardPreparing), SetupMessage(msgPreparingDesc), @OnDownloadProgress);
end;

function NextButtonClick(CurPageID: Integer): Boolean;
begin
  if CurPageID = wpReady then begin
    DownloadPage.Clear
    DownloadPage.Add('http://wireshare.sourceforge.net/WSSecurityUpdates/version', 'version.txt', '');

    DownloadPage.Show;
  try
    try
    DownloadPage.Download; // This downloads the files to {tmp}
    Result := True;
    except
    if DownloadPage.AbortedByUser then
      Log('Aborted by user.')
    else
      SuppressibleMsgBox(AddPeriod(GetExceptionMessage), mbCriticalError, MB_OK, IDOK);
    Result := False;
  end;
finally
  DownloadPage.Hide;
end;
end else
Result := True;
end;
```

Body:
Having problems when Components section added to Inno Setup 6.2.1 download installation. Compiles ok, but unable to locate temporary file problem when code is run. What extra needs to be done when this download code is used for a components installer?
Simplified to a single custom install option.
Environment: Inno Setup 6.2.1, Windows 7

[Setup]
PrivilegesRequired=lowest

[Types]
Name: "custom"; Description: "Custom installation"; Flags: iscustom

[Components]
Name: "test";  Description: "Test File";  Types: custom; Flags: exclusive

[Files]
Source: "{tmp}\version.txt";  DestDir: "{userappdata}\wire"; DestName: "test.txt"; Components: "test"; Flags: external ignoreversion

[Code]
var
DownloadPage: TDownloadWizardPage;

function OnDownloadProgress(const Url, FileName: String; const Progress, ProgressMax: Int64): Boolean;
begin
  if Progress = ProgressMax then
    Log(Format('Successfully downloaded file to {tmp}: %s', [FileName]));
  Result := True;
end;

procedure InitializeWizard;
begin
  DownloadPage := CreateDownloadPage(SetupMessage(msgWizardPreparing), SetupMessage(msgPreparingDesc), @OnDownloadProgress);
end;

function NextButtonClick(CurPageID: Integer): Boolean;
begin
  if CurPageID = wpReady then begin
    DownloadPage.Clear
    DownloadPage.Add('http://wireshare.sourceforge.net/WSSecurityUpdates/version', 'version.txt', '');

    DownloadPage.Show;
  try
    try
    DownloadPage.Download; // This downloads the files to {tmp}
    Result := True;
    except
    if DownloadPage.AbortedByUser then
      Log('Aborted by user.')
    else
      SuppressibleMsgBox(AddPeriod(GetExceptionMessage), mbCriticalError, MB_OK, IDOK);
    Result := False;
  end;
finally
  DownloadPage.Hide;
end;
end else
Result := True;
end;


问:
Run Class method in parallel
Task: i have a class that takes some arguments and runs a function in a cycle, that clones a  lot of git repositories. I'd like to run it in a parallel, but faced with errors such like

cannot pickle '_thread.RLock' object (when trying multiprocessing)
cannot pickle 'ConsoleThreadLocals' object (when trying multiprocessing with dill)

Code structure:

# main.py
import ProcessProjects

if __name__ == '__main__':
    ProcessProjects(
        project_list=['project1', 'project2'],
        project_dir='projects',
        repo_type='all',
        clear_before_start=True)
```
<pre class="lang-py prettyprint-override"><code># ProcessProjects.py
import git
import os
import re
import shutil
import params

class ProcessProjects:
    def __init__(self,
                 project_dir: str,
                 project_list: list[str] = ['all'],
                 repo_type: str = 'all',
                 clear_before_start: bool = False,):
        self.project_dir = project_dir
        self.project_list = project_list
        self.repo_type = repo_type
        self.clear_before_start = clear_before_start
        self.main()

    def _task(self, project_name):
        _data = params.projects[project_name]

        def _run(repo_type, repo_name, repo_branch, repo_url, repo_dir):
            repo = git.Repo.clone_from(repo_url, repo_dir)
            repo.git.checkout(repo_branch)

        def _get_inventory():
            _repo_url = _data['inventory']['url']
            _repo_name = re.findall(r'7999\/.+\/(.+)\.git', _repo_url)[0]
            _repo_dir = f"{self.project_dir}/{project_name}/inventory"
            _repo_branch = _data['inventory']['branch']
            if os.path.exists(_repo_dir) and os.path.isdir(_repo_dir):
                if self.clear_before_start:
                    shutil.rmtree(_repo_dir)
                    _run('inventory', _repo_name, _repo_branch, _repo_url, _repo_dir)
            else:
                _run('inventory', _repo_name, _repo_branch, _repo_url, _repo_dir)

        def _get_code():
            for _repo in _data['code']:
                _repo_url = _repo['url']
                _repo_name = re.findall(r'7999\/.+\/(.+)\.git', _repo_url)[0]
                _repo_dir = f"{self.project_dir}/{project_name}/code/{_repo_name}"
                _repo_branch = _repo['branch']
                if os.path.exists(_repo_dir) and os.path.isdir(_repo_dir):
                    if self.clear_before_start:
                        shutil.rmtree(_repo_dir)
                        _run('code', _repo_name, _repo_branch, _repo_url, _repo_dir)
                else:
                    _run('code', _repo_name, _repo_branch, _repo_url, _repo_dir)

        if self.project_list[0] == 'all' or project_name in self.project_list:
            if self.repo_type == 'all':
                _get_inventory()
                _get_code()
            elif self.repo_type == 'inventory':
                _get_inventory()
            elif self.repo_type == 'code':
                _get_code()

    def main(self):
        for project in params.projects.keys():
            self._task(project)
</code>```

# params.py example

projects = {
    'project1': {
        'inventory': {'branch': 'master', 'url': 'ssh://.../inventory.git'},
        'code': [
            {'branch': 'develop', 'url': 'ssh://.../code.git'},
        ]
    },
    'project2': {
        'inventory': {'branch': 'master', 'url': 'ssh://.../inventory.git'},
        'code': [
            {'branch': 'master', 'url': 'ssh://.../code.git'},
            {'branch': 'master', 'url': 'ssh://.../code2.git'},
        ]
    },
```
<p>This is a code example without multiprocessing. When I call class, I specify, what projects I want to download, where to store it, and what type of repository i want to get.</p>
<p>How can I rewrite main method, to replace cycle</p>
<pre class="lang-py prettyprint-override"><code>for project in params.projects.keys():
            self._task(project)

</code>```

and run task in a parallel?

for example

from multiprocessing import Pool

with multiprocessing.Pool() as pool:
    pool.map(self._task, [project for project in params.projects.keys()])
```
<p>TypeError: cannot pickle '_thread.RLock' object</p>
<pre class="lang-py prettyprint-override"><code>from multiprocessing import Process
workers = []
for project in params.projects.keys():
    worker = Process(target=self._task, args=[project])
    worker.start()
    workers.append(worker)
for worker in workers:
    worker.join()
</code>```

TypeError: cannot pickle '_thread.RLock' object

Title: Run Class method in parallel

Body:
Task: i have a class that takes some arguments and runs a function in a cycle, that clones a  lot of git repositories. I'd like to run it in a parallel, but faced with errors such like

cannot pickle '_thread.RLock' object (when trying multiprocessing)
cannot pickle 'ConsoleThreadLocals' object (when trying multiprocessing with dill)

Code structure:

# main.py
import ProcessProjects

if __name__ == '__main__':
    ProcessProjects(
        project_list=['project1', 'project2'],
        project_dir='projects',
        repo_type='all',
        clear_before_start=True)

# ProcessProjects.py
import git
import os
import re
import shutil
import params

class ProcessProjects:
    def __init__(self,
                 project_dir: str,
                 project_list: list[str] = ['all'],
                 repo_type: str = 'all',
                 clear_before_start: bool = False,):
        self.project_dir = project_dir
        self.project_list = project_list
        self.repo_type = repo_type
        self.clear_before_start = clear_before_start
        self.main()

    def _task(self, project_name):
        _data = params.projects[project_name]

        def _run(repo_type, repo_name, repo_branch, repo_url, repo_dir):
            repo = git.Repo.clone_from(repo_url, repo_dir)
            repo.git.checkout(repo_branch)

        def _get_inventory():
            _repo_url = _data['inventory']['url']
            _repo_name = re.findall(r'7999\/.+\/(.+)\.git', _repo_url)[0]
            _repo_dir = f"{self.project_dir}/{project_name}/inventory"
            _repo_branch = _data['inventory']['branch']
            if os.path.exists(_repo_dir) and os.path.isdir(_repo_dir):
                if self.clear_before_start:
                    shutil.rmtree(_repo_dir)
                    _run('inventory', _repo_name, _repo_branch, _repo_url, _repo_dir)
            else:
                _run('inventory', _repo_name, _repo_branch, _repo_url, _repo_dir)

        def _get_code():
            for _repo in _data['code']:
                _repo_url = _repo['url']
                _repo_name = re.findall(r'7999\/.+\/(.+)\.git', _repo_url)[0]
                _repo_dir = f"{self.project_dir}/{project_name}/code/{_repo_name}"
                _repo_branch = _repo['branch']
                if os.path.exists(_repo_dir) and os.path.isdir(_repo_dir):
                    if self.clear_before_start:
                        shutil.rmtree(_repo_dir)
                        _run('code', _repo_name, _repo_branch, _repo_url, _repo_dir)
                else:
                    _run('code', _repo_name, _repo_branch, _repo_url, _repo_dir)

        if self.project_list[0] == 'all' or project_name in self.project_list:
            if self.repo_type == 'all':
                _get_inventory()
                _get_code()
            elif self.repo_type == 'inventory':
                _get_inventory()
            elif self.repo_type == 'code':
                _get_code()

    def main(self):
        for project in params.projects.keys():
            self._task(project)

# params.py example

projects = {
    'project1': {
        'inventory': {'branch': 'master', 'url': 'ssh://.../inventory.git'},
        'code': [
            {'branch': 'develop', 'url': 'ssh://.../code.git'},
        ]
    },
    'project2': {
        'inventory': {'branch': 'master', 'url': 'ssh://.../inventory.git'},
        'code': [
            {'branch': 'master', 'url': 'ssh://.../code.git'},
            {'branch': 'master', 'url': 'ssh://.../code2.git'},
        ]
    },

This is a code example without multiprocessing. When I call class, I specify, what projects I want to download, where to store it, and what type of repository i want to get.

How can I rewrite main method, to replace cycle

for project in params.projects.keys():
            self._task(project)

and run task in a parallel?

for example

from multiprocessing import Pool

with multiprocessing.Pool() as pool:
    pool.map(self._task, [project for project in params.projects.keys()])

TypeError: cannot pickle '_thread.RLock' object

from multiprocessing import Process
workers = []
for project in params.projects.keys():
    worker = Process(target=self._task, args=[project])
    worker.start()
    workers.append(worker)
for worker in workers:
    worker.join()

TypeError: cannot pickle '_thread.RLock' object


问:
Scrapy parsed unknown character
I have wanted to scrape the site https://www.bikebd.com/brand/yamaha/ . here is my script

```<code>import scrapy
from scrapy.utils.response import open_in_browser

from urllib.parse import urlencode

class BikebdSpider(scrapy.Spider):
    name = 'bikebd'
    allowed_domains = ['www.bikebd.com']
    headers = {
            'accept': '*/*',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'en-US,en;q=0.9,da;q=0.8',
            'cache-control':'no-cache',
            'cookie': '_ga=GA1.1.1549289426.1669609851; XSRF-TOKEN=eyJpdiI6IjhCN1BnV0RoK3dOQnFEQlhYRUZVZEE9PSIsInZhbHVlIjoiTFQ4Ym15MWhoU1hmR3FxaWdVYnkvbnovMTVDbS9iRm1OVCsrV0F2RzA5dHlmMWpObENoSFBWY0VXclBNWkZaNlV1aitwSXBWNjhNMGs2Z3JqQ3ZvQWVIQ25QcnNOZkNpR3lwMGNkL01aWHM3VDZ5YmZJblRha0kyUk5IMTh2UzQiLCJtYWMiOiJjMzFmMDZlZDFjNzVhNTVlZjY1MWEzNWJkZjY5Y2Q1MjFiZmNmM2UxOWRiZWJlMGRhZWY5OGU0MGQ4OWI5N2ViIiwidGFnIjoiIn0%3D; bikebd_session=eyJpdiI6ImVVb2NqcmFLR2dKSXc2NnNqUlV6ZWc9PSIsInZhbHVlIjoibUVNcEZidUxsbWdkK3c2UDFYdDYwcHFOdVU1WmVXY0ZiV1pHRzJBbzlaUDNuWGl2Vk1OTk5QYnRkdmVXdDg3bEx2SEpiMGE1c2dvakdkU0tQOTBucHc5ajRpcGpod2ViL3B2ME9DRXc4SUFtSG56YU9MVTdEVi9rYW8reXk0TDYiLCJtYWMiOiI5MmU2NWEyZDhkOGFiNTdkYzQ0ZGJhMDQwNzFhYzFmOGY4MzNjNWU2ODczYWNiOTVlNjU4MWUyZWVmMzE5NjNmIiwidGFnIjoiIn0%3D; _ga_HEG073JLWK=GS1.1.1670663205.2.1.1670663540.0.0.0',
            'pragma': 'no-cache',
            'referer': 'https://www.bikebd.com/bike-price-in-bd',
            'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': "Windows",
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'no-cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
            }

    def start_requests(self):
        urls = ["https://www.bikebd.com/brand/yamaha"]
        for url in urls:
            yield scrapy.Request(url= url ,  callback=self.parse)

    def parse(self, response):
        container = response.xpath("//div[@class='tab-cards-rev']/div/div[@class='col-md-3']")
        for item in container:
            title = item.xpath(".//h2[@class='ltn-tittle mb-0']/strong/text()").get()

            yield {'title' : title}
</code>```

but when I crawl the script it returns none. Then I start debug the spider with open in browser by this line of code...

```<code>def parse(self, response):
    open_in_browser(response)
</code>```

Then it showed me some unreadable characters like below.

```<code>ôÿ‘šôC@#tøœ÷ÿfjun_N?ÈKÛžDÜ$YVyË²UÒ–³TUoŸÄ'…8hI®ö,ëá4·9g¶åÝûtÎOûUéCh|â¢€Ð8`÷ D“†b&³“ÝªW¯ª~÷À"Á¹¹a]Ðøß¿{©wŽ(€è  ¼ÇX¶nû»¥ˆŠ¦eÙËÿ«Íñ"åY³1Vÿõ¯³½ÍUDÃ±‡½â`¹‰½é½ê”§Œl‡%,{Š»È?8PaÐ-œ[·EÏ&Žl,ö‰êµŽÄ€ŠŒ+ŒMØèãG{L˜ž2 ?£?èaÂ´UWÞ$[0²üÃZ’‡N±ÅÔ%$[pÝ9ä[ ¯±ÖÞW(ñ¥-ˆxf¿ì±
</code>```

What's going on the site? need some help.

Title: Scrapy parsed unknown character

Body:
I have wanted to scrape the site https://www.bikebd.com/brand/yamaha/ . here is my script

import scrapy
from scrapy.utils.response import open_in_browser

from urllib.parse import urlencode

class BikebdSpider(scrapy.Spider):
    name = 'bikebd'
    allowed_domains = ['www.bikebd.com']
    headers = {
            'accept': '*/*',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'en-US,en;q=0.9,da;q=0.8',
            'cache-control':'no-cache',
            'cookie': '_ga=GA1.1.1549289426.1669609851; XSRF-TOKEN=eyJpdiI6IjhCN1BnV0RoK3dOQnFEQlhYRUZVZEE9PSIsInZhbHVlIjoiTFQ4Ym15MWhoU1hmR3FxaWdVYnkvbnovMTVDbS9iRm1OVCsrV0F2RzA5dHlmMWpObENoSFBWY0VXclBNWkZaNlV1aitwSXBWNjhNMGs2Z3JqQ3ZvQWVIQ25QcnNOZkNpR3lwMGNkL01aWHM3VDZ5YmZJblRha0kyUk5IMTh2UzQiLCJtYWMiOiJjMzFmMDZlZDFjNzVhNTVlZjY1MWEzNWJkZjY5Y2Q1MjFiZmNmM2UxOWRiZWJlMGRhZWY5OGU0MGQ4OWI5N2ViIiwidGFnIjoiIn0%3D; bikebd_session=eyJpdiI6ImVVb2NqcmFLR2dKSXc2NnNqUlV6ZWc9PSIsInZhbHVlIjoibUVNcEZidUxsbWdkK3c2UDFYdDYwcHFOdVU1WmVXY0ZiV1pHRzJBbzlaUDNuWGl2Vk1OTk5QYnRkdmVXdDg3bEx2SEpiMGE1c2dvakdkU0tQOTBucHc5ajRpcGpod2ViL3B2ME9DRXc4SUFtSG56YU9MVTdEVi9rYW8reXk0TDYiLCJtYWMiOiI5MmU2NWEyZDhkOGFiNTdkYzQ0ZGJhMDQwNzFhYzFmOGY4MzNjNWU2ODczYWNiOTVlNjU4MWUyZWVmMzE5NjNmIiwidGFnIjoiIn0%3D; _ga_HEG073JLWK=GS1.1.1670663205.2.1.1670663540.0.0.0',
            'pragma': 'no-cache',
            'referer': 'https://www.bikebd.com/bike-price-in-bd',
            'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': "Windows",
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'no-cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
            }

    def start_requests(self):
        urls = ["https://www.bikebd.com/brand/yamaha"]
        for url in urls:
            yield scrapy.Request(url= url ,  callback=self.parse)

    def parse(self, response):
        container = response.xpath("//div[@class='tab-cards-rev']/div/div[@class='col-md-3']")
        for item in container:
            title = item.xpath(".//h2[@class='ltn-tittle mb-0']/strong/text()").get()

            yield {'title' : title}

but when I crawl the script it returns none. Then I start debug the spider with open in browser by this line of code...

def parse(self, response):
    open_in_browser(response)

Then it showed me some unreadable characters like below.

ôÿ‘šôC@#tøœ÷ÿfjun_N?ÈKÛžDÜ$YVyË²UÒ–³TUoŸÄ'…8hI®ö,ëá4·9g¶åÝûtÎOûUéCh|â¢€Ð8`÷ D“†b&³“ÝªW¯ª~÷À"Á¹¹a]Ðøß¿{©wŽ(€è  ¼ÇX¶nû»¥ˆŠ¦eÙËÿ«Íñ"åY³1Vÿõ¯³½ÍUDÃ±‡½â`¹‰½é½ê”§Œl‡%,{Š»È?8PaÐ-œ[·EÏ&Žl,ö‰êµŽÄ€ŠŒ+ŒMØèãG{L˜ž2 ?£?èaÂ´UWÞ$[0²üÃZ’‡N±ÅÔ%$[pÝ9ä[ ¯±ÖÞW(ñ¥-ˆxf¿ì±

What's going on the site? need some help.


问:
adding tailwind classes for table borders dynamically doesn't work
I have a bit of a custom table within my app , I receive data about which borders are there on each td tag

my border info property for example is TBLR , which means I have borders on top , bottom , left and right and so on
tailwind isn't really picking up on individual borders for me ,
an example tag would look like this :

```<code> <td class=" border-t-2 border-t-red-900  border-b-2 border-b-red-900  border-l-2 border-l-red-900 " colspan="1" rowspan="1">Unit Supply temp in Econ mode</td>
</code>```

but that doesn't add the border colors ,

Here's a sandbox with the example : https://codesandbox.io/s/tailwind-css-and-react-forked-dsy1em

Would love some help why these classes aren't working

Body:
I have a bit of a custom table within my app , I receive data about which borders are there on each td tag

my border info property for example is TBLR , which means I have borders on top , bottom , left and right and so on
tailwind isn't really picking up on individual borders for me ,
an example tag would look like this :

 Unit Supply temp in Econ mode

but that doesn't add the border colors ,

Here's a sandbox with the example : https://codesandbox.io/s/tailwind-css-and-react-forked-dsy1em

Would love some help why these classes aren't working


问:
Error when deploy Shiny: "An error has occurred. The application failed to start. exit status 1"
I encounter an error when trying to publish my shiny apps, the code runs perfectly in the local R studio. However when I tried to deploy the Shiny I had this error

"An error has occurred
The application failed to start.
exit status 1"

error image

I have tried to clean the global environment and rerun the codes but same issue still occur. There are no warning message or errors in the r studio console as well. Any thoughts on what is causing this error?

Thank you in advance.


问:
Backtrader, using mongodb as datafeed instead CSV
I'm quite new to backtrader and since I've started I couldn't stop wondering why there's no database support for the datafeed. I've found a page on the official website where's described how to implement a custom datafeed. The implementation should be pretty easy, but on github (or more in general on the web) I couldn't fine a single one implementation of a feed with MongoDb. I understand that CSV are easier to manage and so on, but in some cases could require a lot of RAM for storing data all at once in memory. On the other hand, having a db can be "RAM friendly" but will take longer during the backtesting process even if the DB is a documental one. Does anyone have any experience with both of these two approaches? And if yes, there's some code I can take a look at?

Thanks!


问:
Is passing a new string to a function already allocating memory (without using that string)?
We're coding in Unity but I guess it also applies to standard C# apps.

We're trying to avoid creating strings in live builds to prevent garbage collection.

If I understand strings correctly, if I create a new string "ABC" it will allocate memory for the first time but then it will be cached (this exact string) and it shouldn't allocate memory if we reuse that string. I know that there is more to it and the caching mechanisms are much more complex than that.

But I was wondering about function arguments. Let's say we call a function and pass directly created string to it:

```<code>fun("ABC");
</code>```

I guess the rules still apply: "ABC" will allocate memory with the first invocation of fun() but subsequent calls will not allocate (because of caching)

What bothers me is lots of optimization guides suggesting that we should use compilation directives to remove logs from live builds like this (example here):

```<code>public static void LogMessage(string message)
{
    #if UNITY_EDITOR
    Debug.Log(message);
    #endif
}
</code>```

If the UNITY_EDITOR directive is false it's obviously gonna strip the debug log from the final build, but the invocation will still remain in the code:

```<code>LogMessage("some message");
</code>```

Which - if I'm not wrong - will still allocate memory on the first invocation.

Or maybe, if the compilator detects that this string is indeed passed to the function but it's not used later, it will not allocate? How does it work?

Body:
We're coding in Unity but I guess it also applies to standard C# apps.

We're trying to avoid creating strings in live builds to prevent garbage collection.

If I understand strings correctly, if I create a new string "ABC" it will allocate memory for the first time but then it will be cached (this exact string) and it shouldn't allocate memory if we reuse that string. I know that there is more to it and the caching mechanisms are much more complex than that.

But I was wondering about function arguments. Let's say we call a function and pass directly created string to it:

fun("ABC");

I guess the rules still apply: "ABC" will allocate memory with the first invocation of fun() but subsequent calls will not allocate (because of caching)

What bothers me is lots of optimization guides suggesting that we should use compilation directives to remove logs from live builds like this (example here):

public static void LogMessage(string message)
{
    #if UNITY_EDITOR
    Debug.Log(message);
    #endif
}

If the UNITY_EDITOR directive is false it's obviously gonna strip the debug log from the final build, but the invocation will still remain in the code:

LogMessage("some message");

Which - if I'm not wrong - will still allocate memory on the first invocation.

Or maybe, if the compilator detects that this string is indeed passed to the function but it's not used later, it will not allocate? How does it work?


问:
Create multiple attributes using a single parameter in python dataclasses
I want to create multiple attributes using a single parameter in python dataclasses but it ends up showing an error

-This is my Code

@dataclass
class Human:
    name: str
    age: int
    birthyear:int=2022-age

h1 = Human("john", 35)
print(h1.birthyear)
```
<p>-This error ends up showing</p>
```Traceback (most recent call last):
  File "D:\Taha\Programs\Python\projects\UNO\tests.py", line 5, in <module>
    class Human:
  File "D:\Taha\Programs\Python\projects\UNO\tests.py", line 8, in Human
    yearOfBirth :int= 2022-age
NameError: name 'age' is not defined
```
<p>I want to create a class like this</p>
<pre class="lang-py prettyprint-override"><code>class Human:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.birthyear = 2022 - age
</code>```

OR

class Human:
    def __init__(self, name, age, birthyear=2022):
        self.name = name
        self.age = age
        self.birthyear = birthyear - age
```

Body:
I want to create multiple attributes using a single parameter in python dataclasses but it ends up showing an error

-This is my Code

@dataclass
class Human:
    name: str
    age: int
    birthyear:int=2022-age

h1 = Human("john", 35)
print(h1.birthyear)

-This error ends up showing

Traceback (most recent call last):
  File "D:\Taha\Programs\Python\projects\UNO\tests.py", line 5, in <module>
    class Human:
  File "D:\Taha\Programs\Python\projects\UNO\tests.py", line 8, in Human
    yearOfBirth :int= 2022-age
NameError: name 'age' is not defined

I want to create a class like this

class Human:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.birthyear = 2022 - age

OR

class Human:
    def __init__(self, name, age, birthyear=2022):
        self.name = name
        self.age = age
        self.birthyear = birthyear - age


问:
CVAT localhost not uploading images
I have installed CVAT on local (via Docker) but when trying to upload images from the local storage, it's simply stuck. It says "The data are being uploaded to the server" and is stuck at 0%. I tested with every kind of image file, big or small.

On the network tab it makes requests to http://localhost:8080/api/tasks/10/status?org= and keeps returning

What's going on?

Title: CVAT localhost not uploading images


问:
If item exist updat else insert
I have this problem where I need to check if a specific item exists by its id in the "Items" field, if it exists then I need to add new indices, I already did the adding new indices part but I don't know how I can add an item new when it does not exist.

Document to modify

```<code>{
    UserID: 100,
    UserAddress: '0x000000',
    Items: [
        {
            item_id: 1000,
            item_type: "NULL",
            item_indexes: [ "0x11111", "0x22222", "0x33333" ]
        },
        {
            item_id: 2000,
            item_type: "NULL",
            item_indexes: [ "0x44444", "0x55555", "0x66666" ]
        }
    ],
}
</code>```

Code to add new indexes

```<code>this.raw.bulkWrite(objects.map(object => {
    return {
        updateOne: {
            filter: {
                UserID: userId
            },
            update: {
                $addToSet: {
                    "Items.$[t].item_indexes": {
                        $each: object.indexesAsArray
                    }
                },
            },
            upsert: true,
            arrayFilters: [{
                "t.item_id": object.itemId
            }]
        }
    } as any
}))
</code>```

What I expect is to be able to insert new items that do not exist in the 'Items' field, but if it exists then add new indexes, I clarify that it must be in the same query

Example

Document to modify

```<code>{
    UserID: 100,
    UserAddress: '0x000000',
    Items: [
        {
            item_id: 1000,
            item_type: "NULL",
            item_indexes: [ "0x11111", "0x22222", "0x33333" ]
        }
    ],
}
</code>```

expected result

```<code>{
    UserID: 100,
    UserAddress: '0x000000',
    Items: [
        {
            item_id: 1000,
            item_type: "NULL",
            item_indexes: [ "0x11111", "0x22222", "0x33333", "0x88888", "0x99999" ]
        },
        {
            item_id: 2000,
            item_type: "NULL",
            item_indexes: [ "0x44444" ]
        }
    ],
}
</code>```

Title: If item exist updat else insert

Body:
I have this problem where I need to check if a specific item exists by its id in the "Items" field, if it exists then I need to add new indices, I already did the adding new indices part but I don't know how I can add an item new when it does not exist.

Document to modify

{
    UserID: 100,
    UserAddress: '0x000000',
    Items: [
        {
            item_id: 1000,
            item_type: "NULL",
            item_indexes: [ "0x11111", "0x22222", "0x33333" ]
        },
        {
            item_id: 2000,
            item_type: "NULL",
            item_indexes: [ "0x44444", "0x55555", "0x66666" ]
        }
    ],
}

Code to add new indexes

this.raw.bulkWrite(objects.map(object => {
    return {
        updateOne: {
            filter: {
                UserID: userId
            },
            update: {
                $addToSet: {
                    "Items.$[t].item_indexes": {
                        $each: object.indexesAsArray
                    }
                },
            },
            upsert: true,
            arrayFilters: [{
                "t.item_id": object.itemId
            }]
        }
    } as any
}))

What I expect is to be able to insert new items that do not exist in the 'Items' field, but if it exists then add new indexes, I clarify that it must be in the same query

Example

Document to modify

{
    UserID: 100,
    UserAddress: '0x000000',
    Items: [
        {
            item_id: 1000,
            item_type: "NULL",
            item_indexes: [ "0x11111", "0x22222", "0x33333" ]
        }
    ],
}

expected result

{
    UserID: 100,
    UserAddress: '0x000000',
    Items: [
        {
            item_id: 1000,
            item_type: "NULL",
            item_indexes: [ "0x11111", "0x22222", "0x33333", "0x88888", "0x99999" ]
        },
        {
            item_id: 2000,
            item_type: "NULL",
            item_indexes: [ "0x44444" ]
        }
    ],
}


问:
Backdrop filter blur does not work properly
The filter does not work properly only in one element (the content is inserted via js), everywhere else it works (static content).

<search_results></search_results> is empty and the search results are injected via js

<search_results style="padding: 10px;">

            <search_results_img style="
        background: center/contain no-repeat;
        background-image: url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTdwjX-Qajoog5Euindbr3EWi-BzkTkmofYPka25AjX&s=10);
    "></search_results_img>

                HelloFresh

            <search_results_img style="
        background: center/contain no-repeat;
        background-image: url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDKokubLSel1qbI81l_2oVHwTety1asucEi3DMhwBks7PqoosOe-af3dIbQQ&s=10);
    "></search_results_img>

                Hello

    </search_results>
```
<pre class="lang-css prettyprint-override"><code>search_results {
    position: relative;
    z-index: 5;
    background: var(--bg-transparent);
    font-size: var(--font-size1);
    display: block;
    width: 100%;
    height: fit-content;
    box-sizing: border-box;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    box-shadow: var(--shadow);
    max-height: 280px;
    -webkit-backdrop-filter: blur(10px); /* <- ??? */
    backdrop-filter: blur(10px); /* <- ??? */
}
</code>```

what could be the reason for this (dynamically inserted content?)

as an example, here is the rest of the (static) content where it works (relatively same css)

Body:
The filter does not work properly only in one element (the content is inserted via js), everywhere else it works (static content).

<search_results></search_results> is empty and the search results are injected via js

<search_results style="padding: 10px;">

            <search_results_img style="
        background: center/contain no-repeat;
        background-image: url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTdwjX-Qajoog5Euindbr3EWi-BzkTkmofYPka25AjX&s=10);
    "></search_results_img>

                HelloFresh

            <search_results_img style="
        background: center/contain no-repeat;
        background-image: url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDKokubLSel1qbI81l_2oVHwTety1asucEi3DMhwBks7PqoosOe-af3dIbQQ&s=10);
    "></search_results_img>

                Hello

    </search_results>

search_results {
    position: relative;
    z-index: 5;
    background: var(--bg-transparent);
    font-size: var(--font-size1);
    display: block;
    width: 100%;
    height: fit-content;
    box-sizing: border-box;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    box-shadow: var(--shadow);
    max-height: 280px;
    -webkit-backdrop-filter: blur(10px); /* <- ??? */
    backdrop-filter: blur(10px); /* <- ??? */
}

what could be the reason for this (dynamically inserted content?)

as an example, here is the rest of the (static) content where it works (relatively same css)


问:
how I iterate coulmns in 3d array in a wide dimension in c?
i'm looking for a loop logic to iterate over all possible columns in a 3d array of size 4X4X4.
I need to check eacgh cell with a ceratin color,
meaning:


问:
Folium Map: zoom level greater than 19?
Using a drone with a camera, I'm trying to plot on a map the location of specific object (gps coordinates are taken from gps drone).

I'm using Folium and python to perform the plot on a map which works fine, except for the zoom level that is not enough for my objective. Therefore, my points are all crushed in the same spot.

```<code>m = folium.Map(location=[lat, lon], zoom_start=25)
</code>```

I understand that in Folium the maximum is 19, but is there a way I can increase the zoom level to 25/30?
Maybe using other Maps or different platform?

Many Thanks!!

Title: Folium Map: zoom level greater than 19?

Body:
Using a drone with a camera, I'm trying to plot on a map the location of specific object (gps coordinates are taken from gps drone).

I'm using Folium and python to perform the plot on a map which works fine, except for the zoom level that is not enough for my objective. Therefore, my points are all crushed in the same spot.

m = folium.Map(location=[lat, lon], zoom_start=25)

I understand that in Folium the maximum is 19, but is there a way I can increase the zoom level to 25/30?
Maybe using other Maps or different platform?

Many Thanks!!


问:
Constructor misunderstanding
Normally, I've seen using new Vector2() while calling a constructor and instantiating an object for a class. Like:

Vector2 v2_values = new Vector2(float x , float y);

Here we called to the Vector2 constructor to instantiate an object of Vector2 class and stored it in v2_values variable. That I understood. But I don't understand the new Vector2(2,5) part of the code. Like how can we call an constructor in between and that too without making an object

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoverScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Rigidbody2D rd2d = GetComponent<Rigidbody2D>();
        rd2d.AddForce(new Vector2(2,5) ,
            ForceMode2D.Impulse);
    }
}
</code>```

Title: Constructor misunderstanding

Body:
Normally, I've seen using new Vector2() while calling a constructor and instantiating an object for a class. Like:

Vector2 v2_values = new Vector2(float x , float y);

Here we called to the Vector2 constructor to instantiate an object of Vector2 class and stored it in v2_values variable. That I understood. But I don't understand the new Vector2(2,5) part of the code. Like how can we call an constructor in between and that too without making an object

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoverScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Rigidbody2D rd2d = GetComponent<Rigidbody2D>();
        rd2d.AddForce(new Vector2(2,5) ,
            ForceMode2D.Impulse);
    }
}