问:
Find the percentage for both cash and credit
So, I have a column 'Type' that has cash and credit transactions. I want to find the percentage for both as results. Can anybody help me accomplish this?

```<code>SELECT COUNT(Type),
    SUM(CASE WHEN Type = 'Cash' THEN 1 ELSE 0 END)/COUNT(*) * 100 AS PercentageCashTransaction,
    SUM(CASE WHEN Type = 'Credit' THEN 1 ELSE 0 END)/COUNT(*) * 100 AS PercentageCreditTransaction
FROM vending_machine_sales
GROUP BY type;
</code>```

Actual results:

TYPE
%Cash
%Credit

2148
0
100

4297
100
0

Desired results:

%Cash
%Credit

67%
33%

Body:
So, I have a column 'Type' that has cash and credit transactions. I want to find the percentage for both as results. Can anybody help me accomplish this?

SELECT COUNT(Type),
    SUM(CASE WHEN Type = 'Cash' THEN 1 ELSE 0 END)/COUNT(*) * 100 AS PercentageCashTransaction,
    SUM(CASE WHEN Type = 'Credit' THEN 1 ELSE 0 END)/COUNT(*) * 100 AS PercentageCreditTransaction
FROM vending_machine_sales
GROUP BY type;

Actual results:

TYPE
%Cash
%Credit

2148
0
100

4297
100
0

Desired results:

%Cash
%Credit

67%
33%


来源: stackexchange

问:
Placing a background image behind a semi-transparent table in wxPython
I'm trying to make a frame in wxPython using a wx.grid as a table and with a background image behind the cells.

I already tried placing the grid in a table and lowering the frame opacity with frame.SetTransparent(), which might work, but the frame just refuses to display if I give the parent a background with StaticBitmap. I couldn't find an alternative way to use an image as a background or a way to fix that problem.
There's also the wx.grid.SetDefaultCellBackgroundColour function, but the function only accepts RGB values with no alpha. I tried messing around with internal values but no luck there either.

Bonus points if the image doesn't overlap with the headers but at this point I'll take what I can get.

ContentLicense: CC BY-SA 4.0


问:
Writing and reading a file without fseek
I have some embedded code, that is writing data to a file in one task and reading data from the same file in another task. The writer is faster than the reader, so the reader will first reach end-of-file after the writer has completed.

```<code>WRITER TASK:
fseek(f, 0, SEEK_END);
fwrite(...)

READER TASK:
fseek(f, rdpos, SEEK_SET);
rdpos += fread(...)
</code>```

Currently the code logic works, but it is too slow.
The fseek calls is taking too long time, especially when the file gets large.

Is there another way of writing and reading a file simultaneously ?

EDIT: I can see this question is probably needs some more info.
The system is a ESP32, so the memory is relative limited, and the file is located on an sdcard and the file size is up to 100Mbyte.
I have tried to open the file two times, like:

```<code>fwr = fopen(filename, "w+");
...
frd = fopen(filename, "r");
</code>```

Then fwrite(..., fwr) and fread(..., frd), but the read data is bogus.

EDIT2:
The data being stored is audio, we want the audio to be stored fast, but simultaneously being able to start playing the audio.
The audio output codec has a limited buffer, so to prevent this buffer from running empty, we need a low read time. The isolated write and read times are ok, but when during seek, the time gets too high.

EDIT3:
The write speed is about 250Kbyte/s, and the read speed is 16Kbyte/s.

Body:
I have some embedded code, that is writing data to a file in one task and reading data from the same file in another task. The writer is faster than the reader, so the reader will first reach end-of-file after the writer has completed.

WRITER TASK:
fseek(f, 0, SEEK_END);
fwrite(...)

READER TASK:
fseek(f, rdpos, SEEK_SET);
rdpos += fread(...)

Currently the code logic works, but it is too slow.
The fseek calls is taking too long time, especially when the file gets large.

Is there another way of writing and reading a file simultaneously ?

EDIT: I can see this question is probably needs some more info.
The system is a ESP32, so the memory is relative limited, and the file is located on an sdcard and the file size is up to 100Mbyte.
I have tried to open the file two times, like:

fwr = fopen(filename, "w+");
...
frd = fopen(filename, "r");

Then fwrite(..., fwr) and fread(..., frd), but the read data is bogus.

EDIT2:
The data being stored is audio, we want the audio to be stored fast, but simultaneously being able to start playing the audio.
The audio output codec has a limited buffer, so to prevent this buffer from running empty, we need a low read time. The isolated write and read times are ok, but when during seek, the time gets too high.

EDIT3:
The write speed is about 250Kbyte/s, and the read speed is 16Kbyte/s.


问:
relative path for rmarkdown template in shiny app
I'm generating a report in my shiny app using rmarkdown template.
I have a logo for the header which if I use the absolute path to the image, everything is fine :

```<code>---
title: "test"
date: "`r Sys.Date()`"
output:
  pdf_document :
  keep_tex: true
number_sections: true
params:
monthly_mean: NA
hourly_mean: NA
df: NA
pn: NA
in1: NA
in2: NA
header-includes:
\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\setlength\headheight{80.0pt}
\addtolength{\textheight}{-80.0pt}
\fancyhead[C]{\includegraphics[width=5cm]{/home/user/app/www/logo.png}}
\geometry{a4paper, left=2.3cm, right=2.3cm, top=3.3cm, bottom=2.7cm}
\fancyfoot[C]{\thepage}

---

\backgroundsetup{
    scale=1,
    color=black,
    opacity=0.9,
    angle=0,
    contents={
      \includegraphics[width=\paperwidth,height=\paperheight]{/home/user/app/www/WSTE1.pdf}
    }
</code>```

If I change the absolute path to www/logo.png and /www/WSTE1.pdf I'm getting error !
So I don't know how to define the path to be able to deploy the app to the server !

Body:
I'm generating a report in my shiny app using rmarkdown template.
I have a logo for the header which if I use the absolute path to the image, everything is fine :

---
title: "test"
date: "`r Sys.Date()`"
output:
  pdf_document :
  keep_tex: true
number_sections: true
params:
monthly_mean: NA
hourly_mean: NA
df: NA
pn: NA
in1: NA
in2: NA
header-includes:
\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\setlength\headheight{80.0pt}
\addtolength{\textheight}{-80.0pt}
\fancyhead[C]{\includegraphics[width=5cm]{/home/user/app/www/logo.png}}
\geometry{a4paper, left=2.3cm, right=2.3cm, top=3.3cm, bottom=2.7cm}
\fancyfoot[C]{\thepage}

---

\backgroundsetup{
    scale=1,
    color=black,
    opacity=0.9,
    angle=0,
    contents={
      \includegraphics[width=\paperwidth,height=\paperheight]{/home/user/app/www/WSTE1.pdf}
    }

If I change the absolute path to www/logo.png and /www/WSTE1.pdf I'm getting error !
So I don't know how to define the path to be able to deploy the app to the server !


问:
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). in methods
This is my code. i want to return

1 if 0 <= x <= 13

2 if 14 <= x <= 26

3 if 27 <= x <= 40

```<code>def get_part_b_values():
    x = (dataset['part_b_q1'].apply(part_b_values)
        + dataset['part_b_q2'].apply(part_b_values)
        + dataset['part_b_q3'].apply(part_b_values)
        + dataset['part_b_q4'].apply(part_b_values_reverse)
        + dataset['part_b_q5'].apply(part_b_values_reverse)
        + dataset['part_b_q6'].apply(part_b_values)
        + dataset['part_b_q7'].apply(part_b_values_reverse)
        + dataset['part_b_q8'].apply(part_b_values_reverse)
        + dataset['part_b_q9'].apply(part_b_values)
        + dataset['part_b_q10'].apply(part_b_values))
    if ((x>=0) & (x<=13)):
        return 1
    elif((x>=14) & (x<=26)):
        return 2
    else:
        return 3
</code>```

but when im running this code i got this error

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/ym/_wjy7pyj6zjdlnf94rq4grjr0000gn/T/ipykernel_1155/3542724477.py in <module>
----> 1 dataset['newCol'] = test()

/var/folders/ym/_wjy7pyj6zjdlnf94rq4grjr0000gn/T/ipykernel_1155/2427638497.py in test()
      1 def test():
----> 2     t = get_part_b_values()
      3     if (t.between(0,13)):
      4         return 1
      5     elif (t.between(14,27)):

/var/folders/ym/_wjy7pyj6zjdlnf94rq4grjr0000gn/T/ipykernel_1155/2029802580.py in get_part_b_values()
     12         + dataset['part_b_q9'].apply(part_b_values)
     13         + dataset['part_b_q10'].apply(part_b_values))
---> 14     if ((x>=0) & (x<=13)):
     15         return 1
     16     elif((x>=14) & (x<=26)):

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/generic.py in __nonzero__(self)
   1525     @final
   1526     def __nonzero__(self):
-> 1527         raise ValueError(
   1528             f"The truth value of a {type(self).__name__} is ambiguous. "
   1529             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

i tried to google. but i couldnt find a solution for this.

Body:
This is my code. i want to return

1 if 0 <= x <= 13

2 if 14 <= x <= 26

3 if 27 <= x <= 40

def get_part_b_values():
    x = (dataset['part_b_q1'].apply(part_b_values)
        + dataset['part_b_q2'].apply(part_b_values)
        + dataset['part_b_q3'].apply(part_b_values)
        + dataset['part_b_q4'].apply(part_b_values_reverse)
        + dataset['part_b_q5'].apply(part_b_values_reverse)
        + dataset['part_b_q6'].apply(part_b_values)
        + dataset['part_b_q7'].apply(part_b_values_reverse)
        + dataset['part_b_q8'].apply(part_b_values_reverse)
        + dataset['part_b_q9'].apply(part_b_values)
        + dataset['part_b_q10'].apply(part_b_values))
    if ((x>=0) & (x<=13)):
        return 1
    elif((x>=14) & (x<=26)):
        return 2
    else:
        return 3

but when im running this code i got this error

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/ym/_wjy7pyj6zjdlnf94rq4grjr0000gn/T/ipykernel_1155/3542724477.py in <module>
----> 1 dataset['newCol'] = test()

/var/folders/ym/_wjy7pyj6zjdlnf94rq4grjr0000gn/T/ipykernel_1155/2427638497.py in test()
      1 def test():
----> 2     t = get_part_b_values()
      3     if (t.between(0,13)):
      4         return 1
      5     elif (t.between(14,27)):

/var/folders/ym/_wjy7pyj6zjdlnf94rq4grjr0000gn/T/ipykernel_1155/2029802580.py in get_part_b_values()
     12         + dataset['part_b_q9'].apply(part_b_values)
     13         + dataset['part_b_q10'].apply(part_b_values))
---> 14     if ((x>=0) & (x<=13)):
     15         return 1
     16     elif((x>=14) & (x<=26)):

~/opt/anaconda3/lib/python3.9/site-packages/pandas/core/generic.py in __nonzero__(self)
   1525     @final
   1526     def __nonzero__(self):
-> 1527         raise ValueError(
   1528             f"The truth value of a {type(self).__name__} is ambiguous. "
   1529             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

i tried to google. but i couldnt find a solution for this.


问:
Failed to connect python and MySQL using Docker Compose
I am trying to connect to MySQL database using Docker Compose and I get the following error

```<code>Traceback (most recent call last):
|   File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 268, in _open_connection
|     self._cmysql.connect(**cnx_kwargs)
| _mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on '172.22.0.2:3306' (110)
|
| The above exception was the direct cause of the following exception:
| Traceback (most recent call last):
|   File "//script.py", line 19, in <module>
|     cnx = mysql.connector.connect(host='172.22.0.2', user='user', password='pass', database='db', port=3306)
|   File "/usr/local/lib/python3.9/site-packages/mysql/connector/pooling.py", line 286, in connect
|     return CMySQLConnection(*args, **kwargs)
|   File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 101, in __init__
|     self.connect(**kwargs)
|   File "/usr/local/lib/python3.9/site-packages/mysql/connector/abstracts.py", line 1108, in connect
|     self._open_connection()
|   File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 273, in _open_connection..
|     raise get_mysql_exception(mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '172.22.0.2:3306'
</code>```

In my programm I have to containers: for python script and for MySQL database. Both containers are built successfully and db container starts just fine.

172.22.0.2 stands for ip address in network I've created (see docker-compose).

My python script simply connects to the database using mysql-connector.

The code is the following

Dockerfile for script

```<code>FROM python:3.9

COPY script.py script.py
RUN pip install mysql-connector-python

</code>```

script.py

```<code>import mysql.connector

cnx = mysql.connector.connect(host='172.22.0.2', user='user', password='pass', database='db', port=3306)

</code>```

docker-compose.yaml

```<code>version: "3"
                                                                                services:
  db:
    image: mysql
    container_name: db
    command: '--init-file /data/app/init.sql'
    ports:
      - "3306:3306"
    volumes:
      - "./init.sql:/data/app/init.sql"
    environment:
      MYSQL_DATABASE: "db"
      MYSQL_USER: "user"
      MYSQL_PASSWORD: "pass"
      MYSQL_ROOT_PASSWORD: "pass"
    networks:
      net:
        ipv4_address: 172.22.0.2
  script:
    build:
      context: ./
      dockerfile: Dockerfile
    depends_on:
      - db
    links:
      - db
    container_name: script
    command: sh -c "sleep 10s ; python script.py"
    networks:
      net:
        ipv4_address: 172.22.0.3

networks:
  net:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.22.0.0/24
        gateway: 172.22.0.1

</code>```

init.sql

```<code>CREATE DATABASE IF NOT EXIST db;
USE db;
</code>```

Body:
I am trying to connect to MySQL database using Docker Compose and I get the following error

Traceback (most recent call last):
|   File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 268, in _open_connection
|     self._cmysql.connect(**cnx_kwargs)
| _mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on '172.22.0.2:3306' (110)
|
| The above exception was the direct cause of the following exception:
| Traceback (most recent call last):
|   File "//script.py", line 19, in <module>
|     cnx = mysql.connector.connect(host='172.22.0.2', user='user', password='pass', database='db', port=3306)
|   File "/usr/local/lib/python3.9/site-packages/mysql/connector/pooling.py", line 286, in connect
|     return CMySQLConnection(*args, **kwargs)
|   File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 101, in __init__
|     self.connect(**kwargs)
|   File "/usr/local/lib/python3.9/site-packages/mysql/connector/abstracts.py", line 1108, in connect
|     self._open_connection()
|   File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 273, in _open_connection..
|     raise get_mysql_exception(mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '172.22.0.2:3306'

In my programm I have to containers: for python script and for MySQL database. Both containers are built successfully and db container starts just fine.

172.22.0.2 stands for ip address in network I've created (see docker-compose).

My python script simply connects to the database using mysql-connector.

The code is the following

Dockerfile for script

FROM python:3.9

COPY script.py script.py
RUN pip install mysql-connector-python

script.py

import mysql.connector

cnx = mysql.connector.connect(host='172.22.0.2', user='user', password='pass', database='db', port=3306)

docker-compose.yaml

version: "3"
                                                                                services:
  db:
    image: mysql
    container_name: db
    command: '--init-file /data/app/init.sql'
    ports:
      - "3306:3306"
    volumes:
      - "./init.sql:/data/app/init.sql"
    environment:
      MYSQL_DATABASE: "db"
      MYSQL_USER: "user"
      MYSQL_PASSWORD: "pass"
      MYSQL_ROOT_PASSWORD: "pass"
    networks:
      net:
        ipv4_address: 172.22.0.2
  script:
    build:
      context: ./
      dockerfile: Dockerfile
    depends_on:
      - db
    links:
      - db
    container_name: script
    command: sh -c "sleep 10s ; python script.py"
    networks:
      net:
        ipv4_address: 172.22.0.3

networks:
  net:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.22.0.0/24
        gateway: 172.22.0.1

init.sql

CREATE DATABASE IF NOT EXIST db;
USE db;


问:
Bluetooth Core v5.3 Set Extended Advertising Data Command
I'm trying to re-implement HCITool functions in my application. Currently trying to get the command "cmd" working so that I can set extended advertising data which will hold manufacturer data.

My first approach was to see how HCITool registers the command and so I came up with this:

```<code>hcitool -i hci0 cmd 0x08 0x0037 01 03 01 0C FFFF 12 34
</code>```

I also tried it this way:

```<code>hcitool -i hci0 cmd 0x08 0x0037 01 03 01 0C FF FF 12 34
</code>```

These gave me error code 1, which is saying the command doesn't exist so I'm guessing I didn't write it correctly. My first request is if anyone can explain how to correctly send this command in HCITool.

The following is how I am trying to implment it in my code. This code is just a lightly altered version of open source HCITool's approach.

```<code>static void cmd_manufacturer(int dev_id)
{
    unsigned char buf[HCI_MAX_EVENT_SIZE], *ptr = buf;
    struct hci_filter flt;
    hci_event_hdr *hdr;
    int i, opt, len, dd;
    uint16_t ocf;
    uint8_t ogf;
    char arr[][20] = {"0xFFFF", "0x12", "0x34"};

    if (dev_id < 0)
        dev_id = hci_get_route(NULL);

    errno = 0;
    ogf = strtol("0x08", NULL, 16);
    ocf = strtol("0x0037", NULL, 16);
    if (errno == ERANGE || (ogf > 0x3f) || (ocf > 0x3ff))
    {
        return;
    }

    for (i = 2, len = 0; i < 12 && len < (int) sizeof(buf); i++, len++)
    {
        *ptr++ = (uint8_t) strtol(arr[i], NULL, 16);
    }

    dd = hci_open_dev(dev_id);
    if (dd < 0) {
        perror("Device open failed");
        exit(EXIT_FAILURE);
    }

    /* Setup filter */
    hci_filter_clear(&flt);
    hci_filter_set_ptype(HCI_EVENT_PKT, &flt);
    hci_filter_all_events(&flt);
    if (setsockopt(dd, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0) {
        perror("HCI filter setup failed");
        exit(EXIT_FAILURE);
    }

    printf("< HCI Command: ogf 0x%02x, ocf 0x%04x, plen %d\n", ogf, ocf, len);

    if (hci_send_cmd(dd, ogf, ocf, len, buf) < 0) {
        perror("Send failed");
        exit(EXIT_FAILURE);
    }

    len = read(dd, buf, sizeof(buf));
    if (len < 0) {
        perror("Read failed");
        exit(EXIT_FAILURE);
    }

    hdr = (void *)(buf + 1);
    ptr = buf + (1 + HCI_EVENT_HDR_SIZE);
    len -= (1 + HCI_EVENT_HDR_SIZE);

    printf("> HCI Event: 0x%02x plen %d\n", hdr->evt, hdr->plen);

    hci_close_dev(dd);
}
</code>```

I run my application, turn advertising on and am using btmon to see the HCI events/commands. Btmon doesn't show my extended advertising data being set.

Anyone have any idea on what I can do to make this work? I think I'm not providing the data correctly to the function.

Thank you for the help.

Body:
I'm trying to re-implement HCITool functions in my application. Currently trying to get the command "cmd" working so that I can set extended advertising data which will hold manufacturer data.

My first approach was to see how HCITool registers the command and so I came up with this:

hcitool -i hci0 cmd 0x08 0x0037 01 03 01 0C FFFF 12 34

I also tried it this way:

hcitool -i hci0 cmd 0x08 0x0037 01 03 01 0C FF FF 12 34

These gave me error code 1, which is saying the command doesn't exist so I'm guessing I didn't write it correctly. My first request is if anyone can explain how to correctly send this command in HCITool.

The following is how I am trying to implment it in my code. This code is just a lightly altered version of open source HCITool's approach.

static void cmd_manufacturer(int dev_id)
{
    unsigned char buf[HCI_MAX_EVENT_SIZE], *ptr = buf;
    struct hci_filter flt;
    hci_event_hdr *hdr;
    int i, opt, len, dd;
    uint16_t ocf;
    uint8_t ogf;
    char arr[][20] = {"0xFFFF", "0x12", "0x34"};

    if (dev_id < 0)
        dev_id = hci_get_route(NULL);

    errno = 0;
    ogf = strtol("0x08", NULL, 16);
    ocf = strtol("0x0037", NULL, 16);
    if (errno == ERANGE || (ogf > 0x3f) || (ocf > 0x3ff))
    {
        return;
    }

    for (i = 2, len = 0; i < 12 && len < (int) sizeof(buf); i++, len++)
    {
        *ptr++ = (uint8_t) strtol(arr[i], NULL, 16);
    }

    dd = hci_open_dev(dev_id);
    if (dd < 0) {
        perror("Device open failed");
        exit(EXIT_FAILURE);
    }

    /* Setup filter */
    hci_filter_clear(&flt);
    hci_filter_set_ptype(HCI_EVENT_PKT, &flt);
    hci_filter_all_events(&flt);
    if (setsockopt(dd, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0) {
        perror("HCI filter setup failed");
        exit(EXIT_FAILURE);
    }

    printf("< HCI Command: ogf 0x%02x, ocf 0x%04x, plen %d\n", ogf, ocf, len);

    if (hci_send_cmd(dd, ogf, ocf, len, buf) < 0) {
        perror("Send failed");
        exit(EXIT_FAILURE);
    }

    len = read(dd, buf, sizeof(buf));
    if (len < 0) {
        perror("Read failed");
        exit(EXIT_FAILURE);
    }

    hdr = (void *)(buf + 1);
    ptr = buf + (1 + HCI_EVENT_HDR_SIZE);
    len -= (1 + HCI_EVENT_HDR_SIZE);

    printf("> HCI Event: 0x%02x plen %d\n", hdr->evt, hdr->plen);

    hci_close_dev(dd);
}

I run my application, turn advertising on and am using btmon to see the HCI events/commands. Btmon doesn't show my extended advertising data being set.

Anyone have any idea on what I can do to make this work? I think I'm not providing the data correctly to the function.

Thank you for the help.


问:
Lua - Match pattern for CSV import to array, that factors in empty values (two commas next to each other)
I have been using the following Lua code for a while to do simply csv to array conversions, but everything previously had a value in every column, but this time on a csv formatted bank statement there are empty values, which this does not handle.

Here’s an example csv, with debit and credits.

```<code>Transaction Date,Transaction Type,Sort Code,Account Number,Transaction Description,Debit Amount,Credit Amount,Balance
05/04/2022,DD,'11-70-79,6033606,Refund,,10.00,159.57
05/04/2022,DEB,'11-70-79,6033606,Henry Ltd,30.00,,149.57
05/04/2022,SO,'11-70-79,6033606,NEIL PARKS,20.00,,179.57
01/04/2022,FPO,'11-70-79,6033606,MORTON GREEN,336.00,,199.57
01/04/2022,DD,'11-70-79,6033606,WORK SALARY,,100.00,435.57
01/04/2022,DD,'11-70-79,6033606,MERE BC,183.63,,535.57
01/04/2022,DD,'11-70-79,6033606,ABC LIFE,54.39,,719.20
</code>```

I’ve tried different patterns (https://www.lua.org/pil/20.2.html), but none seem to work, I’m beginning to think I can’t fix this via the pattern as it’ll break how it works for the rest? I appreciate it if anyone can share how they would approach this…

```<code>local csvfilename = "/mnt/nas/Fireflyiii.csv"
local MATCH_PATTERN = "[^,]+"

local function create_array_from_file(csvfilename)
    local file = assert(io.open(csvfilename, "r"))
    local arr = {}
    for line in file:lines() do
        local row = {}
        for match in string.gmatch(line, MATCH_PATTERN) do
            table.insert(row, match)
        end
        table.insert(arr, row)
    end
    return arr
end
</code>```

Body:
I have been using the following Lua code for a while to do simply csv to array conversions, but everything previously had a value in every column, but this time on a csv formatted bank statement there are empty values, which this does not handle.

Here’s an example csv, with debit and credits.

Transaction Date,Transaction Type,Sort Code,Account Number,Transaction Description,Debit Amount,Credit Amount,Balance
05/04/2022,DD,'11-70-79,6033606,Refund,,10.00,159.57
05/04/2022,DEB,'11-70-79,6033606,Henry Ltd,30.00,,149.57
05/04/2022,SO,'11-70-79,6033606,NEIL PARKS,20.00,,179.57
01/04/2022,FPO,'11-70-79,6033606,MORTON GREEN,336.00,,199.57
01/04/2022,DD,'11-70-79,6033606,WORK SALARY,,100.00,435.57
01/04/2022,DD,'11-70-79,6033606,MERE BC,183.63,,535.57
01/04/2022,DD,'11-70-79,6033606,ABC LIFE,54.39,,719.20

I’ve tried different patterns (https://www.lua.org/pil/20.2.html), but none seem to work, I’m beginning to think I can’t fix this via the pattern as it’ll break how it works for the rest? I appreciate it if anyone can share how they would approach this…

local csvfilename = "/mnt/nas/Fireflyiii.csv"
local MATCH_PATTERN = "[^,]+"

local function create_array_from_file(csvfilename)
    local file = assert(io.open(csvfilename, "r"))
    local arr = {}
    for line in file:lines() do
        local row = {}
        for match in string.gmatch(line, MATCH_PATTERN) do
            table.insert(row, match)
        end
        table.insert(arr, row)
    end
    return arr
end


问:
Expected mean of correlated data in python
I have successfully generated three correlated random variables with Cholesky. I use the same mean(10) and the same standard deviation(5) for all of them. However, I tried to calculate the expected mean of the correlated variables, but I got some an unpleasant results I can't seem to know where exactly the problem. Please here is a working code:

```<code>import numpy as np
import pandas as pd
corr = np.array([[1,0.7,0.7], [0.7,1,0.7],[0.7,0.7,1]])
chol = np.linalg.cholesky(corr)
N=1000
rand_data = np.random.normal(10, 5, size=(3,N))

# generate uncorrelated data
uncorrelated_data = pd.DataFrame(rand_data, index=['A','B','C']).T/100
uncorrelated_data.corr()     # shows barely any correlation as it should
uncorrelated_data.mean()*100 # shows each mean around 10
</code>```

Output

```<code>A    10.308595
B     9.931958
C    10.165347
</code>```

Generating correlation among them

```<code>x = np.dot(chol, rand_data)     # cholesky
correlated_data = pd.DataFrame(x, index=['A','B','C']).T/100
print(correlated_data.corr()) # shows there are correlations among variable
sim_corr_rets.mean()*100      # mean keep increasing in across the variables
</code>```

Output:

```<code> A    10.308595
 B    14.308853
 C    16.752117
</code>```

The means of the uncorrelated variables were as expected but the mean of the correlated variables keeps increasing from the first variable to the last variable. My expectation is that each mean will be around the actual mean. Please could my noble seniors help me figure out the problem or suggest an alternative solution?

Body:
I have successfully generated three correlated random variables with Cholesky. I use the same mean(10) and the same standard deviation(5) for all of them. However, I tried to calculate the expected mean of the correlated variables, but I got some an unpleasant results I can't seem to know where exactly the problem. Please here is a working code:

import numpy as np
import pandas as pd
corr = np.array([[1,0.7,0.7], [0.7,1,0.7],[0.7,0.7,1]])
chol = np.linalg.cholesky(corr)
N=1000
rand_data = np.random.normal(10, 5, size=(3,N))

# generate uncorrelated data
uncorrelated_data = pd.DataFrame(rand_data, index=['A','B','C']).T/100
uncorrelated_data.corr()     # shows barely any correlation as it should
uncorrelated_data.mean()*100 # shows each mean around 10

Output

A    10.308595
B     9.931958
C    10.165347

Generating correlation among them

x = np.dot(chol, rand_data)     # cholesky
correlated_data = pd.DataFrame(x, index=['A','B','C']).T/100
print(correlated_data.corr()) # shows there are correlations among variable
sim_corr_rets.mean()*100      # mean keep increasing in across the variables

Output:

 A    10.308595
 B    14.308853
 C    16.752117

The means of the uncorrelated variables were as expected but the mean of the correlated variables keeps increasing from the first variable to the last variable. My expectation is that each mean will be around the actual mean. Please could my noble seniors help me figure out the problem or suggest an alternative solution?


问:
Using DockPanelSuite, how do you get context menu for tab strip separate from document tab?
When using DockPanelSuite, is it possible to have a context menu for the tab strip that is different from the one for a document tab? For example, right click an empty space on the tab strip and get one context menu then right click a document tab and get a different context menu specific to the document.

I tried setting the ContextMenuStrip property of the DockPanel. I got a context menu for any empty space on the DockPanel control as well as the document tab strip when visible and all open document tabs. That's a good start but I really only wanted the context menu for the tab strip. Not the main control or any tabs.

I also followed along with the sample project to make a context menu for the document by setting the TabPageContextMenuStrip property of the DockContent form. I discovered that you get a document specific context menu by right clicking the document tab, but it also overrides the DockPanel's ContextMenuStrip. While that is useful, it's still not the desired result.

Edit:
Updating this post in case anyone else is interested in achieving the objective of the question.
After much source code analysis and testing, I concluded that the objective could not be achieved using the available public Properties, Methods, and Events. However, we can achieve the goal by using a bit of reflection.

Discoveries:

```<code>DockContent.ContextMenuStrip
</code>```

This property does nothing for the DockPanel. It will provide a context menu in the client area of the document. However, for some reason, the RichTextBox control set to Fill in the provided sample blocks the context menu from popping up.

```<code>DockContent.TabPageContextMenuStrip
</code>```

This property causes the associated ContextMenuStrip to display when the document is active. However, it displays when you right click anywhere on the tab strip, not just when you right click the document tab.

Solution:

First, add a public property to the DockContent form which will contain a reference to the context menu.

```<code>public ContextMenuStrip TabContextMenu { get { return contextMenuTabPage; } }
</code>```

Next, add an event handler in the MDI main form for the DockPanel.ActiveDocmentChanged event. This will be used to add an event handler to the tab strip after it’s been created.

```<code>this.dockPanel.ActiveDocumentChanged += new System.EventHandler(this.dockPanel_ActiveDocumentChanged);

private void dockPanel_ActiveDocumentChanged(object sender, EventArgs e)
{
  // Hook into the document pane tabstrip mouse up event
  // if we haven't already.
  if (dockPanel.ActiveDocumentPane != null
    && dockPanel.ActiveDocumentPane.TabStripControl != null
    && dockPanel.ActiveDocumentPane.TabStripControl.Tag == null)
  {
  dockPanel.ActiveDocumentPane.TabStripControl.Tag = "MouseUp Hooked";
  dockPanel.ActiveDocumentPane.TabStripControl.MouseUp +=
  TabStripControl_MouseUp;
  }
}
</code>```

Finally, add the event handler for the TabStripControl.

```<code>private void TabStripControl_MouseUp(object sender, MouseEventArgs e)
{
  // Capture right click action
  if (e.Button == MouseButtons.Right)
  {
    ContextMenuStrip menu = contextMenuDocumentPane;
    Point screenPos = Cursor.Position;
    Point tabstripsPos = dockPanel.ActiveDocumentPane
      .TabStripControl.PointToClient(screenPos);

    // Determine if cursor is over a tab
    var tabstrip = dockPanel.ActiveDocumentPane.TabStripControl;
    var tabs = tabstrip.GetType()
      .GetProperty("Tabs", BindingFlags.Instance |
      BindingFlags.NonPublic).GetValue(tabstrip);
    foreach (var tab in (IEnumerable)tabs)
    {
      var bounds = tab.GetType()
        .GetProperty("Rectangle")
        .GetValue(tab);
      if (((Rectangle)bounds).Contains(tabstripsPos))
      {
        // Display context menu for this document tab
        var document = tab.GetType()
          .GetProperty("Content")
          .GetValue(tab);
        menu = ((ContentWindow)document).TabContextMenu;
      }
    }

    // Show appropriate context menu
    menu.Show(screenPos);
  }
}
</code>```

Body:
When using DockPanelSuite, is it possible to have a context menu for the tab strip that is different from the one for a document tab? For example, right click an empty space on the tab strip and get one context menu then right click a document tab and get a different context menu specific to the document.

I tried setting the ContextMenuStrip property of the DockPanel. I got a context menu for any empty space on the DockPanel control as well as the document tab strip when visible and all open document tabs. That's a good start but I really only wanted the context menu for the tab strip. Not the main control or any tabs.

I also followed along with the sample project to make a context menu for the document by setting the TabPageContextMenuStrip property of the DockContent form. I discovered that you get a document specific context menu by right clicking the document tab, but it also overrides the DockPanel's ContextMenuStrip. While that is useful, it's still not the desired result.

Edit:
Updating this post in case anyone else is interested in achieving the objective of the question.
After much source code analysis and testing, I concluded that the objective could not be achieved using the available public Properties, Methods, and Events. However, we can achieve the goal by using a bit of reflection.

Discoveries:

DockContent.ContextMenuStrip

This property does nothing for the DockPanel. It will provide a context menu in the client area of the document. However, for some reason, the RichTextBox control set to Fill in the provided sample blocks the context menu from popping up.

DockContent.TabPageContextMenuStrip

This property causes the associated ContextMenuStrip to display when the document is active. However, it displays when you right click anywhere on the tab strip, not just when you right click the document tab.

Solution:

First, add a public property to the DockContent form which will contain a reference to the context menu.

public ContextMenuStrip TabContextMenu { get { return contextMenuTabPage; } }

Next, add an event handler in the MDI main form for the DockPanel.ActiveDocmentChanged event. This will be used to add an event handler to the tab strip after it’s been created.

this.dockPanel.ActiveDocumentChanged += new System.EventHandler(this.dockPanel_ActiveDocumentChanged);

private void dockPanel_ActiveDocumentChanged(object sender, EventArgs e)
{
  // Hook into the document pane tabstrip mouse up event
  // if we haven't already.
  if (dockPanel.ActiveDocumentPane != null
    && dockPanel.ActiveDocumentPane.TabStripControl != null
    && dockPanel.ActiveDocumentPane.TabStripControl.Tag == null)
  {
  dockPanel.ActiveDocumentPane.TabStripControl.Tag = "MouseUp Hooked";
  dockPanel.ActiveDocumentPane.TabStripControl.MouseUp +=
  TabStripControl_MouseUp;
  }
}

Finally, add the event handler for the TabStripControl.

private void TabStripControl_MouseUp(object sender, MouseEventArgs e)
{
  // Capture right click action
  if (e.Button == MouseButtons.Right)
  {
    ContextMenuStrip menu = contextMenuDocumentPane;
    Point screenPos = Cursor.Position;
    Point tabstripsPos = dockPanel.ActiveDocumentPane
      .TabStripControl.PointToClient(screenPos);

    // Determine if cursor is over a tab
    var tabstrip = dockPanel.ActiveDocumentPane.TabStripControl;
    var tabs = tabstrip.GetType()
      .GetProperty("Tabs", BindingFlags.Instance |
      BindingFlags.NonPublic).GetValue(tabstrip);
    foreach (var tab in (IEnumerable)tabs)
    {
      var bounds = tab.GetType()
        .GetProperty("Rectangle")
        .GetValue(tab);
      if (((Rectangle)bounds).Contains(tabstripsPos))
      {
        // Display context menu for this document tab
        var document = tab.GetType()
          .GetProperty("Content")
          .GetValue(tab);
        menu = ((ContentWindow)document).TabContextMenu;
      }
    }

    // Show appropriate context menu
    menu.Show(screenPos);
  }
}


问:
Some devices cannot connect to socket on [iOS,Android] both devices
I've developed an app with flutter. Socket is working perfectly. However, I realized that some devices cannot connect to Socket.
I was searching about this issues but i found nothing. Do you have any idea about this problem?
I couldn't debug devices which cannot connect to socket, I'll do it soon and let you know it.

Nodejs server v4.5.5, flutter client 2.0.0

If you had this issue before please let me know. Thank you

I tried same iOS version and iPhone model.

One of them connected successfully but other couldn't connect.


问:
Getting ESLint to FormatOnSave WITHOUT using Prettier in Next.js app
I had followed the NextJS documentation to install ESLint and Prettier in my NextJS app for VS Code. It was fine until I kept running into this problem (which is annoying):

React/NextJS {" "} before an element

The above issue was intermittent and annoying so I am uncoupling Prettier out of my app.

Now I am having trouble making everything work without Prettier and using .tsx / TypeScript files for my project.

The steps I have done are:

Remove the Prettier plugin.

Reinstall and upgrade the ESLint plugin.

Add the following to the settings.json file for VSCode.

```<code>{
    "eslint.format.enable": true,
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true}
 }
</code>```

I do not see an eslintrc.js/json file but only a eslintrc.cjs file in my node_modules of the app.

What am I missing as all the docs I find involve Prettier installations as well (I wish I had a way to use Prettier without the {" "} issue)?

Body:
I had followed the NextJS documentation to install ESLint and Prettier in my NextJS app for VS Code. It was fine until I kept running into this problem (which is annoying):

React/NextJS {" "} before an element

The above issue was intermittent and annoying so I am uncoupling Prettier out of my app.

Now I am having trouble making everything work without Prettier and using .tsx / TypeScript files for my project.

The steps I have done are:

Remove the Prettier plugin.

Reinstall and upgrade the ESLint plugin.

Add the following to the settings.json file for VSCode.

{
    "eslint.format.enable": true,
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true}
 }

I do not see an eslintrc.js/json file but only a eslintrc.cjs file in my node_modules of the app.

What am I missing as all the docs I find involve Prettier installations as well (I wish I had a way to use Prettier without the {" "} issue)?


问:
How do I access useAccordion methods and properties? (ChakraUI React Hook)
I have a ChakraUI accordion that I need to manually change the open index based on section name/id, since elements are hidden/shown depending on view/edit state, and this is causing the open index to open the wrong panel when switching state.

I see the useAccordion hook in their code, but I don't understand why it takes accordion props, which I declare in  (allowToggle, allowMultiple, etc).

Wouldn't the hook want a ref or ID? I'm confused on how this hook and the JSK element connect.

useAccordion looks like this:

```<code>declare function useAccordion(props: UseAccordionProps): {
  index: ExpandedIndex;
  setIndex: react.Dispatch<react.SetStateAction<ExpandedIndex>>;
  htmlProps: {};
  getAccordionItemProps: (idx: number | null) => {
    isOpen: boolean;
    onChange: (isOpen: boolean) => void;
  };
  focusedIndex: number;
  setFocusedIndex: react.Dispatch<react.SetStateAction<number>>;
  descendants: _chakra_ui_descendant.DescendantsManager<HTMLButtonElement, {}>;
};
</code>```

I was thinking it should look like:

```<code>const {index, setIndex, htmlProps} = useAccordion(ref)
</code>```

But that goes against their type defs. Maybe I'm missing something about hooks? Thanks in advance.

Body:
I have a ChakraUI accordion that I need to manually change the open index based on section name/id, since elements are hidden/shown depending on view/edit state, and this is causing the open index to open the wrong panel when switching state.

I see the useAccordion hook in their code, but I don't understand why it takes accordion props, which I declare in  (allowToggle, allowMultiple, etc).

Wouldn't the hook want a ref or ID? I'm confused on how this hook and the JSK element connect.

useAccordion looks like this:

declare function useAccordion(props: UseAccordionProps): {
  index: ExpandedIndex;
  setIndex: react.Dispatch<react.SetStateAction<ExpandedIndex>>;
  htmlProps: {};
  getAccordionItemProps: (idx: number | null) => {
    isOpen: boolean;
    onChange: (isOpen: boolean) => void;
  };
  focusedIndex: number;
  setFocusedIndex: react.Dispatch<react.SetStateAction<number>>;
  descendants: _chakra_ui_descendant.DescendantsManager<HTMLButtonElement, {}>;
};

I was thinking it should look like:

const {index, setIndex, htmlProps} = useAccordion(ref)

But that goes against their type defs. Maybe I'm missing something about hooks? Thanks in advance.


问:
Running Nestjs And Postgres On Docker 127.0.0.1 Error
I'm new at Docker. I'm trying to run my postgres and nestjs app on docker. They work correctly but I guess they nestjs can't access to postgres container.

docker-compose.yaml - docker-compose up --build

```<code>version: '3.5'

services:
  postgres:
    container_name: postgres_container
    image: postgres
    environment:
      POSTGRES_USER: Sol
      POSTGRES_PASSWORD: 1234
      PGDATA: /data/postgres
      POSTGRES_DB: gamalol
    volumes:
       - ./postgres:/data/postgres
    ports:
      - "4321:5432"
    networks:
      - postgres
    restart: unless-stopped

  pgadmin:
    container_name: pgadmin_container
    image: dpage/pgadmin4
    environment:
      PGADMIN_DEFAULT_EMAIL: gama@lol.com
      PGADMIN_DEFAULT_PASSWORD: 1234
      PGADMIN_CONFIG_SERVER_MODE: 'False'
    volumes:
       - ./pgadmin:/var/lib/pgadmin
    depends_on:
      - postgres

    ports:
      - "5050:80"
    networks:
      - postgres
    restart: unless-stopped

networks:
  postgres:
    driver: bridge

volumes:
    postgres:
    pgadmin:
</code>```

app.module.ts - docker run -d --network=host -p 3000:3000 prj:latest

```<code>    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'postgres_container',
      port: 5432,
      username: 'Lenovo',
      password: '1234',
      database: 'gamalol',
      autoLoadEntities: true,
      synchronize: true,
    }),
</code>```

Error:

```<code>[Nest] 1  - 01/03/2023, 9:38:07 PM   ERROR [ExceptionHandler] connect ECONNREFUSED 127.0.0.1:5432
Error: connect ECONNREFUSED 127.0.0.1:5432
</code>```

I guess postgres working on 0.0.0.0:5432 but nestjs trying to connect at 127.0.0.1:5432. I tried to change host and port from app.module.ts but didn't work.

Body:
I'm new at Docker. I'm trying to run my postgres and nestjs app on docker. They work correctly but I guess they nestjs can't access to postgres container.

docker-compose.yaml - docker-compose up --build

version: '3.5'

services:
  postgres:
    container_name: postgres_container
    image: postgres
    environment:
      POSTGRES_USER: Sol
      POSTGRES_PASSWORD: 1234
      PGDATA: /data/postgres
      POSTGRES_DB: gamalol
    volumes:
       - ./postgres:/data/postgres
    ports:
      - "4321:5432"
    networks:
      - postgres
    restart: unless-stopped

  pgadmin:
    container_name: pgadmin_container
    image: dpage/pgadmin4
    environment:
      PGADMIN_DEFAULT_EMAIL: gama@lol.com
      PGADMIN_DEFAULT_PASSWORD: 1234
      PGADMIN_CONFIG_SERVER_MODE: 'False'
    volumes:
       - ./pgadmin:/var/lib/pgadmin
    depends_on:
      - postgres

    ports:
      - "5050:80"
    networks:
      - postgres
    restart: unless-stopped

networks:
  postgres:
    driver: bridge

volumes:
    postgres:
    pgadmin:

app.module.ts - docker run -d --network=host -p 3000:3000 prj:latest

    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'postgres_container',
      port: 5432,
      username: 'Lenovo',
      password: '1234',
      database: 'gamalol',
      autoLoadEntities: true,
      synchronize: true,
    }),

Error:

[Nest] 1  - 01/03/2023, 9:38:07 PM   ERROR [ExceptionHandler] connect ECONNREFUSED 127.0.0.1:5432
Error: connect ECONNREFUSED 127.0.0.1:5432

I guess postgres working on 0.0.0.0:5432 but nestjs trying to connect at 127.0.0.1:5432. I tried to change host and port from app.module.ts but didn't work.


问:
PublishAsync method of MQTTNet client hangs forever when calling wait during internet disconnection
I am using the mqttnet client in a sync way. Meaning that I am waiting for the result every time I am calling the publish async method.

the tread context is neither from UI nor from a MVC controller.

In fact I am creating a task using a BlockingCollection,

The blocking collection is called this way:

```<code>            foreach (var action in ActionBuffer.GetConsumingEnumerable(_cancellationToken.Token))
            {
                try
                {
                    if (res)
                    {
                        action.Invoke();
                    }
                }
                catch (Exception exception)
                {
                }
            }
</code>```

the blocking collection is triggered from its own task

Task.Run(CallGetConsuming);

The action itself will simply call the mqttNet publishAsync method

```<code>var mqttApplicationMessage = new MqttApplicationMessageBuilder()
                        .WithTopic(mqttMessage.Topic)
                        .WithPayload(mqttMessage.Payload)

        .WithQualityOfServiceLevel((MqttQualityOfServiceLevel)mqttMessage.Qos)
                        .Build();
        var task = _client.PublishAsync(mqttApplicationMessage);
        TaskUtil.WaitForSendingTask(task);
</code>```

the waitforSending is just a normal task.wait.

Everything is working completely fine however when I am having some disconnection issue. Sometimes the wait method is hanging forever, I am on able to explain why. Is it an issue from the mqttnet library?

Note that I can reproduce it easily by calling disconnecting my internet connection while publishing a MQTT message.

I am using the version

MQTTnet.Extensions.ManagedClient

4.1.0.247

Any Idea,
Thanks in advance,
hak

Body:
I am using the mqttnet client in a sync way. Meaning that I am waiting for the result every time I am calling the publish async method.

the tread context is neither from UI nor from a MVC controller.

In fact I am creating a task using a BlockingCollection,

The blocking collection is called this way:

            foreach (var action in ActionBuffer.GetConsumingEnumerable(_cancellationToken.Token))
            {
                try
                {
                    if (res)
                    {
                        action.Invoke();
                    }
                }
                catch (Exception exception)
                {
                }
            }

the blocking collection is triggered from its own task

Task.Run(CallGetConsuming);

The action itself will simply call the mqttNet publishAsync method

var mqttApplicationMessage = new MqttApplicationMessageBuilder()
                        .WithTopic(mqttMessage.Topic)
                        .WithPayload(mqttMessage.Payload)

        .WithQualityOfServiceLevel((MqttQualityOfServiceLevel)mqttMessage.Qos)
                        .Build();
        var task = _client.PublishAsync(mqttApplicationMessage);
        TaskUtil.WaitForSendingTask(task);

the waitforSending is just a normal task.wait.

Everything is working completely fine however when I am having some disconnection issue. Sometimes the wait method is hanging forever, I am on able to explain why. Is it an issue from the mqttnet library?

Note that I can reproduce it easily by calling disconnecting my internet connection while publishing a MQTT message.

I am using the version

MQTTnet.Extensions.ManagedClient

4.1.0.247

Any Idea,
Thanks in advance,
hak


问:
Copy Dynamic Range Defined by String Values
I am trying to figure out how to copy values from a range of cells starting from one text string to another using Office-Scripts.

For example I would like to copy:

```<code>Name of Owner //Starting String
row 1
row 2
row 3
row n
Total Amount Owed //Ending String
</code>```

And paste these rows in a second sheet.

I believe I can find the first string with something like this:

```<code>usedRange.find("Name of Owner", {
{ completeMatch: true, matchCase: false, searchDirection: ExcelScript.SearchDirection.forward });

</code>```

But how do I then define the rest of the range in between this string and the ending string (as the specific cell that will contain the ending string will vary)? If someone could point me in the right direction I'd greatly appreciate it!

Body:
I am trying to figure out how to copy values from a range of cells starting from one text string to another using Office-Scripts.

For example I would like to copy:

Name of Owner //Starting String
row 1
row 2
row 3
row n
Total Amount Owed //Ending String

And paste these rows in a second sheet.

I believe I can find the first string with something like this:

usedRange.find("Name of Owner", {
{ completeMatch: true, matchCase: false, searchDirection: ExcelScript.SearchDirection.forward });

But how do I then define the rest of the range in between this string and the ending string (as the specific cell that will contain the ending string will vary)? If someone could point me in the right direction I'd greatly appreciate it!


问:
Changing how fast time passes in-game
As a first step into working with AzerothCore, I want to dehardcode a setting I'm modifying quite often, as it involves recompiling the core every single time I adjust the float value.

In player.cpp, in the function void Player::SendInitialPacketsBeforeAddToMap(), data << float(0.01666667f);. That value sets how fast the in-game time of day is. But that value is typically used in games to set engine tick rates to 60fps.

That doesn't seem good to increase; if I want to make it so that 1 minute real time = 20 minutes in-game (full 24 hour cycle takes 72 minutes, same as Skyrim), I'll have to lower that value by 20x, so there's 20x as many ticks.

What's the best way of changing the time speed? Affecting the tick rate seems like the wrong way to do it (if that is a tick rate value, that is)

Title: Changing how fast time passes in-game


问:
Windows programming and key events: ALT key sound effect
Is there any way to prevent Windows from playing that annoying sound effect when the alt key is pressed in an app that doesn't make use of it?

My app is a 3D desktop C++ game that uses WM_CHAR and Direct Input (API needs upgraded) to make use of the ALT key. I am actually using the ALT+* commands in my program, but Windows has no way of knowing that. Is there any way to inform it so, to make it stop playing the sound effect?

Apologies if this has been asked before. I searched, but found nothing. I'm looking for a way to disable it within my program, rather than asking all of my users to disable the sound, for example.

Edit: After some research, it appears that handling WM_SYSCHAR will stop Windows from playing sounds, but it also blocks all of the standard windows functionality, such as ALT+F4 (Alt+Tab still works). I'm not a fan of this, so hoping someone knows of a simple method to stop the sound alone. I can manually handle ALT+F4, but can't imagine what other commands I'm likely blocking.


问:
Config service vs Feature service vs AB test
I had a long argument with my peers on the difference between the three ways of doing canary releases. I know there are more but the current set in question are these three below

Config service

Feature service

AB testing

Following are the doubts

Can someone help me understand why a config service can/cannot be used as a feature service?

if someone pre-fixes the userIDs participating in the A and B cohorts, will it still qualify as an AB test? My understanding has been that the cohorts must be randomly chosen to remove bias while I am being told that it’s just one of the strategies

To some, it may seem all of this is just nomenclature but names are important. They anchor concepts.

It would also be great if someone can refer to me the right literature so that me and my peers can read it and improve our understanding.


问:
How to obtain proper state estimates at new times from a smoothed Kalman Filter track?
Suppose I have a fully processed track created by a Kalman Filter with smoothing (say RTS).  So I have means and covariances at specified times.  I no longer have access to the original observables.

Is there a way to obtain proper state estimates at times not in the provided track? Specifically, if I know the motion model used in the original tracking, can I obtain an estimate at an "in-between" time that is the same as would have been obtained if the original track/smooth process had included an estimate at that time?  If so, how?

I know I can do approximations by simple interpolation, or by picking the closest estimate and projecting it in time, but I'd like to do it properly if possible.


问:
How to calculate the time difference between each timestep in Python
I have a dataframe index by seconds. I want to create a new column dTime that shows the change in time from Time T and T-1 in seconds. I tried df["dTime"].total_seconds(), however, I get an attribute error "'Series' object has no attribute 'total_seconds'".

```<code>data = ["prod.dat")]
df = pd.DataFrame(index=read_dat(data[0], header_lines=3).index.values)
df["dTime"] = pd.to_timedelta(df.index, unit='s')
df
Time        Prod        dTime
662558400   1.975595    7668 days 12:00:10
662558400   1.975916    7668 days 12:00:25
662558400   1.976396    7668 days 12:00:47.500000
662558500   1.977118    7668 days 12:01:21.250000
66258500    1.9782  7668 days 12:02:11.879999995
</code>```

In this example above I would want the change in time seconds

```<code>Time        Prod        dTime
662558400   1.975595    0
662558400   1.975916    0
662558400   1.976396    0
662558500   1.977118    100
66258500    1.9782  0
</code>```

Body:
I have a dataframe index by seconds. I want to create a new column dTime that shows the change in time from Time T and T-1 in seconds. I tried df["dTime"].total_seconds(), however, I get an attribute error "'Series' object has no attribute 'total_seconds'".

data = ["prod.dat")]
df = pd.DataFrame(index=read_dat(data[0], header_lines=3).index.values)
df["dTime"] = pd.to_timedelta(df.index, unit='s')
df
Time        Prod        dTime
662558400   1.975595    7668 days 12:00:10
662558400   1.975916    7668 days 12:00:25
662558400   1.976396    7668 days 12:00:47.500000
662558500   1.977118    7668 days 12:01:21.250000
66258500    1.9782  7668 days 12:02:11.879999995

In this example above I would want the change in time seconds

Time        Prod        dTime
662558400   1.975595    0
662558400   1.975916    0
662558400   1.976396    0
662558500   1.977118    100
66258500    1.9782  0


问:
What if STATIC_ROOT and STATICFILES_DIRS have different path in Django?
I'm working on my project that is basically some type of blog. But I needed to compile different features in one project, which now it can be a problem or maybe not.

In order to work I needed to have STATIC_ROOT and STATICFILES_DIRS but I cannot have them both on same location because I got error (ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting.)

So I searched for answer and I one guy here on stackoverflow said that he just changed location... he suggested to do it like this...

```<code>STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'assets_static')
MEDIA_ROOT = ''
MEDIA_URL = '/media/'

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
</code>```

For that time it has worked, but now I'm changing some static files and they are not updating. Also, now I have folders static and asset_static. Can someone tell what is the best practice here?

Body:
I'm working on my project that is basically some type of blog. But I needed to compile different features in one project, which now it can be a problem or maybe not.

In order to work I needed to have STATIC_ROOT and STATICFILES_DIRS but I cannot have them both on same location because I got error (ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting.)

So I searched for answer and I one guy here on stackoverflow said that he just changed location... he suggested to do it like this...

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'assets_static')
MEDIA_ROOT = ''
MEDIA_URL = '/media/'

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

For that time it has worked, but now I'm changing some static files and they are not updating. Also, now I have folders static and asset_static. Can someone tell what is the best practice here?


问:
Navigation inside iframe only working on some links
My code is meant to run a really bad version of a browser. I do it using iframes with the source as Bing.

Whenever I type something into the Bing search bar and press enter, it doesn't load the search page. When I click on other links on the Bing home page, however, it does go to some of those links. I tried adding all the sandbox stuff: allow-same-origin, allow-top-navigation, allow-forms, allow-scripts, and allow-popups, but those don't change anything.

The iframe code is pretty simple (it's generated dynamically with javascript). It comes out to:
<iframe src="https://www.bing.com/?toWww=1&redig=D8D172B7DD7E47F7836B91AD3DE58EF8" sandbox="allow-same-origin allow-top-navigation allow-forms allow-scripts allow-popups" id="frame1"


问:
Kivymd MDSegmentedControl size
I'm trying to use the MDSegmentedControl but can't figure out how to adjust the overall width. It just runs off the screen when placed next to another widget.</p>
```<code>KV = '''
MDScreen:

    MDCard:
        MDLabel:
            size_hint: None,1
            width: 200
            text: 'Gender'

        MDSegmentedControl:
            adaptive_width: True
            pos_hint: {"center_x": .5, "center_y": .5}

            MDSegmentedControlItem:
                text: "Male"

            MDSegmentedControlItem:
                text: "Female"

'''

class Example(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Orange"
        return Builder.load_string(KV)

Example().run()
</code>```

Title: Kivymd MDSegmentedControl size

Body:
I'm trying to use the MDSegmentedControl but can't figure out how to adjust the overall width. It just runs off the screen when placed next to another widget.

KV = '''
MDScreen:

    MDCard:
        MDLabel:
            size_hint: None,1
            width: 200
            text: 'Gender'

        MDSegmentedControl:
            adaptive_width: True
            pos_hint: {"center_x": .5, "center_y": .5}

            MDSegmentedControlItem:
                text: "Male"

            MDSegmentedControlItem:
                text: "Female"

'''

class Example(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Orange"
        return Builder.load_string(KV)

Example().run()


问:
Swift - how to conform to two protocols that define a variable with the same name
I'm trying to figure out how to make this work.
I have a class where I adopt two protocols InputA and InputB.

```<code>class Example: InputA, InputB {

}
</code>```

Both InputA and InputB protocols define a variable called output, but with a different type in each one.

```<code>protocol InputA {

    var output: OutputA? { get set }

}

protocol InputB {

    var output: OutputB? { get set }

}
</code>```

In this way, I cannot conform to both protocols simultaneously.

I tried to achieve this by simply making OutputA of type OutputB.

```<code>class Example: InputA, InputB {

    var output: OutputA?

}

protocol OutputA: OutputB {

    func dummyFuncA()

}

protocol OutputB {

    func dummyFuncB()

}
</code>```

But this results in a compilation error that says Example does not conform to the InputB protocol.

The closest solution I could get was to use an associatedtype on InputB in addition to the modification made above.

```<code>protocol InputB {

    associatedtype Output
    var output: Output? { get set }

}
</code>```

This solution compiles and inside the Example class I can access the OutputA and OutputB functions through the output variable. But then, if I try to create a default implementation of some function defined in InputB, I can't access the variable output as an element of type OutputB without casting with as?.

If I try to add a type constraint to associatedtype like below, class Example no longer conforms to InputB.

```<code>protocol InputB {

    associatedtype Output: OutputB
    var output: Output? { get set }

    func dummyInputB()

}
</code>```

Is there a way to achieve this result or am I trying to solve this problem in a dumb way?

Body:
I'm trying to figure out how to make this work.
I have a class where I adopt two protocols InputA and InputB.

class Example: InputA, InputB {

}

Both InputA and InputB protocols define a variable called output, but with a different type in each one.

protocol InputA {

    var output: OutputA? { get set }

}

protocol InputB {

    var output: OutputB? { get set }

}

In this way, I cannot conform to both protocols simultaneously.

I tried to achieve this by simply making OutputA of type OutputB.

class Example: InputA, InputB {

    var output: OutputA?

}

protocol OutputA: OutputB {

    func dummyFuncA()

}

protocol OutputB {

    func dummyFuncB()

}

But this results in a compilation error that says Example does not conform to the InputB protocol.

The closest solution I could get was to use an associatedtype on InputB in addition to the modification made above.

protocol InputB {

    associatedtype Output
    var output: Output? { get set }

}

This solution compiles and inside the Example class I can access the OutputA and OutputB functions through the output variable. But then, if I try to create a default implementation of some function defined in InputB, I can't access the variable output as an element of type OutputB without casting with as?.

If I try to add a type constraint to associatedtype like below, class Example no longer conforms to InputB.

protocol InputB {

    associatedtype Output: OutputB
    var output: Output? { get set }

    func dummyInputB()

}

Is there a way to achieve this result or am I trying to solve this problem in a dumb way?


问:
Spyder notebook can't open files in cloud storage (OneDrive) (Anaconda Spyder Juptyer Notebook plugin)
I need some help with the jupyter notebook plugin within spyder on a anaconda/ conda installation...

These dialog boxes appear when I try to open any notebook which is in my work/school onedrive folder on my mac:
First box
Second box: error

The Spyder editor has no problem accessing these files when in onedrive.
They can be opened once moved out of the Onedrive directory. I can open all other files which are out of Onedrive.
Anaconda-navigator has access permissions for all these folders.

This is a new problem, I'm not sure if it started happening after an update. I have recently been fiddling with another python installation on this computer (the standard one from the python website, but I don't think it has interfered)

Any help would be great, thanks.

I have tried updating spyder, conda, spyder-notebook, removing any pip modules I accidently installed when trying to add modules to the other python installation, then reinstalling spyder-notebook. None of this has changed anything.


问:
Yarn command installs a dependency of a sub dependency inside the root node_modules folder with wrong minor update
Let's imagine a folder structure below:

```<code>/#root
a.ts
b.ts
package.json
  "dependencies": {
     "dependency2":^1.0.3
   }
node_modules
  -dependency1
  -dependency2
      -node_modules
      -c.ts
      -package.json
        "dependencies": {
            "dependency3":^5.1.1
         }
  -dependency3
    -package.json
       **"version": 5.2.1**
</code>```

When you run yarn in the root folder there are 2 main problems that I faced on the different repos that package.json is included with the same dependency

That dependency3 is installed on the root node_modules folder instead of sub dependency's node_modules folder.

Dependency3 is installed on the repoA as version 5.1.1 but on the repoB it is 5.2.1 which caused problems

What could this be caused by?

I ran yarn on both repos on the same computer (npm version and node version is the same) but installed packages were different than each other for one minor update.

I had expected the same needed to be installed.

Body:
Let's imagine a folder structure below:

/#root
a.ts
b.ts
package.json
  "dependencies": {
     "dependency2":^1.0.3
   }
node_modules
  -dependency1
  -dependency2
      -node_modules
      -c.ts
      -package.json
        "dependencies": {
            "dependency3":^5.1.1
         }
  -dependency3
    -package.json
       **"version": 5.2.1**

When you run yarn in the root folder there are 2 main problems that I faced on the different repos that package.json is included with the same dependency

That dependency3 is installed on the root node_modules folder instead of sub dependency's node_modules folder.

Dependency3 is installed on the repoA as version 5.1.1 but on the repoB it is 5.2.1 which caused problems

What could this be caused by?

I ran yarn on both repos on the same computer (npm version and node version is the same) but installed packages were different than each other for one minor update.

I had expected the same needed to be installed.


问:
Visual Studio Code - Where is the terminal output history saved?
I ran a python script that had important timings inside the script but I accidently killed the terminal.
Is there a way to see terminal history outputs somewhere?

I tried to find an answer to my question but only thing I could find is how to find the history of commands I have ran.


问:
How to establish zmq connections between docker containers using docker compose option network_mode: host?
I want to establish a connection using the draft server/client pattern of ZeroMQ across different docker containers. For that, I have a zmq.server that is running in docker_container_server. In addition, I have a zmq.client which runs in docker_container_client. Both containers are based on different docker images. Despite using the network_mode: host option with docker compose, this does not work. If I do the same within one container, it just works fine.

The docker-compose files are the following.
docker-compose-client.yaml:

```<code>services:
  client:
    privileged: true
    image: client-image
    container_name: client
    command: tail -F anything
    network_mode: host
    environment:
      - "ROS_MASTER_URI=http://127.0.0.1:11311"
      - "ROS_HOSTNAME=127.0.0.1"
    build:
      context: ./client
      network: host
      dockerfile: Dockerfile
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
</code>```

docker-compose-server.yaml:

```<code>services:
  server:
    image: server-image
    privileged: true
    container_name: server
    network_mode: host
    command: tail -F anything
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    build:
      context: .
      network: host
      dockerfile: Dockerfile.server
</code>```

The server application uses pyzmq as follows:

```<code>import zmq

class ServerExample():
    def __init__(self):
        self.stop = False
        self.ctx = zmq.Context.instance()
        self.url = 'tcp://127.0.0.1:5555'
        self.server = self.ctx.socket(zmq.SERVER)
        self.server.bind(self.url)
        try:
            while not self.stop:
                msg = self.server.recv(copy=False) # stucks in this line
                print(msg.routing_id)

if __name__ == '__main__':
    server = ServerExample()
</code>```

The client uses cppzmq as follows: (I also tried a pyzmq-client. This also works within a container but not across different containers.)

```<code>#include <zmq.hpp>

class ClientExample
{
private:
    zmq::socket_t socket;
    zmq::context_t ctx;
 public:
     ClientExample()
     {
        socket = zmq::socket_t(ctx, zmq::socket_type::client);
        socket_.connect("tcp://127.0.0.1:5555");
        char[] some_data;
        socket_.send(zmq::buffer(some_data)); // not received by server
     }
};
</code>```

The containers are started by docker compose up server and docker compose up client.

When I do everything in one container and have a look on netstat -t | grep 5555, I get the same result in the container and on the host: (In this case, there are two clients and one server)

```<code>tcp        0   2856 localhost:56674         localhost:5555          ESTABLISHED
tcp        0   2856 localhost:5555          localhost:47666         ESTABLISHED
tcp        0      0 localhost:5555          localhost:56674         ESTABLISHED
</code>```

That is why I think that the docker compose option network_mode: host is properly working in my case.

When I start the docker_container_server and docker_container_client, the execution stucks in the line where the server should receive a message. netstat -t | grep 5555 ouputs both on the host and in the containers just nothing.

The versions I use:

Ubuntu 20.04

Docker Compose version v2.12.2

Docker Engine Version 20.10.21

libzmq v4.3.4

cppzmq v4.9.0

pyzmq v25.0.0b1

I searched a lot through the internet, read the documentations of docker, docker compose, zmq etc. I came to the conclusion, that it should work with the network_mode: host option and I think I confirmed that the network_mode: host option works as it should. The code itself should not contain any mistakes, as it works fine within one container. But I didn't figure out, why the communication doesn't work across containers.

Body:
I want to establish a connection using the draft server/client pattern of ZeroMQ across different docker containers. For that, I have a zmq.server that is running in docker_container_server. In addition, I have a zmq.client which runs in docker_container_client. Both containers are based on different docker images. Despite using the network_mode: host option with docker compose, this does not work. If I do the same within one container, it just works fine.

The docker-compose files are the following.
docker-compose-client.yaml:

services:
  client:
    privileged: true
    image: client-image
    container_name: client
    command: tail -F anything
    network_mode: host
    environment:
      - "ROS_MASTER_URI=http://127.0.0.1:11311"
      - "ROS_HOSTNAME=127.0.0.1"
    build:
      context: ./client
      network: host
      dockerfile: Dockerfile
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

docker-compose-server.yaml:

services:
  server:
    image: server-image
    privileged: true
    container_name: server
    network_mode: host
    command: tail -F anything
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    build:
      context: .
      network: host
      dockerfile: Dockerfile.server

The server application uses pyzmq as follows:

import zmq

class ServerExample():
    def __init__(self):
        self.stop = False
        self.ctx = zmq.Context.instance()
        self.url = 'tcp://127.0.0.1:5555'
        self.server = self.ctx.socket(zmq.SERVER)
        self.server.bind(self.url)
        try:
            while not self.stop:
                msg = self.server.recv(copy=False) # stucks in this line
                print(msg.routing_id)

if __name__ == '__main__':
    server = ServerExample()

The client uses cppzmq as follows: (I also tried a pyzmq-client. This also works within a container but not across different containers.)

#include <zmq.hpp>

class ClientExample
{
private:
    zmq::socket_t socket;
    zmq::context_t ctx;
 public:
     ClientExample()
     {
        socket = zmq::socket_t(ctx, zmq::socket_type::client);
        socket_.connect("tcp://127.0.0.1:5555");
        char[] some_data;
        socket_.send(zmq::buffer(some_data)); // not received by server
     }
};

The containers are started by docker compose up server and docker compose up client.

When I do everything in one container and have a look on netstat -t | grep 5555, I get the same result in the container and on the host: (In this case, there are two clients and one server)

tcp        0   2856 localhost:56674         localhost:5555          ESTABLISHED
tcp        0   2856 localhost:5555          localhost:47666         ESTABLISHED
tcp        0      0 localhost:5555          localhost:56674         ESTABLISHED

That is why I think that the docker compose option network_mode: host is properly working in my case.

When I start the docker_container_server and docker_container_client, the execution stucks in the line where the server should receive a message. netstat -t | grep 5555 ouputs both on the host and in the containers just nothing.

The versions I use:

Ubuntu 20.04

Docker Compose version v2.12.2

Docker Engine Version 20.10.21

libzmq v4.3.4

cppzmq v4.9.0

pyzmq v25.0.0b1

I searched a lot through the internet, read the documentations of docker, docker compose, zmq etc. I came to the conclusion, that it should work with the network_mode: host option and I think I confirmed that the network_mode: host option works as it should. The code itself should not contain any mistakes, as it works fine within one container. But I didn't figure out, why the communication doesn't work across containers.


问:
Kaldi - How do I create .ark and .scp files?
I have my own datasets of Voxceleb1 and Voxceleb2. I am trying to find information on how to generate an .ark file so I can get access to creating an .scp file since that's how I understand it works. Is there a script for it?</p>


问:
Library not loaded: '/System/Library/PrivateFrameworks/JavaApplicationLauncher.framework/Versions/A/JavaApplicationLauncher'
Installed SQL Workbench on my new Mac which is of Monterey 12.6.
After installation, tried to open SQL Workbench but got error like this

```<code>Library not loaded: '/System/Library/PrivateFrameworks/JavaApplicationLauncher.framework/Versions/A/JavaApplicationLauncher'
</code>```

Followed instruction here System cannot find JavaApplicationLauncher and open the Show Package Contents--> Contents/MacOS but there is no JavaApplicationStub or universalJavaApplicationStub in this folder.
I have newest JRE installed.
After searching for a while I could not find solution for this.
Any suggestions?

Body:
Installed SQL Workbench on my new Mac which is of Monterey 12.6.
After installation, tried to open SQL Workbench but got error like this

Library not loaded: '/System/Library/PrivateFrameworks/JavaApplicationLauncher.framework/Versions/A/JavaApplicationLauncher'

Followed instruction here System cannot find JavaApplicationLauncher and open the Show Package Contents--> Contents/MacOS but there is no JavaApplicationStub or universalJavaApplicationStub in this folder.
I have newest JRE installed.
After searching for a while I could not find solution for this.
Any suggestions?


问:
EF: Nullable object must have a value after updating to .Net 6
In .net core 3.1 I had the following expression:

```<code>var result = _dbContext.Orders.Where(x => x.OrderId == orderId)
                                .Select(x =>
                                    new
                                    {
                                        x.Customer.CustomerId,
                                        x.ProductId,
                                        x.Quantity,
                                    }).FirstOrDefault();
</code>```

Everything was working fine. After we updated to .Net 6 with the latest EntityFramework core 6.x we started receiving the error Nullable object must have a value after updating to .Net 6.

I know that this error is because the Order table rows have sometimes customers which are null (not pointing to a customer).

So, the x.Customer.CustomerId inside the anonymous object gives this error.

I also know that if I convert that expression to the below, then it will operate correctly.

```<code>var result = _dbContext.Orders.Where(x => x.OrderId == orderId)
                                .Select(x =>
                                    new
                                    {
                                        CustomerId = (int?)x.Customer.CustomerId,
                                        x.ProductId,
                                        x.Quantity,
                                    }).FirstOrDefault();
</code>```

Can someone tell me please what changed to the .Net 6 and/or EFCore 6 and the previous statement doesn't operate any more? Can you please let me know if there is any change that I can make (either globally or at least in the DB model) in order to avoid such errors?

It will be difficult for me to do changes one by one as there are hundreds of such expressions we are using. As such I need a change to be done globally...

Body:
In .net core 3.1 I had the following expression:

var result = _dbContext.Orders.Where(x => x.OrderId == orderId)
                                .Select(x =>
                                    new
                                    {
                                        x.Customer.CustomerId,
                                        x.ProductId,
                                        x.Quantity,
                                    }).FirstOrDefault();

Everything was working fine. After we updated to .Net 6 with the latest EntityFramework core 6.x we started receiving the error Nullable object must have a value after updating to .Net 6.

I know that this error is because the Order table rows have sometimes customers which are null (not pointing to a customer).

So, the x.Customer.CustomerId inside the anonymous object gives this error.

I also know that if I convert that expression to the below, then it will operate correctly.

var result = _dbContext.Orders.Where(x => x.OrderId == orderId)
                                .Select(x =>
                                    new
                                    {
                                        CustomerId = (int?)x.Customer.CustomerId,
                                        x.ProductId,
                                        x.Quantity,
                                    }).FirstOrDefault();

Can someone tell me please what changed to the .Net 6 and/or EFCore 6 and the previous statement doesn't operate any more? Can you please let me know if there is any change that I can make (either globally or at least in the DB model) in order to avoid such errors?

It will be difficult for me to do changes one by one as there are hundreds of such expressions we are using. As such I need a change to be done globally...


问:
When i want to save multiple image to database it's only save the last on telegram

if (req[0].site == '1') {
    link = await bot.telegram.getFileLink(ctx.message.photo[ctx.message.photo.length - 1].file_id) // Save the last image
    await console.log(link.href) // Print the last image url to know it's the good
    await db.query(`UPDATE base SET photo = '${link.href} \n ${req[0].photo} ' where user = '${ctx.chat.id}'`) // To add to the database, but it's only save the last sended picture
    return;
}
```

I try to know where was the problem, change my db query but it's not that, check if all of my code is in await and it's good

Body:
if (req[0].site == '1') {
    link = await bot.telegram.getFileLink(ctx.message.photo[ctx.message.photo.length - 1].file_id) // Save the last image
    await console.log(link.href) // Print the last image url to know it's the good
    await db.query(`UPDATE base SET photo = '${link.href} \n ${req[0].photo} ' where user = '${ctx.chat.id}'`) // To add to the database, but it's only save the last sended picture
    return;
}

I try to know where was the problem, change my db query but it's not that, check if all of my code is in await and it's good


问:
When (if ever) C++ concepts must be “decayed”, do it at concept definition or at “requires”?

Imagine I have a concept that checks for some trait of a member type, e.g. its integralness. In anticipation of what is to come, let me define it in two ways:

namespace decayedAtConcept {
  template <typename T>
  concept hasIntegralMemberType = std::integral<typename std::decay_t<T>::MemberType>;
}

namespace notDecayedAtConcept {
  template <typename T>
  concept hasIntegralMemberType = std::integral<typename T::MemberType>;
}
```
<p>With the following definitions</p>
<pre class="lang-c++ prettyprint-override"><code>struct HasIntegralMemberType {using MemberType = int;};

struct HasNonintegralMemberType {using MemberType = double;};

struct DoesNotHaveMemberType {};
</code>```

and the following function declarations

void usesIntegralMemberType1 (decayedAtConcept::hasIntegralMemberType auto&&);

void usesIntegralMemberType2 (notDecayedAtConcept::hasIntegralMemberType auto&&);

template <typename T> requires notDecayedAtConcept::hasIntegralMemberType<std::decay_t<T>>
void usesIntegralMemberType3 (T&&);
```
<p>in effect, a client can try to use this library in the following way:</p>
<pre class="lang-c++ prettyprint-override"><code>void client () {
  HasIntegralMemberType h;

  usesIntegralMemberType1(HasIntegralMemberType{});
  usesIntegralMemberType1(h); // OK
  //usesIntegralMemberType1(HasNonintegralMemberType{}); //note: constraints not satisfied
  //usesIntegralMemberType1(DoesNotHaveMemberType{});    //note: constraints not satisfied

  usesIntegralMemberType2(HasIntegralMemberType{});
  //usesIntegralMemberType2(h); //error: ‘HasIntegralMemberType&’ is not a class, struct, or union type

  usesIntegralMemberType3(HasIntegralMemberType{});
  usesIntegralMemberType3(h); // OK again
}
</code>```

The notes just demonstrate that the concept works as expected in usesIntegralMemberType1. My question is related to the error caused by the naive usage of the notDecayedAtConcept in usesIntegralMemberType2.

Apparently, the notDecayedAtConcept version of the concept is less convenient to use because any time it is used with a universal reference, it needs to be decayed in a requires clause as in usesIntegralMemberType3. We even lose the syntactic sugar we had in defining the constrained template parameter in usesIntegralMemberType1.

And now the question: are there already some guidelines which of the two strategies to use in such a situation? Or, is there any other, more transparent/convenient solution?

Body:
Imagine I have a concept that checks for some trait of a member type, e.g. its integralness. In anticipation of what is to come, let me define it in two ways:

namespace decayedAtConcept {
  template <typename T>
  concept hasIntegralMemberType = std::integral<typename std::decay_t<T>::MemberType>;
}

namespace notDecayedAtConcept {
  template <typename T>
  concept hasIntegralMemberType = std::integral<typename T::MemberType>;
}

With the following definitions

struct HasIntegralMemberType {using MemberType = int;};

struct HasNonintegralMemberType {using MemberType = double;};

struct DoesNotHaveMemberType {};

and the following function declarations

void usesIntegralMemberType1 (decayedAtConcept::hasIntegralMemberType auto&&);

void usesIntegralMemberType2 (notDecayedAtConcept::hasIntegralMemberType auto&&);

template <typename T> requires notDecayedAtConcept::hasIntegralMemberType<std::decay_t<T>>
void usesIntegralMemberType3 (T&&);

in effect, a client can try to use this library in the following way:

void client () {
  HasIntegralMemberType h;

  usesIntegralMemberType1(HasIntegralMemberType{});
  usesIntegralMemberType1(h); // OK
  //usesIntegralMemberType1(HasNonintegralMemberType{}); //note: constraints not satisfied
  //usesIntegralMemberType1(DoesNotHaveMemberType{});    //note: constraints not satisfied

  usesIntegralMemberType2(HasIntegralMemberType{});
  //usesIntegralMemberType2(h); //error: ‘HasIntegralMemberType&’ is not a class, struct, or union type

  usesIntegralMemberType3(HasIntegralMemberType{});
  usesIntegralMemberType3(h); // OK again
}

The notes just demonstrate that the concept works as expected in usesIntegralMemberType1. My question is related to the error caused by the naive usage of the notDecayedAtConcept in usesIntegralMemberType2.

Apparently, the notDecayedAtConcept version of the concept is less convenient to use because any time it is used with a universal reference, it needs to be decayed in a requires clause as in usesIntegralMemberType3. We even lose the syntactic sugar we had in defining the constrained template parameter in usesIntegralMemberType1.

And now the question: are there already some guidelines which of the two strategies to use in such a situation? Or, is there any other, more transparent/convenient solution?


问:
How to I access an endpoint covered by next-auth through google app script
So recently I decided that I need to access a protected api endpoint in google app script. The only thing I can find is app-script-oauth2, the reason this does not work is because my middleware for the tRPC endpoint (code below) says if there is not a session (which is stored in a prisma db) you cannot access the api.

```<code>.middleware(async ({ ctx: { session }, next }) => {
  if (!session) {
    throw new TRPCError({ code: "UNAUTHORIZED" });
  }
  return next();
})
</code>```

I have also tried to login and try to make the request but it seems as if the request is completely unrelated to the local session. I know this isn't a ton to work from but any help at all would be greatly appreciated.

Body:
So recently I decided that I need to access a protected api endpoint in google app script. The only thing I can find is app-script-oauth2, the reason this does not work is because my middleware for the tRPC endpoint (code below) says if there is not a session (which is stored in a prisma db) you cannot access the api.

.middleware(async ({ ctx: { session }, next }) => {
  if (!session) {
    throw new TRPCError({ code: "UNAUTHORIZED" });
  }
  return next();
})

I have also tried to login and try to make the request but it seems as if the request is completely unrelated to the local session. I know this isn't a ton to work from but any help at all would be greatly appreciated.


问:
Are builtins like str() and int() functions or classes?
In Python, when we call str(<something>), are we calling the function, or are we calling the class constructor (the class being str)? Similarly, int(), complex() etc.


问:
Is widely used porter-duff formula for source-over on non-premultiplied (straight) alpha wrong?
I am looking for a formula to draw rgba color over rgba background, and it seems to me, that widely used formula for non-premultiplied alpha has an unexpected side-effect when both the underlying (background) and source (foreground) is non-opaque.

The formula, as cited eg. in Win2D for WinUI3 is

To perform a source-over blend between two colors that use straight alpha format:

```<code>result = (source.RGB * source.A) + (dest.RGB * (1 - source.A))
</code>```

However, if we are blending eg. partially transparent blue over a red color with zero alpha, the red color will show up in the result.

```<code>destination = rgba(1, 0, 0, 0)
source = rgba(0, 0, 1, 0.5)
</code>```

resultRed = (source.R * source.A) + (dest.R * (1 - source.A)) = (0 * 0.5) + (1 * (1 - 0.5)) = 0 + 0.5 = 0.5 - the result has a strong red component, even though we are blending blue over 'empty' image.

I haven't found any source that would discuss this or offer alternative formula, short of premultiplying the source colors, doing the porter-duff src-over, and then trying to convert back from premultiplied space, which is a lossy and slow operation.

Do you have a solution for a more natural blend (eg. that would produce partially transparent blue in the above case) operation in non-premultiplied space?

Body:
I am looking for a formula to draw rgba color over rgba background, and it seems to me, that widely used formula for non-premultiplied alpha has an unexpected side-effect when both the underlying (background) and source (foreground) is non-opaque.

The formula, as cited eg. in Win2D for WinUI3 is

To perform a source-over blend between two colors that use straight alpha format:

result = (source.RGB * source.A) + (dest.RGB * (1 - source.A))

However, if we are blending eg. partially transparent blue over a red color with zero alpha, the red color will show up in the result.

destination = rgba(1, 0, 0, 0)
source = rgba(0, 0, 1, 0.5)

resultRed = (source.R * source.A) + (dest.R * (1 - source.A)) = (0 * 0.5) + (1 * (1 - 0.5)) = 0 + 0.5 = 0.5 - the result has a strong red component, even though we are blending blue over 'empty' image.

I haven't found any source that would discuss this or offer alternative formula, short of premultiplying the source colors, doing the porter-duff src-over, and then trying to convert back from premultiplied space, which is a lossy and slow operation.

Do you have a solution for a more natural blend (eg. that would produce partially transparent blue in the above case) operation in non-premultiplied space?