问:
The function called by std::async is not executed immediately?

#include <iostream>
#include <future>
auto gClock = clock();

char threadPool(char c) {
    std::cout << "enter thread :" << c << " cost time:" << clock() - gClock << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));
    for (int i = 0; i < 10; i++)
        std::cout << c;
    std::cout << std::endl;
    return c;
}
void fnTestAsync(){
    auto begin = clock();
    std::future<char> futures[10];
    for (int i = 0; i < 10; ++i){
        futures[i] = std::async(std::launch::async,threadPool, 'a' + i);
    }
    for (int i = 0; i < 10; ++i){
        std::cout << futures[i].get() << " back ,cost time: " << clock() - begin << std::endl;
    }

    std::cout << "fnTestAsync: " << clock() - begin << std::endl;
}
int main(){
    std::thread testAsync(fnTestAsync);
    testAsync.detach();
    std::this_thread::sleep_for(std::chrono::seconds(10));
    return 0;
}
```

run result

I'm trying to get these 10 threads to execute together and all return immediately after a two second delay, but I output the time spent and find that it takes about 2900ms, much larger than the 2000ms I expected.

What is the cause of this increase?
How should he fix it?

Body:
#include <iostream>
#include <future>
auto gClock = clock();

char threadPool(char c) {
    std::cout << "enter thread :" << c << " cost time:" << clock() - gClock << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));
    for (int i = 0; i < 10; i++)
        std::cout << c;
    std::cout << std::endl;
    return c;
}
void fnTestAsync(){
    auto begin = clock();
    std::future<char> futures[10];
    for (int i = 0; i < 10; ++i){
        futures[i] = std::async(std::launch::async,threadPool, 'a' + i);
    }
    for (int i = 0; i < 10; ++i){
        std::cout << futures[i].get() << " back ,cost time: " << clock() - begin << std::endl;
    }

    std::cout << "fnTestAsync: " << clock() - begin << std::endl;
}
int main(){
    std::thread testAsync(fnTestAsync);
    testAsync.detach();
    std::this_thread::sleep_for(std::chrono::seconds(10));
    return 0;
}

run result

I'm trying to get these 10 threads to execute together and all return immediately after a two second delay, but I output the time spent and find that it takes about 2900ms, much larger than the 2000ms I expected.

What is the cause of this increase?
How should he fix it?


来源: stackexchange

问:
Put flutter app in kiosk mode while on another app
I want to make a screen lock application with flutter. How can I put it in kiosk mode when I'm on top of other applications? thanks

I tried showing an overlay with the system_alert_window package and running it there, but it didn't work.

ContentLicense: CC BY-SA 4.0


问:
Troubleshooting Latency Increase for Lambda to EFS Reads

The Gist

We've got a Lambda job running that reads data from EFS (elastic throughout) for up to 200 TPS of read requests.

PercentIOLimit is well below 20%.

Latency goes from about 20 ms to about 400 ms during traffic spikes.

Are there any steps I can take to get more granularity into where the latency for the reads is coming from?

Additional Info:

At low TPS (~5), reads take about 10-20 ms.
At higher TPS (~50), p90 can take 300-400 ms.

I'd really like to narrow down what limit is causing these latency spikes, especially when the IOPercent usage is around 60%.


问:
problem with face_recognition package: _UFuncNoLoopError: 'subtract' with signature matching types (dtype('<U2080'), dtype('float64'))
So i'm trying to make a facial recognition system for my school project . Step 1 : The software primarly reads a bunch of images gets there names and Facial data (encodings to recognize who is who) and stores them in CSV file . Step 2 :  After that another part of the software opens the csv file and stores the names from the CSV file as list('name_of_people') and Facial Data as list('knownEncodedList') . Now in step 1 if store the face readings and names in a list the code works fine , but when i store them in a csv and then try using them the code throws this erro .   Link of the repository: https://github.com/ZahinFyz/Face_Recognition

```<code>Traceback (most recent call last):
  File "F:\This Semester\Python\Projects\Face Recognition\Face_recognition.py", line 47, in <module>
    matches = fr.compare_faces(knownEncodedList , encodeFaceF)
  File "F:\This Semester\Python\Projects\Face Recognition\venv\lib\site-packages\face_recognition\api.py", line 226, in compare_faces
    return list(face_distance(known_face_encodings, face_encoding_to_check) <= tolerance)
  File "F:\This Semester\Python\Projects\Face Recognition\venv\lib\site-packages\face_recognition\api.py", line 75, in face_distance
    return np.linalg.norm(face_encodings - face_to_compare, axis=1)
numpy.core._exceptions._UFuncNoLoopError: ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U2080'), dtype('float64')) -> None

</code>```

The actual code :

```<code>import cv2
import csv
import face_recognition as fr
import numpy as np

name_of_people = []
with open('Facial Data.csv') as data :
    data = csv.reader(data)
    next(data)
    for col in data :
        name_of_people.append(col[0])

#file = open("Facial Data.csv")
#numpy_array = np. loadtxt(file, delimiter=",")
#print(numpy_array)

knownEncodedList = []
with open('Facial Data.csv') as data :
    data = csv.reader(data)
    next(data)
    for col in data :
        encode = np.array(col[1])
        knownEncodedList.append(encode)

#Use to get video steam from camera
'''https://www.geeksforgeeks.org/python-opencv-capture-video-
from-camera/#:~:text=Use%20cv2.,the%20frames%20in%20the%20video.'''
cap = cv2.VideoCapture(0)

while True :
    '''https://stackoverflow.com/
    questions/65535939/python-understanding-read-in-opencv'''
    success , img = cap.read()
    #Resiving the image so that it doesn't take much time to read
    imgS = cv2.resize(img,(0,0),None , 0.25 , 0.25)

    facesInF = fr.face_locations(imgS)
    encInF = fr.face_encodings(imgS,facesInF)

    #sequentially grab face locations and face encodings of the video
    for encodeFaceF , facelocF in zip(encInF,facesInF):

        #matching with our given data set
        matches = fr.compare_faces(knownEncodedList , encodeFaceF)
        faceDis = fr.face_distance(knownEncodedList , encodeFaceF)

        #getting the best match
        matchIndex = np.argmin(faceDis)
        z = np.min(faceDis)
        #print(matchIndex)
        if z < 0.45 :
            #Designing the Frame
            if matches[matchIndex]:
                name = name_of_people[matchIndex]
                y1,x2,y2,x1 = facelocF
                y1, x2, y2, x1 = y1*4,x2*4,y2*4,x1*4
                cv2.rectangle(img,(x1 , y1),(x2,y2),(0,255,0),2)
                cv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)
                cv2.putText(img , name,(x1+6 , y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
                print(name)
        else :
            name = 'Tresspasser'
            y1, x2, y2, x1 = facelocF
            y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
            cv2.rectangle(img, (x1, y1), (x2, y2), (128,0,0), 2)
            cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (128,0,0), cv2.FILLED)
            cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255),2)

    cv2.imshow('webcam' ,img)
    cv2.waitKey(1)

</code>```

So the software is supposed to get the names and readings from the csv file and when it sees a face it can detect the person and show his name . I tried using genfromtxt() and loadtxt() but couldn't get to bring the data from csv properly

Body:
So i'm trying to make a facial recognition system for my school project . Step 1 : The software primarly reads a bunch of images gets there names and Facial data (encodings to recognize who is who) and stores them in CSV file . Step 2 :  After that another part of the software opens the csv file and stores the names from the CSV file as list('name_of_people') and Facial Data as list('knownEncodedList') . Now in step 1 if store the face readings and names in a list the code works fine , but when i store them in a csv and then try using them the code throws this erro .   Link of the repository: https://github.com/ZahinFyz/Face_Recognition

Traceback (most recent call last):
  File "F:\This Semester\Python\Projects\Face Recognition\Face_recognition.py", line 47, in <module>
    matches = fr.compare_faces(knownEncodedList , encodeFaceF)
  File "F:\This Semester\Python\Projects\Face Recognition\venv\lib\site-packages\face_recognition\api.py", line 226, in compare_faces
    return list(face_distance(known_face_encodings, face_encoding_to_check) <= tolerance)
  File "F:\This Semester\Python\Projects\Face Recognition\venv\lib\site-packages\face_recognition\api.py", line 75, in face_distance
    return np.linalg.norm(face_encodings - face_to_compare, axis=1)
numpy.core._exceptions._UFuncNoLoopError: ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U2080'), dtype('float64')) -> None

The actual code :

import cv2
import csv
import face_recognition as fr
import numpy as np

name_of_people = []
with open('Facial Data.csv') as data :
    data = csv.reader(data)
    next(data)
    for col in data :
        name_of_people.append(col[0])

#file = open("Facial Data.csv")
#numpy_array = np. loadtxt(file, delimiter=",")
#print(numpy_array)

knownEncodedList = []
with open('Facial Data.csv') as data :
    data = csv.reader(data)
    next(data)
    for col in data :
        encode = np.array(col[1])
        knownEncodedList.append(encode)

#Use to get video steam from camera
'''https://www.geeksforgeeks.org/python-opencv-capture-video-
from-camera/#:~:text=Use%20cv2.,the%20frames%20in%20the%20video.'''
cap = cv2.VideoCapture(0)

while True :
    '''https://stackoverflow.com/
    questions/65535939/python-understanding-read-in-opencv'''
    success , img = cap.read()
    #Resiving the image so that it doesn't take much time to read
    imgS = cv2.resize(img,(0,0),None , 0.25 , 0.25)

    facesInF = fr.face_locations(imgS)
    encInF = fr.face_encodings(imgS,facesInF)

    #sequentially grab face locations and face encodings of the video
    for encodeFaceF , facelocF in zip(encInF,facesInF):

        #matching with our given data set
        matches = fr.compare_faces(knownEncodedList , encodeFaceF)
        faceDis = fr.face_distance(knownEncodedList , encodeFaceF)

        #getting the best match
        matchIndex = np.argmin(faceDis)
        z = np.min(faceDis)
        #print(matchIndex)
        if z < 0.45 :
            #Designing the Frame
            if matches[matchIndex]:
                name = name_of_people[matchIndex]
                y1,x2,y2,x1 = facelocF
                y1, x2, y2, x1 = y1*4,x2*4,y2*4,x1*4
                cv2.rectangle(img,(x1 , y1),(x2,y2),(0,255,0),2)
                cv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)
                cv2.putText(img , name,(x1+6 , y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
                print(name)
        else :
            name = 'Tresspasser'
            y1, x2, y2, x1 = facelocF
            y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
            cv2.rectangle(img, (x1, y1), (x2, y2), (128,0,0), 2)
            cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (128,0,0), cv2.FILLED)
            cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255),2)

    cv2.imshow('webcam' ,img)
    cv2.waitKey(1)

So the software is supposed to get the names and readings from the csv file and when it sees a face it can detect the person and show his name . I tried using genfromtxt() and loadtxt() but couldn't get to bring the data from csv properly


问:
Click button A submit button B at the same time
I want to auto calculate shipping when the quantity changed?
How can "Calculate shipping botton" auto submit when updated quantity?
This script worked in the first time when i clicked to quantity button, it do not work in the next time. I appreciate your help!</p>
```<code> <button class="quantity__button" name="minus" type="button">Minus</button>
 <button class="quantity__button" name="plus" type="button">Plus</button>

 <input type="button" class="get-rates" value="CALCULATE SHIPPING" />

  <script>
 $('.quantity__button').click(function(){
 $('.get-rates').click();
 })
 </script>
</code>```

Body:
I want to auto calculate shipping when the quantity changed?
How can "Calculate shipping botton" auto submit when updated quantity?
This script worked in the first time when i clicked to quantity button, it do not work in the next time. I appreciate your help!

 <button class="quantity__button" name="minus" type="button">Minus</button>
 <button class="quantity__button" name="plus" type="button">Plus</button>

 <input type="button" class="get-rates" value="CALCULATE SHIPPING" />


问:
using shared package in multiple webapi projects at runtime at production server (net 7)
I've already followed thisto setup a runtime store at deployed server, but i can't make package store at runtime environment that reference assembly to that, in other word when i browse my webapi i get 500.30 error and event log show me that IIS AspNetCore Module V2 cant find the assembly this Error:

```<code> Application '/LM/W3SVC/14/ROOT/webapi' with physical root 'D:\webapi\' hit unexpected managed exception, exception code = '0xe0434352'. First 30KB characters of captured stdout and stderr logs:
 Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'CSTR, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
 File name: 'CSTR, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
 at Program.<Main>$(String[] args)
</code>```

the host uses In-process hosting with IIS and ASP.NET Core.

i appreciate your help.

we used GAC (Global Assembly GAC) before, for .net framework projects and try to migrate it to .net project but it fails.

Body:
I've already followed thisto setup a runtime store at deployed server, but i can't make package store at runtime environment that reference assembly to that, in other word when i browse my webapi i get 500.30 error and event log show me that IIS AspNetCore Module V2 cant find the assembly this Error:

 Application '/LM/W3SVC/14/ROOT/webapi' with physical root 'D:\webapi\' hit unexpected managed exception, exception code = '0xe0434352'. First 30KB characters of captured stdout and stderr logs:
 Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'CSTR, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
 File name: 'CSTR, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
 at Program.$(String[] args)

the host uses In-process hosting with IIS and ASP.NET Core.

i appreciate your help.

we used GAC (Global Assembly GAC) before, for .net framework projects and try to migrate it to .net project but it fails.


问:
Access denied when renaming folder with cmd
I don't know if this is the right place to ask this question, but I am going to ask it anyway.

I have written a small batch script/file to rename a folder. The user can say what the name should be and then the folder should be renamed.
But it always says access denied or nothing happens. As soon as I take the single line of code and copy it into cmd and run it, it says access denied.

Batch file:

```<code>@echo off
set /p old_name=Old name of the Folder:
set /p new_name=New name of the Folder:
rename %userprofile%\Pictures\%old_name% %new_name%
pause
exit
</code>```

Then nothing happens...
In the Folder are two subfolders and in these folders are two .txt files with content
The .bat file is on the desktop

When i do it with cmd there is written "Access denied"
Code in cmd:

```<code>rename %userprofile%\Pictures\Test test
</code>```

Does someone know a Solution?

Body:
I don't know if this is the right place to ask this question, but I am going to ask it anyway.

I have written a small batch script/file to rename a folder. The user can say what the name should be and then the folder should be renamed.
But it always says access denied or nothing happens. As soon as I take the single line of code and copy it into cmd and run it, it says access denied.

Batch file:

@echo off
set /p old_name=Old name of the Folder:
set /p new_name=New name of the Folder:
rename %userprofile%\Pictures\%old_name% %new_name%
pause
exit

Then nothing happens...
In the Folder are two subfolders and in these folders are two .txt files with content
The .bat file is on the desktop

When i do it with cmd there is written "Access denied"
Code in cmd:

rename %userprofile%\Pictures\Test test

Does someone know a Solution?


问:
What is "mgt-todo" in mgt-react 2.8.0 what about other todo lists other than "Tasks"
Where can I find all the React equivalent of the tags I see in the playground?
I am looking for . I tested with <Task but it only brings on task for myself.

In the explorer,

```<code>https://graph.microsoft.com/v1.0/me/todo/lists/tasks/tasks
</code>```

brings 3 tasks
Also I have tasks in other lists too. how do I get them in MGT?

Thank you

Body:
Where can I find all the React equivalent of the tags I see in the playground?
I am looking for . I tested with <Task but it only brings on task for myself.

In the explorer,

https://graph.microsoft.com/v1.0/me/todo/lists/tasks/tasks

brings 3 tasks
Also I have tasks in other lists too. how do I get them in MGT?

Thank you


问:
failed to close batch:[7] Request Timed Out: the request exceeded the user-specified time limit in the request
It's my first use of Kafka-go. I installed everything locally on a clean machine and used the very first two code samples: Produce Messages and Consume Messages as follows. Please note that I just copy-pasted the code from the aforementioned link.

```<code>package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/segmentio/kafka-go"
)

func main() {

    ProduceMessages()
    ConsumeMessages()
}

func ProduceMessages() {
    // to produce messages
    topic := "my-topic"
    partition := 0

    conn, err := kafka.DialLeader(context.Background(), "tcp", "localhost:9092", topic, partition)
    if err != nil {
        log.Fatal("failed to dial leader:", err)
    }

    conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
    _, err = conn.WriteMessages(
        kafka.Message{Value: []byte("one!")},
        kafka.Message{Value: []byte("two!")},
        kafka.Message{Value: []byte("three!")},
    )
    if err != nil {
        log.Fatal("failed to write messages:", err)
    }

    if err := conn.Close(); err != nil {
        log.Fatal("failed to close writer:", err)
    }
}

func ConsumeMessages() {
    // to consume messages
    topic := "my-topic"
    partition := 0

    conn, err := kafka.DialLeader(context.Background(), "tcp", "localhost:9092", topic, partition)
    if err != nil {
        log.Fatal("failed to dial leader:", err)
    }

    conn.SetReadDeadline(time.Now().Add(10 * time.Second))
    batch := conn.ReadBatch(10e3, 1e6) // fetch 10KB min, 1MB max

    b := make([]byte, 10e3) // 10KB max per message
    for {
        n, err := batch.Read(b)
        if err != nil {
            break
        }
        fmt.Println(string(b[:n]))
    }

    if err := batch.Close(); err != nil {
        log.Fatal("failed to close batch:", err)
    }

    if err := conn.Close(); err != nil {
        log.Fatal("failed to close connection:", err)
    }
}
</code>```

However, whenever trying to close the batch session, I am getting the following result (after waiting a bunch of seconds):

```<code>one!
two!
three!
</code>```

Well, that's nice so far, but this is always followed by the following error.

```<code>2022/12/10 10:35:50 failed to close batch:[7] Request Timed Out: the request exceeded the user-specified time limit in the request
exit status 1
</code>```

Why is it failing to close the batch (why is it timed out)?

PS> Please note that I'm unable to add the Kafka-go which differs from the already existing confluent-kafka-go tag

Body:
It's my first use of Kafka-go. I installed everything locally on a clean machine and used the very first two code samples: Produce Messages and Consume Messages as follows. Please note that I just copy-pasted the code from the aforementioned link.

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/segmentio/kafka-go"
)

func main() {

    ProduceMessages()
    ConsumeMessages()
}

func ProduceMessages() {
    // to produce messages
    topic := "my-topic"
    partition := 0

    conn, err := kafka.DialLeader(context.Background(), "tcp", "localhost:9092", topic, partition)
    if err != nil {
        log.Fatal("failed to dial leader:", err)
    }

    conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
    _, err = conn.WriteMessages(
        kafka.Message{Value: []byte("one!")},
        kafka.Message{Value: []byte("two!")},
        kafka.Message{Value: []byte("three!")},
    )
    if err != nil {
        log.Fatal("failed to write messages:", err)
    }

    if err := conn.Close(); err != nil {
        log.Fatal("failed to close writer:", err)
    }
}

func ConsumeMessages() {
    // to consume messages
    topic := "my-topic"
    partition := 0

    conn, err := kafka.DialLeader(context.Background(), "tcp", "localhost:9092", topic, partition)
    if err != nil {
        log.Fatal("failed to dial leader:", err)
    }

    conn.SetReadDeadline(time.Now().Add(10 * time.Second))
    batch := conn.ReadBatch(10e3, 1e6) // fetch 10KB min, 1MB max

    b := make([]byte, 10e3) // 10KB max per message
    for {
        n, err := batch.Read(b)
        if err != nil {
            break
        }
        fmt.Println(string(b[:n]))
    }

    if err := batch.Close(); err != nil {
        log.Fatal("failed to close batch:", err)
    }

    if err := conn.Close(); err != nil {
        log.Fatal("failed to close connection:", err)
    }
}

However, whenever trying to close the batch session, I am getting the following result (after waiting a bunch of seconds):

one!
two!
three!

Well, that's nice so far, but this is always followed by the following error.

2022/12/10 10:35:50 failed to close batch:[7] Request Timed Out: the request exceeded the user-specified time limit in the request
exit status 1

Why is it failing to close the batch (why is it timed out)?

PS> Please note that I'm unable to add the Kafka-go which differs from the already existing confluent-kafka-go tag


问:
Assigning an object to a property from a QList
In my main app class I have a property which contains a list of the ProjectItems. Within my application a user can specifically select a an item in that list which I then assign to the property called currentProjectItem.

I know in same applications you would use a pointer here to point to the selected item in the list, in my case I'm just assigning that item to the 'currentProjectItem' property directly as seen below. The reason being, is the selected one can possibly be changed by the user and i don't want the original one in the list to be affected. Are there any issues in the way my code is written? Only ask because im a bit new to C++ and Qt. The app seems to be working as expected, I'm just not sure if what im doing is unstable.

I wasn't sure if i needed to set currentProjectItem = nullprt before assigning it a new value or something like that.

.h file

```<code>class AppCore : public QObject {
  Q_OBJECT

  Q_PROPERTY(QList<ProjectItem> projectItems READ getProjectItems
                 NOTIFY projectItemsChanged)
  Q_PROPERTY(
      ProjectItem currentProjectItem READ currentProjectItem WRITE
          setCurrentProjectItem  NOTIFY currentProjectItemChanged)

public:
  ~AppCore();

  static AppCore *instance();

  ProjectItem currentProjectItem ();

  void setCurrentProjectItem(const ProjectItem &item);

private:
  static AppCore *m_instance;

  explicit AppCore(QObject *parent = nullptr);

  QList<ProjectItem> getProjectItems() const;
  ProjectItem m_currentProjectItem ;

signals:
  void projectItemsChanged();
  void currentProjectItemChanged();
};

</code>```

.cpp file

```<code>void AppCore::setCurrentProjectItem (const &ProjectItem&item) {
  m_currentProjectItem = item;
  emit currentProjectItemChanged();
}
</code>```

Body:
In my main app class I have a property which contains a list of the ProjectItems. Within my application a user can specifically select a an item in that list which I then assign to the property called currentProjectItem.

I know in same applications you would use a pointer here to point to the selected item in the list, in my case I'm just assigning that item to the 'currentProjectItem' property directly as seen below. The reason being, is the selected one can possibly be changed by the user and i don't want the original one in the list to be affected. Are there any issues in the way my code is written? Only ask because im a bit new to C++ and Qt. The app seems to be working as expected, I'm just not sure if what im doing is unstable.

I wasn't sure if i needed to set currentProjectItem = nullprt before assigning it a new value or something like that.

.h file

class AppCore : public QObject {
  Q_OBJECT

  Q_PROPERTY(QList<ProjectItem> projectItems READ getProjectItems
                 NOTIFY projectItemsChanged)
  Q_PROPERTY(
      ProjectItem currentProjectItem READ currentProjectItem WRITE
          setCurrentProjectItem  NOTIFY currentProjectItemChanged)

public:
  ~AppCore();

  static AppCore *instance();

  ProjectItem currentProjectItem ();

  void setCurrentProjectItem(const ProjectItem &item);

private:
  static AppCore *m_instance;

  explicit AppCore(QObject *parent = nullptr);

  QList<ProjectItem> getProjectItems() const;
  ProjectItem m_currentProjectItem ;

signals:
  void projectItemsChanged();
  void currentProjectItemChanged();
};

.cpp file

void AppCore::setCurrentProjectItem (const &ProjectItem&item) {
  m_currentProjectItem = item;
  emit currentProjectItemChanged();
}


问:
How to add read more button and in that when we touch it show some extra text?
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Perspiciatis voluptates quaerat voluptas quidem reiciendis, non maiores a, autem nobis, quos quisquam earum! Incidunt, nisi unde, facere atque eveniet eum ut odit quisquam hic consectetur animi tenetur nihil enim repudiandae soluta laudantium laborum est quis iste harum consequuntur. Illum, nemo explicabo!

    </p>
<button type="submit">Read more</button>
</body>
</html>
</code>```

First I take a paragraph and a button. When we click at the button it more text

Body:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Perspiciatis voluptates quaerat voluptas quidem reiciendis, non maiores a, autem nobis, quos quisquam earum! Incidunt, nisi unde, facere atque eveniet eum ut odit quisquam hic consectetur animi tenetur nihil enim repudiandae soluta laudantium laborum est quis iste harum consequuntur. Illum, nemo explicabo!

<button type="submit">Read more</button>

First I take a paragraph and a button. When we click at the button it more text


问:
Display an image from a URL using request()
I have a list of dictionaries containing data on products. Each product has one image URL. The data looks very much like below:

products_dicts = [
  {
    "uniq_id": "123987",
    "sku": "123",
    "name": "ABC",
    "cat": "DEF",
    "cat_tree": "A|B|C",
    "image_urls": "http://sitecom/image1.tif"
  },
  {
    "uniq_id": "987123",
    "sku": "987",
    "name": "GHI",
    "cat": "JKL",
    "cat_tree": "Z|Y|X",
    "image_urls": "http://sitecom/img/image2.tif"
  }
]
```
<p>I want to use the <code>urllib.request()</code> to retrieve the image and display it for <code>product</code> with the <code>uniq_id</code> equals to <code>123987</code>. I have started with the following:</p>
<pre class="lang-py prettyprint-override"><code>import urllib.request
from PIL import Image

q = [x['product_image_urls'] for x in products_dicts if x['uniq_id'] == '123987']
</code>```

Body:
I have a list of dictionaries containing data on products. Each product has one image URL. The data looks very much like below:

products_dicts = [
  {
    "uniq_id": "123987",
    "sku": "123",
    "name": "ABC",
    "cat": "DEF",
    "cat_tree": "A|B|C",
    "image_urls": "http://sitecom/image1.tif"
  },
  {
    "uniq_id": "987123",
    "sku": "987",
    "name": "GHI",
    "cat": "JKL",
    "cat_tree": "Z|Y|X",
    "image_urls": "http://sitecom/img/image2.tif"
  }
]

I want to use the urllib.request() to retrieve the image and display it for product with the uniq_id equals to 123987. I have started with the following:

import urllib.request
from PIL import Image

q = [x['product_image_urls'] for x in products_dicts if x['uniq_id'] == '123987']


问:
Editor.js How to save editor content

The question

https://github.com/codex-team/editor.js/issues/2212

This is the link I posted.
I get an error as per this link. What can I do to fix this problem?

I looked for a site that might be helpful but didn't find much.

Title: Editor.js How to save editor content


问:
Proper toggling between play/pause buttons in chat app with audio messages defined
I have an app that has a fragment with chat to admin. View is represented by a recyclerView. Ofc I'm at the beginning of app, but I have some problems.

1- Here is the view. If we press "play button" in a message, its goes invisible and "pause button" appears and vice versa. After recording two audio and trying to "play" the second message after first one,  first message button view stays as a "pause button" and don't reset. I want "pause button" of first message change back to "play button" (like it's ready to play from start) and there is my seekBar that has to reset too. Mediaplayer works fine. How can I depend my second message as an item of RecyclerView to first message and do the toggle properly?

2- My second question is more general. When I scroll down my messages list and scroll back up while my audio message is playing, it's stop playing. I know how RecyclerView works about recycle messages on scroll but how can I prevent or deal with it?

Searched a lot but couldn't find a proper answer to my problem. Here is a part of my code (sorry if it's messy):

```<code>import android.media.MediaPlayer;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import java.io.IOException;
import java.util.ArrayList;

import saman.zamani.persiandate.PersianDate;
import saman.zamani.persiandate.PersianDateFormat;

public class ChatMessageRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    //message kinds
    final int DATE_MESSAGE = 1;
    final int SENT_TEXT_MESSAGE = 2;
    final int RECEIVED_TEXT_MESSAGE = 3;
    final int SENT_AUDIO_MESSAGE = 4;
    final int RECEIVED_AUDIO_MESSAGE = 5;
    final int SENT_REPLY_MESSAGE = 6;
    final int RECEIVED_REPLY_MESSAGE = 7;
    final int SENT_REPLY_AUDIO = 8;
    final int RECEIVED_REPLY_AUDIO = 9;

    ArrayList<ChatMessageBuilder> messageList;
    static String lastPlayed = "", currentlyPlaying = "";
    static Handler handler = new Handler();
    static final int delay = 50;

    public ChatMessageRecyclerViewAdapter(ArrayList<ChatMessageBuilder> messageList) {
        this.messageList = messageList;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    // Determines the appropriate ViewType according to the sender or receiver of the message.
    @Override
    public int getItemViewType(int position) {
        if (messageList.get(position).getMessageType() == SENT_TEXT_MESSAGE)
            return SENT_TEXT_MESSAGE;

        else if (messageList.get(position).getMessageType() == RECEIVED_TEXT_MESSAGE)
            return RECEIVED_TEXT_MESSAGE;

        else if (messageList.get(position).getMessageType() == SENT_AUDIO_MESSAGE)
            return SENT_AUDIO_MESSAGE;

        else if (messageList.get(position).getMessageType() == RECEIVED_AUDIO_MESSAGE)
            return RECEIVED_AUDIO_MESSAGE;

        else if (messageList.get(position).getMessageType() == RECEIVED_REPLY_MESSAGE)
            return RECEIVED_REPLY_MESSAGE;

        else if (messageList.get(position).getMessageType() == SENT_REPLY_MESSAGE)
            return SENT_REPLY_MESSAGE;

        else if (messageList.get(position).getMessageType() == SENT_REPLY_AUDIO)
            return SENT_REPLY_AUDIO;

        else if (messageList.get(position).getMessageType() == RECEIVED_REPLY_AUDIO)
            return RECEIVED_REPLY_AUDIO;

        else
            return DATE_MESSAGE;
    }

    // Inflates the appropriate layout according to the ViewType.
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;

        if (viewType == SENT_TEXT_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_sent_message_layout, parent, false);
            return new SentMessageHolder(view);
        } else if (viewType == RECEIVED_TEXT_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_received_message_layout, parent, false);
            return new ReceivedMessageHolder(view);
        } else if (viewType == SENT_AUDIO_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_sent_recording_message_layout, parent, false);
            return new SentAudioMessageHolder(view);
        } else if (viewType == RECEIVED_AUDIO_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_received_recording_message_layout, parent, false);
            return new ReceivedAudioMessageHolder(view);
        } else if (viewType == SENT_REPLY_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_sent_reply_message_message_layout, parent, false);
            return new SentReplyMessageHolder(view);
        } else if (viewType == RECEIVED_REPLY_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_received_reply_message_message_layout, parent, false);
            return new ReceivedReplyMessageHolder(view);
        } else if (viewType == SENT_REPLY_AUDIO) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_sent_reply_message_audio_layout, parent, false);
            return new SentReplyAudioHolder(view);
        } else if (viewType == RECEIVED_REPLY_AUDIO) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_received_reply_message_audio_layout, parent, false);
            return new ReceivedReplyAudioHolder(view);
        } else {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_date_message_layout, parent, false);
            return new DateMessageHolder(view);
        }

    }

    // Passes the message object to a ViewHolder so that the contents can be bound to UI.
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ChatMessageBuilder message = messageList.get(position);

        switch (holder.getItemViewType()) {
            case SENT_TEXT_MESSAGE:
                ((SentMessageHolder) holder).bind(message);
                break;
            case RECEIVED_TEXT_MESSAGE:
                ((ReceivedMessageHolder) holder).bind(message);
                break;
            case SENT_AUDIO_MESSAGE:
                ((SentAudioMessageHolder) holder).bind(message);
                break;
            case RECEIVED_AUDIO_MESSAGE:
                ((ReceivedAudioMessageHolder) holder).bind(message);
                break;
            case SENT_REPLY_MESSAGE:
                ((SentReplyMessageHolder) holder).bind(message);
                break;
            case RECEIVED_REPLY_MESSAGE:
                ((ReceivedReplyMessageHolder) holder).bind(message);
                break;
            case SENT_REPLY_AUDIO:
                ((SentReplyAudioHolder) holder).bind(message);
                break;
            case RECEIVED_REPLY_AUDIO:
                ((ReceivedReplyAudioHolder) holder).bind(message);
                break;
            case DATE_MESSAGE:
                ((DateMessageHolder) holder).bind(message);
                break;
        }
    }

//...

//type of send an Audio Message
    private static class SentAudioMessageHolder extends RecyclerView.ViewHolder {
        TextView messageTime, messageDuration, messageCurrentPosition;
        ImageView messageStatus, play, pause;
        SeekBar seekBar;

        public SentAudioMessageHolder(@NonNull View itemView) {
            super(itemView);
            messageTime = itemView.findViewById(R.id.messageTime);
            messageStatus = itemView.findViewById(R.id.messageStatus);
            play = itemView.findViewById(R.id.play);
            pause = itemView.findViewById(R.id.pause);
            seekBar = itemView.findViewById(R.id.recordSeekBar);
            messageDuration = itemView.findViewById(R.id.messageDuration);
            messageCurrentPosition = itemView.findViewById(R.id.messageCurrentPosition);
        }

        void bind(ChatMessageBuilder message) {
            messageTime.setText(message.getMessageTime().substring(message.getMessageTime().length() - 5));
            messageStatus.setImageResource(R.drawable.ic_message_sent);
            final int[] currentTime = {0};

            if (!message.getMessageText().equals(lastPlayed)) {
                try {
                    ChatMessageInterfaceFragment.audioPlayer.reset();
                    ChatMessageInterfaceFragment.audioPlayer.setDataSource(message.getMessageText());
                    ChatMessageInterfaceFragment.audioPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                seekBar.setProgress(0);
                messageDuration.setText(createTime(ChatMessageInterfaceFragment.audioPlayer.getDuration()));
                lastPlayed = message.getMessageText();
            }

            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {}

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {}

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    ChatMessageInterfaceFragment.audioPlayer.seekTo(seekBar.getProgress());
                }
            });

            play.setOnClickListener(view -> {
                handler.removeCallbacksAndMessages(null);

                if (!message.getMessageText().equals(currentlyPlaying)) {
                    try {
                        ChatMessageInterfaceFragment.audioPlayer.reset();
                        ChatMessageInterfaceFragment.audioPlayer.setDataSource(message.getMessageText());
                        ChatMessageInterfaceFragment.audioPlayer.prepare();

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

                    seekBar.setMax(ChatMessageInterfaceFragment.audioPlayer.getDuration());
                    messageDuration.setText(createTime(ChatMessageInterfaceFragment.audioPlayer.getDuration()));
                    currentlyPlaying = message.getMessageText();
                }

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        messageCurrentPosition.setText(createTime(ChatMessageInterfaceFragment.audioPlayer.getCurrentPosition()));
                        seekBar.setProgress(ChatMessageInterfaceFragment.audioPlayer.getCurrentPosition());
                        handler.postDelayed(this, delay);
                    }
                }, delay);

                messageCurrentPosition.setVisibility(View.INVISIBLE);
                messageDuration.setVisibility(View.VISIBLE);
                ChatMessageInterfaceFragment.audioPlayer.seekTo(currentTime[0]);
                messageCurrentPosition.setText(createTime(currentTime[0]));
                ChatMessageInterfaceFragment.audioPlayer.start();
                play.setVisibility(View.INVISIBLE);
                pause.setVisibility(View.VISIBLE);
                messageCurrentPosition.setVisibility(View.VISIBLE);
                messageDuration.setVisibility(View.INVISIBLE);

                ChatMessageInterfaceFragment.audioPlayer.setOnCompletionListener(mp -> {
                    seekBar.setProgress(0);
                    currentTime[0] = 0;
                    ChatMessageInterfaceFragment.audioPlayer.seekTo(0);
                    pause.setVisibility(View.INVISIBLE);
                    play.setVisibility(View.VISIBLE);
                    messageCurrentPosition.setVisibility(View.INVISIBLE);
                    messageDuration.setVisibility(View.VISIBLE);
                    handler.removeCallbacksAndMessages(null);
                });

            });

            pause.setOnClickListener(view -> {
                if (currentlyPlaying.equals(message.getMessageText())) {
                    currentTime[0] = ChatMessageInterfaceFragment.audioPlayer.getCurrentPosition();
                    ChatMessageInterfaceFragment.audioPlayer.pause();
                }
                play.setVisibility(View.VISIBLE);
                pause.setVisibility(View.INVISIBLE);
            });
        }
    }

//...

    public static String createTime(int duration) {
        String time = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        if (min < 10) {
            time += "0";
        }
        time += min + ":";

        if (sec < 10) {
            time += "0";
        }
        time += sec;
        return time;
    }

}

</code>```

I removed extra codes to be more clear. Thanks in advance.

Body:
I have an app that has a fragment with chat to admin. View is represented by a recyclerView. Ofc I'm at the beginning of app, but I have some problems.

1- Here is the view. If we press "play button" in a message, its goes invisible and "pause button" appears and vice versa. After recording two audio and trying to "play" the second message after first one,  first message button view stays as a "pause button" and don't reset. I want "pause button" of first message change back to "play button" (like it's ready to play from start) and there is my seekBar that has to reset too. Mediaplayer works fine. How can I depend my second message as an item of RecyclerView to first message and do the toggle properly?

2- My second question is more general. When I scroll down my messages list and scroll back up while my audio message is playing, it's stop playing. I know how RecyclerView works about recycle messages on scroll but how can I prevent or deal with it?

Searched a lot but couldn't find a proper answer to my problem. Here is a part of my code (sorry if it's messy):

import android.media.MediaPlayer;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import java.io.IOException;
import java.util.ArrayList;

import saman.zamani.persiandate.PersianDate;
import saman.zamani.persiandate.PersianDateFormat;

public class ChatMessageRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    //message kinds
    final int DATE_MESSAGE = 1;
    final int SENT_TEXT_MESSAGE = 2;
    final int RECEIVED_TEXT_MESSAGE = 3;
    final int SENT_AUDIO_MESSAGE = 4;
    final int RECEIVED_AUDIO_MESSAGE = 5;
    final int SENT_REPLY_MESSAGE = 6;
    final int RECEIVED_REPLY_MESSAGE = 7;
    final int SENT_REPLY_AUDIO = 8;
    final int RECEIVED_REPLY_AUDIO = 9;

    ArrayList<ChatMessageBuilder> messageList;
    static String lastPlayed = "", currentlyPlaying = "";
    static Handler handler = new Handler();
    static final int delay = 50;

    public ChatMessageRecyclerViewAdapter(ArrayList<ChatMessageBuilder> messageList) {
        this.messageList = messageList;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    // Determines the appropriate ViewType according to the sender or receiver of the message.
    @Override
    public int getItemViewType(int position) {
        if (messageList.get(position).getMessageType() == SENT_TEXT_MESSAGE)
            return SENT_TEXT_MESSAGE;

        else if (messageList.get(position).getMessageType() == RECEIVED_TEXT_MESSAGE)
            return RECEIVED_TEXT_MESSAGE;

        else if (messageList.get(position).getMessageType() == SENT_AUDIO_MESSAGE)
            return SENT_AUDIO_MESSAGE;

        else if (messageList.get(position).getMessageType() == RECEIVED_AUDIO_MESSAGE)
            return RECEIVED_AUDIO_MESSAGE;

        else if (messageList.get(position).getMessageType() == RECEIVED_REPLY_MESSAGE)
            return RECEIVED_REPLY_MESSAGE;

        else if (messageList.get(position).getMessageType() == SENT_REPLY_MESSAGE)
            return SENT_REPLY_MESSAGE;

        else if (messageList.get(position).getMessageType() == SENT_REPLY_AUDIO)
            return SENT_REPLY_AUDIO;

        else if (messageList.get(position).getMessageType() == RECEIVED_REPLY_AUDIO)
            return RECEIVED_REPLY_AUDIO;

        else
            return DATE_MESSAGE;
    }

    // Inflates the appropriate layout according to the ViewType.
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;

        if (viewType == SENT_TEXT_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_sent_message_layout, parent, false);
            return new SentMessageHolder(view);
        } else if (viewType == RECEIVED_TEXT_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_received_message_layout, parent, false);
            return new ReceivedMessageHolder(view);
        } else if (viewType == SENT_AUDIO_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_sent_recording_message_layout, parent, false);
            return new SentAudioMessageHolder(view);
        } else if (viewType == RECEIVED_AUDIO_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_received_recording_message_layout, parent, false);
            return new ReceivedAudioMessageHolder(view);
        } else if (viewType == SENT_REPLY_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_sent_reply_message_message_layout, parent, false);
            return new SentReplyMessageHolder(view);
        } else if (viewType == RECEIVED_REPLY_MESSAGE) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_received_reply_message_message_layout, parent, false);
            return new ReceivedReplyMessageHolder(view);
        } else if (viewType == SENT_REPLY_AUDIO) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_sent_reply_message_audio_layout, parent, false);
            return new SentReplyAudioHolder(view);
        } else if (viewType == RECEIVED_REPLY_AUDIO) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_received_reply_message_audio_layout, parent, false);
            return new ReceivedReplyAudioHolder(view);
        } else {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_chat_date_message_layout, parent, false);
            return new DateMessageHolder(view);
        }

    }

    // Passes the message object to a ViewHolder so that the contents can be bound to UI.
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ChatMessageBuilder message = messageList.get(position);

        switch (holder.getItemViewType()) {
            case SENT_TEXT_MESSAGE:
                ((SentMessageHolder) holder).bind(message);
                break;
            case RECEIVED_TEXT_MESSAGE:
                ((ReceivedMessageHolder) holder).bind(message);
                break;
            case SENT_AUDIO_MESSAGE:
                ((SentAudioMessageHolder) holder).bind(message);
                break;
            case RECEIVED_AUDIO_MESSAGE:
                ((ReceivedAudioMessageHolder) holder).bind(message);
                break;
            case SENT_REPLY_MESSAGE:
                ((SentReplyMessageHolder) holder).bind(message);
                break;
            case RECEIVED_REPLY_MESSAGE:
                ((ReceivedReplyMessageHolder) holder).bind(message);
                break;
            case SENT_REPLY_AUDIO:
                ((SentReplyAudioHolder) holder).bind(message);
                break;
            case RECEIVED_REPLY_AUDIO:
                ((ReceivedReplyAudioHolder) holder).bind(message);
                break;
            case DATE_MESSAGE:
                ((DateMessageHolder) holder).bind(message);
                break;
        }
    }

//...

//type of send an Audio Message
    private static class SentAudioMessageHolder extends RecyclerView.ViewHolder {
        TextView messageTime, messageDuration, messageCurrentPosition;
        ImageView messageStatus, play, pause;
        SeekBar seekBar;

        public SentAudioMessageHolder(@NonNull View itemView) {
            super(itemView);
            messageTime = itemView.findViewById(R.id.messageTime);
            messageStatus = itemView.findViewById(R.id.messageStatus);
            play = itemView.findViewById(R.id.play);
            pause = itemView.findViewById(R.id.pause);
            seekBar = itemView.findViewById(R.id.recordSeekBar);
            messageDuration = itemView.findViewById(R.id.messageDuration);
            messageCurrentPosition = itemView.findViewById(R.id.messageCurrentPosition);
        }

        void bind(ChatMessageBuilder message) {
            messageTime.setText(message.getMessageTime().substring(message.getMessageTime().length() - 5));
            messageStatus.setImageResource(R.drawable.ic_message_sent);
            final int[] currentTime = {0};

            if (!message.getMessageText().equals(lastPlayed)) {
                try {
                    ChatMessageInterfaceFragment.audioPlayer.reset();
                    ChatMessageInterfaceFragment.audioPlayer.setDataSource(message.getMessageText());
                    ChatMessageInterfaceFragment.audioPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                seekBar.setProgress(0);
                messageDuration.setText(createTime(ChatMessageInterfaceFragment.audioPlayer.getDuration()));
                lastPlayed = message.getMessageText();
            }

            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {}

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {}

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    ChatMessageInterfaceFragment.audioPlayer.seekTo(seekBar.getProgress());
                }
            });

            play.setOnClickListener(view -> {
                handler.removeCallbacksAndMessages(null);

                if (!message.getMessageText().equals(currentlyPlaying)) {
                    try {
                        ChatMessageInterfaceFragment.audioPlayer.reset();
                        ChatMessageInterfaceFragment.audioPlayer.setDataSource(message.getMessageText());
                        ChatMessageInterfaceFragment.audioPlayer.prepare();

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

                    seekBar.setMax(ChatMessageInterfaceFragment.audioPlayer.getDuration());
                    messageDuration.setText(createTime(ChatMessageInterfaceFragment.audioPlayer.getDuration()));
                    currentlyPlaying = message.getMessageText();
                }

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        messageCurrentPosition.setText(createTime(ChatMessageInterfaceFragment.audioPlayer.getCurrentPosition()));
                        seekBar.setProgress(ChatMessageInterfaceFragment.audioPlayer.getCurrentPosition());
                        handler.postDelayed(this, delay);
                    }
                }, delay);

                messageCurrentPosition.setVisibility(View.INVISIBLE);
                messageDuration.setVisibility(View.VISIBLE);
                ChatMessageInterfaceFragment.audioPlayer.seekTo(currentTime[0]);
                messageCurrentPosition.setText(createTime(currentTime[0]));
                ChatMessageInterfaceFragment.audioPlayer.start();
                play.setVisibility(View.INVISIBLE);
                pause.setVisibility(View.VISIBLE);
                messageCurrentPosition.setVisibility(View.VISIBLE);
                messageDuration.setVisibility(View.INVISIBLE);

                ChatMessageInterfaceFragment.audioPlayer.setOnCompletionListener(mp -> {
                    seekBar.setProgress(0);
                    currentTime[0] = 0;
                    ChatMessageInterfaceFragment.audioPlayer.seekTo(0);
                    pause.setVisibility(View.INVISIBLE);
                    play.setVisibility(View.VISIBLE);
                    messageCurrentPosition.setVisibility(View.INVISIBLE);
                    messageDuration.setVisibility(View.VISIBLE);
                    handler.removeCallbacksAndMessages(null);
                });

            });

            pause.setOnClickListener(view -> {
                if (currentlyPlaying.equals(message.getMessageText())) {
                    currentTime[0] = ChatMessageInterfaceFragment.audioPlayer.getCurrentPosition();
                    ChatMessageInterfaceFragment.audioPlayer.pause();
                }
                play.setVisibility(View.VISIBLE);
                pause.setVisibility(View.INVISIBLE);
            });
        }
    }

//...

    public static String createTime(int duration) {
        String time = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        if (min < 10) {
            time += "0";
        }
        time += min + ":";

        if (sec < 10) {
            time += "0";
        }
        time += sec;
        return time;
    }

}

I removed extra codes to be more clear. Thanks in advance.


问:
how to use JSON data in nextjs
I'm making an test e-commerce store to learn nextjs and I am having trouble implementing stripe as my payment processor. I'm sending an array of objects to my nextjs api route and I am receiving data that looks like this in my console.log(data):

[{"id":3,"title":"Mens Cotton Jacket","price":55.99,"description":"great outerwear jackets for Spring/Autumn/Winter, suitable for many occasions, such as working, hiking, camping, mountain/rock climbing, cycling, traveling or other outdoors. Good gift choice for you or your family member. A warm hearted love to Father, husband or son in this thanksgiving or Christmas Day.","category":"men's clothing","image":"https://fakestoreapi.com/img/71li-ujtlUL.AC_UX679.jpg"}]

This looks like an array to me, so when I use the data.map array method I get the error .map is not a function. This is also what is recommended in this post How to use JSON data

here is how I am sending the data to the api route:
basket is my array of objects

```<code>    const postData = async () => {
      const response = await fetch("/api/checkout_sessions", {
        method: "POST",
        body: JSON.stringify(basket),
      })
      return response.json();
    };
</code>```

this function is called on a onClick in a button.

here is how I am receiving the data but its not working how I expect. What I want is the transformedItems to make a new array from the array sent by the client and used in the line_items param like below. Again the error I get is that .map is not a function. I know that I am receiving  data but I am not sure how to use it correctly

```<code>const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

export default async function handler(req, res) {

  if (req.method === 'POST') {

    const data = req.body
      console.log(data)

    const transformedItems = data.map(items => ({
      price_data: {
      unit_amount: items.price,
      currency: 'usd',
      product_data: {
        name: items.title,
        description: items.description,
      },
    },
    quantity: 1,
  }))

    try {
      // Create Checkout Sessions from body params.
      const session = await stripe.checkout.sessions.create({
        shipping_address_collection: {
          allowed_countries: ["US", "CA", "GB"],
        },
       line_items: transformedItems,

        mode: 'payment',
        success_url: `${req.headers.origin}/?success=true`,
        cancel_url: `${req.headers.origin}/?canceled=true`,
      });
      res.redirect(303, session.url);
    } catch (err) {
      res.status(err.statusCode || 500).json(err.message);
    }
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}
</code>```

based on the questions asked in the comments when I try the JSON.parse I get this error - TypeError: Cannot convert object to primitive value

Title: how to use JSON data in nextjs

Body:
I'm making an test e-commerce store to learn nextjs and I am having trouble implementing stripe as my payment processor. I'm sending an array of objects to my nextjs api route and I am receiving data that looks like this in my console.log(data):

[{"id":3,"title":"Mens Cotton Jacket","price":55.99,"description":"great outerwear jackets for Spring/Autumn/Winter, suitable for many occasions, such as working, hiking, camping, mountain/rock climbing, cycling, traveling or other outdoors. Good gift choice for you or your family member. A warm hearted love to Father, husband or son in this thanksgiving or Christmas Day.","category":"men's clothing","image":"https://fakestoreapi.com/img/71li-ujtlUL.AC_UX679.jpg"}]

This looks like an array to me, so when I use the data.map array method I get the error .map is not a function. This is also what is recommended in this post How to use JSON data

here is how I am sending the data to the api route:
basket is my array of objects

    const postData = async () => {
      const response = await fetch("/api/checkout_sessions", {
        method: "POST",
        body: JSON.stringify(basket),
      })
      return response.json();
    };

this function is called on a onClick in a button.

here is how I am receiving the data but its not working how I expect. What I want is the transformedItems to make a new array from the array sent by the client and used in the line_items param like below. Again the error I get is that .map is not a function. I know that I am receiving  data but I am not sure how to use it correctly

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

export default async function handler(req, res) {

  if (req.method === 'POST') {

    const data = req.body
      console.log(data)

    const transformedItems = data.map(items => ({
      price_data: {
      unit_amount: items.price,
      currency: 'usd',
      product_data: {
        name: items.title,
        description: items.description,
      },
    },
    quantity: 1,
  }))

    try {
      // Create Checkout Sessions from body params.
      const session = await stripe.checkout.sessions.create({
        shipping_address_collection: {
          allowed_countries: ["US", "CA", "GB"],
        },
       line_items: transformedItems,

        mode: 'payment',
        success_url: `${req.headers.origin}/?success=true`,
        cancel_url: `${req.headers.origin}/?canceled=true`,
      });
      res.redirect(303, session.url);
    } catch (err) {
      res.status(err.statusCode || 500).json(err.message);
    }
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}

based on the questions asked in the comments when I try the JSON.parse I get this error - TypeError: Cannot convert object to primitive value


问:
how do I find out what "pandas._libs.tslibs.timestamps.Timestamp" is aliased to without googling
Train of thoughts:

how do we check datatypes in pandas?

many ways, isinstance(), type(), sr.dtype, df.dtypes etc

the next step is, what's the exact word I should put in your source code to do this:

type(myvar) == <what do I put in here?>

ok, the simpliest way to find out is to try it out:

```<code>type(myvar)
>> pandas._libs.tslibs.timestamps.Timestamp
</code>```

so, the following is good and all, but that's quite a mouthful,

type(myvar) == pandas._libs.tslibs.timestamps.Timestamp

Question

I happen to know that type(myvar) == pandas.Timestamp would work as well for this particular data type. I would like to know a general way of finding out if and what python types are aliased to something shorter.

Body:
Train of thoughts:

how do we check datatypes in pandas?

many ways, isinstance(), type(), sr.dtype, df.dtypes etc

the next step is, what's the exact word I should put in your source code to do this:

type(myvar) == <what do I put in here?>

ok, the simpliest way to find out is to try it out:

type(myvar)
>> pandas._libs.tslibs.timestamps.Timestamp

so, the following is good and all, but that's quite a mouthful,

type(myvar) == pandas._libs.tslibs.timestamps.Timestamp

Question

I happen to know that type(myvar) == pandas.Timestamp would work as well for this particular data type. I would like to know a general way of finding out if and what python types are aliased to something shorter.


问:
My Executable Jar file of Maven project run in IDE but not in the Terminal
My .executable jar do not show me the same in the IDE console and the Terminal

Hi guys,

So I am working on a Maven project with JavaFX in IntelliJ and I need to open the application by using a .executable jar file.

When I run the jar file from the IDE, the console show me my project but when I type java -jar myproject-1.0-SNAPSHOT.jar, I get this error :

```<code>Error: Could not find or load main class mypackage.myproject.Main
Caused by: java.lang.NoClassDefFoundError: javafx/application/Application

</code>```

I used to have the same error when I would click on run in the IDE but I added in the Run > Config > VM options --module-path "mypath\openjfx-19_windows-x64_bin-sdk\javafx-sdk-19\lib" --add-modules javafx.controls,javafx.fxml.

I don't understand why it would run on IntelliJ but not in the Terminal since I added this. I also cleaned, recompiled, build...

Please help me ! Thank you

Body:
My .executable jar do not show me the same in the IDE console and the Terminal

Hi guys,

So I am working on a Maven project with JavaFX in IntelliJ and I need to open the application by using a .executable jar file.

When I run the jar file from the IDE, the console show me my project but when I type java -jar myproject-1.0-SNAPSHOT.jar, I get this error :

Error: Could not find or load main class mypackage.myproject.Main
Caused by: java.lang.NoClassDefFoundError: javafx/application/Application

I used to have the same error when I would click on run in the IDE but I added in the Run > Config > VM options --module-path "mypath\openjfx-19_windows-x64_bin-sdk\javafx-sdk-19\lib" --add-modules javafx.controls,javafx.fxml.

I don't understand why it would run on IntelliJ but not in the Terminal since I added this. I also cleaned, recompiled, build...

Please help me ! Thank you


问:
Permutations in Java with Conditions
I am trying to find a way to get all permutations of ABCDEF but C and E should be side by side of each other how can I do so using Java?

I tried using this method but I am not getting the desired op

```<code>public class PUJ {

    {

        // If string is empty
        if (str.length() == 0) {
            System.out.print(ans + " ");
            return;
        }

        for (int i = 0; i < str.length(); i++) {

            // ith character of str
            char ch = str.charAt(i);

            // Rest of the string after excluding
            // the ith character

            String ros = str.substring(0, i) +
                        str.substring(i + 1);

            // Recursive call
            printPermutn(ros, ans + ch);

        }
    }

    // Driver code
    public static void main(String[] args)
    {
        String s = "ABCDEF";
        if(s.charAt(i)==C && s.charAt(i+1)==E){
        printPermutn(s, "");
        }
    }
}
</code>```

Title: Permutations in Java with Conditions

Body:
I am trying to find a way to get all permutations of ABCDEF but C and E should be side by side of each other how can I do so using Java?

I tried using this method but I am not getting the desired op

public class PUJ {

    {

        // If string is empty
        if (str.length() == 0) {
            System.out.print(ans + " ");
            return;
        }

        for (int i = 0; i < str.length(); i++) {

            // ith character of str
            char ch = str.charAt(i);

            // Rest of the string after excluding
            // the ith character

            String ros = str.substring(0, i) +
                        str.substring(i + 1);

            // Recursive call
            printPermutn(ros, ans + ch);

        }
    }

    // Driver code
    public static void main(String[] args)
    {
        String s = "ABCDEF";
        if(s.charAt(i)==C && s.charAt(i+1)==E){
        printPermutn(s, "");
        }
    }
}


问:
Open CV Blur Face Detection video to Google Cloud Storage
My code tries to upload blob but for some reason when i check in google cloud storage the blob has no seconds and is blank screen.

I tried searching for answers, but no one has ever had the same problem as me so I'm quite confused.

```<code>def upload_blob(bucket_name, source_file_name, destination_blob_name)

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)

    print(
        f"File {source_file_name} uploaded to {destination_blob_name}."
    )

@app.route("/upload")
def upload():
    video = cv2.VideoCapture("https://storage.googleapis.com/blur-video-posts/Man%20-%20122389.mp4")

    face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

    kernel = np.ones((20, 20), np.float32) / 400

    frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = video.get(cv2.CAP_PROP_FPS)

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter("blurred_video.mp4", fourcc, fps, (frame_width, frame_height))

    while (video.isOpened()):
        success, frame = video.read()

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        if not success:
            break

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        faces = face_cascade.detectMultiScale(gray, 1.3, 5)

        for (x, y, w, h) in faces:
            face = frame[y:y+h, x:x+w]

            blurred_face = cv2.filter2D(face, -1, kernel)

            frame[y:y+h, x:x+w] = blurred_face

        out.write(frame)

    video.release()
    out.release()

    # Destroy all windows
    cv2.destroyAllWindows()

    upload_blob('blur-video-posts', "blurred_video.mp4", "blurred_video")
    return "Done"
</code>```

Use OpenCV to read a video file from a URL

Use a Haar cascade classifier to detect faces in the video

Blur the detected faces in the video

Use Google Cloud Storage to upload the blurred video to a bucket

Body:
My code tries to upload blob but for some reason when i check in google cloud storage the blob has no seconds and is blank screen.

I tried searching for answers, but no one has ever had the same problem as me so I'm quite confused.

def upload_blob(bucket_name, source_file_name, destination_blob_name)

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)

    print(
        f"File {source_file_name} uploaded to {destination_blob_name}."
    )

@app.route("/upload")
def upload():
    video = cv2.VideoCapture("https://storage.googleapis.com/blur-video-posts/Man%20-%20122389.mp4")

    face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

    kernel = np.ones((20, 20), np.float32) / 400

    frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = video.get(cv2.CAP_PROP_FPS)

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter("blurred_video.mp4", fourcc, fps, (frame_width, frame_height))

    while (video.isOpened()):
        success, frame = video.read()

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        if not success:
            break

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        faces = face_cascade.detectMultiScale(gray, 1.3, 5)

        for (x, y, w, h) in faces:
            face = frame[y:y+h, x:x+w]

            blurred_face = cv2.filter2D(face, -1, kernel)

            frame[y:y+h, x:x+w] = blurred_face

        out.write(frame)

    video.release()
    out.release()

    # Destroy all windows
    cv2.destroyAllWindows()

    upload_blob('blur-video-posts', "blurred_video.mp4", "blurred_video")
    return "Done"

Use OpenCV to read a video file from a URL

Use a Haar cascade classifier to detect faces in the video

Blur the detected faces in the video

Use Google Cloud Storage to upload the blurred video to a bucket


问:
Save class in a file
first, sorry for my english, I'm french !
I am in the process of creating an account (class) and connecting to it. I use a file where I put my data.

I have a question about my code below (I am a python beginner)
Code :

```<code>import random
import string

#Définition des classes et des fonctions
class compte:

  def __init__(self, user, mdp):
    self.user = user
    self.mdp = mdp
    self.poids = "not defined"
    self.taille = "not defined"
    self.IMC = "not defined"
    self.test = 1
    #self.adresse = adresse
    self.salle_attribuée = "not defined"
    #self.objectif = objectif

  def cIMC(self):
    print("ok")

def create():
  chaine_minuscule = string.ascii_lowercase
  id_compte = "".join(random.choice(chaine_minuscule) for i in range(5))
  num = id_compte
  user = input("Username: ")
  mdp = input("Password: ")
  id_compte = compte(user, mdp)
  f = open("users.txt", "a")
  texte = [num, "|", id_compte.user, "|", id_compte.mdp]
  for t in texte:
    f.write(t)
  f.write('\n')
  print('\n------------Vous avez bien créé votre compte : ------------\n')
  print("Username = ", id_compte.user, "\nPassword = ", id_compte.mdp)

def login():
  user = input("Username: ")
  mdp = input("Password: ")
  f = open("users.txt", "r")
  for line in f.readlines():
    nbr, us, pw = line.strip().split("|")
    if (user == us) and (mdp == pw):
      print("\nLogin successful!")
      return True, nbr
  print("Wrong username/password")
  return False

connection = False
create()
while True:

  while connection == False:
    connection = login()
    print(connection[1])
    connection[1].cIMC()
  afficher_menu()
</code>```

Here is the file in which I put the names of the classes, the user names and the passwords: enter image description here

I then get the following error: "Attribute error : 'str' object has no attribute 'cIMC'"
And it seems logical because I put in my file a str and not the class. How can I solve this problem and get my class with its id in the file? Thank you in advance!

Title: Save class in a file

Body:
first, sorry for my english, I'm french !
I am in the process of creating an account (class) and connecting to it. I use a file where I put my data.

I have a question about my code below (I am a python beginner)
Code :

import random
import string

#Définition des classes et des fonctions
class compte:

  def __init__(self, user, mdp):
    self.user = user
    self.mdp = mdp
    self.poids = "not defined"
    self.taille = "not defined"
    self.IMC = "not defined"
    self.test = 1
    #self.adresse = adresse
    self.salle_attribuée = "not defined"
    #self.objectif = objectif

  def cIMC(self):
    print("ok")

def create():
  chaine_minuscule = string.ascii_lowercase
  id_compte = "".join(random.choice(chaine_minuscule) for i in range(5))
  num = id_compte
  user = input("Username: ")
  mdp = input("Password: ")
  id_compte = compte(user, mdp)
  f = open("users.txt", "a")
  texte = [num, "|", id_compte.user, "|", id_compte.mdp]
  for t in texte:
    f.write(t)
  f.write('\n')
  print('\n------------Vous avez bien créé votre compte : ------------\n')
  print("Username = ", id_compte.user, "\nPassword = ", id_compte.mdp)

def login():
  user = input("Username: ")
  mdp = input("Password: ")
  f = open("users.txt", "r")
  for line in f.readlines():
    nbr, us, pw = line.strip().split("|")
    if (user == us) and (mdp == pw):
      print("\nLogin successful!")
      return True, nbr
  print("Wrong username/password")
  return False

connection = False
create()
while True:

  while connection == False:
    connection = login()
    print(connection[1])
    connection[1].cIMC()
  afficher_menu()

Here is the file in which I put the names of the classes, the user names and the passwords: enter image description here

I then get the following error: "Attribute error : 'str' object has no attribute 'cIMC'"
And it seems logical because I put in my file a str and not the class. How can I solve this problem and get my class with its id in the file? Thank you in advance!


问:
resulting .AVI files are much larger than the input .PNGs
I want an easy way to join multiple timestamped screenshots into a video file of any format (like mt4 or avi) with Python.

For this, I used CV2, but the problem is that the resulting .AVI files are way larger than the input PNGs. Like 400 input pngs that weight 20 mb produce a 500 mb file, which is absurd.

```<code>def movie(image_folder):
video_name = image_folder.split("/")[-2] + ".avi"

# find images
images = sorted([img for img in os.listdir(image_folder) if img.endswith(".png")])

# get height, width, layers of the first image
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

# creates video file
# second parameter is the fourcc (4-character code used for image compression)
# third parameter is the frame rate
# forth parameter is the size of resulting video file
video = cv2.VideoWriter("movies/" + video_name, 0, 1, (width, height))

for image in images:
    file_path = os.path.join(image_folder, image)
    # adds each screenshot to the nascent movie
    video.write(cv2.imread(file_path))

cv2.destroyAllWindows()
video.release()
</code>```

What should I do to make the resulting file have the same (or a bit larger) size as the input PNGs?

Body:
I want an easy way to join multiple timestamped screenshots into a video file of any format (like mt4 or avi) with Python.

For this, I used CV2, but the problem is that the resulting .AVI files are way larger than the input PNGs. Like 400 input pngs that weight 20 mb produce a 500 mb file, which is absurd.

def movie(image_folder):
video_name = image_folder.split("/")[-2] + ".avi"

# find images
images = sorted([img for img in os.listdir(image_folder) if img.endswith(".png")])

# get height, width, layers of the first image
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

# creates video file
# second parameter is the fourcc (4-character code used for image compression)
# third parameter is the frame rate
# forth parameter is the size of resulting video file
video = cv2.VideoWriter("movies/" + video_name, 0, 1, (width, height))

for image in images:
    file_path = os.path.join(image_folder, image)
    # adds each screenshot to the nascent movie
    video.write(cv2.imread(file_path))

cv2.destroyAllWindows()
video.release()

What should I do to make the resulting file have the same (or a bit larger) size as the input PNGs?


问:
mql4-dynamic array-close candle price -read min or max
i want to make a dynamic array to get this result

while on each candle  cond1 && Cond2 && cond3 is true
put the close pricce of candle  to array that doesnt have size

and if some cond are granted

check for  if close of i+1 candle( for example) < maximum of array value

and so on

and if cond1&& cond & & cond 3 not true  it clears the content of array

my problem is when condition are true put that value (closeing price of candles) to array
and when not, clear whole array to ensure that on next time  that conditions are true it works fine


问:
How to replace the Docusaurus v2 CategoryIndexMatcher?
Our documentation has a package/package/Module.mdx structure, with an index.md at every package level, so also next to Module.mdx. The default CategoryIndexMatcher matches both index.mdx and Module.mdx as category index if the last package name is also 'module' (case doesn't matter.. it lowercases everything before matching). I want to retain the module/Module.mdx in the docs, rather than only index.mdx. Currently, only index.html is emitted. I expect also a Module.html.

I read the examples on this page, and tried to replace the CategoryIndexMatcher to ignore matching packages but it didn't help.

...
presets: [
    [
      'classic',
      /** @type {import('@docusaurus/preset-classic').Options} */
      ({
        docs: {
          sidebarPath: require.resolve('./sidebars.js'),
          async sidebarItemsGenerator({
            defaultSidebarItemsGenerator,
            numberPrefixParser,
            item,
            version,
            docs,
            categoriesMetadata,
            isCategoryIndex: isRascalCategoryIndex,
          }) {
            return defaultSidebarItemsGenerator({
              numberPrefixParser,
              item,
              version,
              docs,
              categoriesMetadata,
              isCategoryIndex(doc) {
                const eligibleDocIndexNames = [
                  'index',
                  'readme',
                ];
                return eligibleDocIndexNames.includes(doc.fileName.toLowerCase());;
              },
            });
          },
        },
```
<p>...</p>
``````

Body:
Our documentation has a package/package/Module.mdx structure, with an index.md at every package level, so also next to Module.mdx. The default CategoryIndexMatcher matches both index.mdx and Module.mdx as category index if the last package name is also 'module' (case doesn't matter.. it lowercases everything before matching). I want to retain the module/Module.mdx in the docs, rather than only index.mdx. Currently, only index.html is emitted. I expect also a Module.html.

I read the examples on this page, and tried to replace the CategoryIndexMatcher to ignore matching packages but it didn't help.

...
presets: [
    [
      'classic',
      /** @type {import('@docusaurus/preset-classic').Options} */
      ({
        docs: {
          sidebarPath: require.resolve('./sidebars.js'),
          async sidebarItemsGenerator({
            defaultSidebarItemsGenerator,
            numberPrefixParser,
            item,
            version,
            docs,
            categoriesMetadata,
            isCategoryIndex: isRascalCategoryIndex,
          }) {
            return defaultSidebarItemsGenerator({
              numberPrefixParser,
              item,
              version,
              docs,
              categoriesMetadata,
              isCategoryIndex(doc) {
                const eligibleDocIndexNames = [
                  'index',
                  'readme',
                ];
                return eligibleDocIndexNames.includes(doc.fileName.toLowerCase());;
              },
            });
          },
        },

...


问:
react-native android linking viro-react
I have installed the viro package and next thing is to link the package the problem is that I can't find the android/build.gradle or other files android/app android/gradle/wrapper/gradle-wrapper
so what is wrong with it did I install the package wrong? because I downgrade the react-native version to the supported version 0.65.1 and then installed the package without any problem I tried to test the project without linking and the project is not working and giving this log

```<code>Warning: Invalid version react-native@0.65.1 for expo sdkVersion 45.0.0. Use react-native@0.68.2
Android Bundling failed 1677ms
Unable to resolve module buffer from C:\Users\MrObscure\Desktop\react\Partner\node_modules\safe-buffer\index.js: buffer could not be found within the project or in these directories:
  node_modules

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
  1 | /* eslint-disable node/no-deprecated-api */
> 2 | var buffer = require('buffer')
    |                       ^
  3 | var Buffer = buffer.Buffer
  4 |
  5 | // alternative to using Object.keys for old browsers
</code>```

linking guide

and this is what android folder contain

Title: react-native android linking viro-react

Body:
I have installed the viro package and next thing is to link the package the problem is that I can't find the android/build.gradle or other files android/app android/gradle/wrapper/gradle-wrapper
so what is wrong with it did I install the package wrong? because I downgrade the react-native version to the supported version 0.65.1 and then installed the package without any problem I tried to test the project without linking and the project is not working and giving this log

Warning: Invalid version react-native@0.65.1 for expo sdkVersion 45.0.0. Use react-native@0.68.2
Android Bundling failed 1677ms
Unable to resolve module buffer from C:\Users\MrObscure\Desktop\react\Partner\node_modules\safe-buffer\index.js: buffer could not be found within the project or in these directories:
  node_modules

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
  1 | /* eslint-disable node/no-deprecated-api */
> 2 | var buffer = require('buffer')
    |                       ^
  3 | var Buffer = buffer.Buffer
  4 |
  5 | // alternative to using Object.keys for old browsers

linking guide

and this is what android folder contain


问:
trying to select something from a table with the same name as a python variable
I want the program to look for keywords in the input and if it is the same as one in the names table then it will search for the solutions with that specific name. I want the FROM to be x[space] as that would be the variable with the correct name e.g sound.

```<code>issue = input("BOT: Hello, please specify your issue\nType here:  ")
issue = issue.lower()
x = issue.split(" ")
c.execute("""SELECT Names FROM names""")
prob = c.fetchall()
conn.commit()
prob = str(prob)
prob = prob.split(" ")
space = 0
space1 = 0
right = False
while space < len(x) and right == False:
    if x[space] == prob[space1]:
        c.execute("""SELECT solutions FROM ?""",x[space])
        do = c.fetchall()
        conn.commit()
</code>```

the error I got:

Traceback (most recent call last):
File "/Users/nikkiclarke/Request bot/request code.py", line 272, in
c.execute("""SELECT solutions FROM ?""",x[space])
sqlite3.OperationalError: near "?": syntax error

Body:
I want the program to look for keywords in the input and if it is the same as one in the names table then it will search for the solutions with that specific name. I want the FROM to be x[space] as that would be the variable with the correct name e.g sound.

issue = input("BOT: Hello, please specify your issue\nType here:  ")
issue = issue.lower()
x = issue.split(" ")
c.execute("""SELECT Names FROM names""")
prob = c.fetchall()
conn.commit()
prob = str(prob)
prob = prob.split(" ")
space = 0
space1 = 0
right = False
while space < len(x) and right == False:
    if x[space] == prob[space1]:
        c.execute("""SELECT solutions FROM ?""",x[space])
        do = c.fetchall()
        conn.commit()

the error I got:

Traceback (most recent call last):
File "/Users/nikkiclarke/Request bot/request code.py", line 272, in
c.execute("""SELECT solutions FROM ?""",x[space])
sqlite3.OperationalError: near "?": syntax error


问:
D3 grid with vertical bar chart in every cell
I'm trying to make a grid layout with a chart in every cell.

I'm doing it like this:

```<code>    function gridData (arr) {
        var data = new Array();
        var xpos = 1;
        var ypos = 1;
        var width = 50;
        var height = 50;

        for (var row = 0; row < 4; row++) {
            data.push( new Array() );

            for (var column = 0; column < 10; column++) {
                 data[row].push({
                    x: xpos,
                    y: ypos,
                    width: width,
                    height: height,
                    text: (column === 0) ? "header" : "",
                    value : (column != 0 ) ? [4,5,10,8] : ""
                })
                xpos += width;
            }
            xpos = 1;
            ypos += height;
        }
        return data;
    }
</code>```

where text and values will be replaced with real values. Values would be 4 vertical bars in a vertical bar chart representing quarters of the year.

My d3 code so far:

```<code>    var row = svg.selectAll(".row")
        .data(gridData())
        .enter().append("g")
        .attr("class", "row");

    row.selectAll(".square")
        .data(function(d) { return d; })
        .enter().append("rect")
        .attr("x", function(d) { return d.x; })
        .attr("y", function(d) { return d.y; })
        .attr("width", function(d) { return d.width; })
        .attr("height", function(d) { return d.height; })
        .style("fill", "#fff")
        .style("stroke", "#222");

    row.selectAll('.label')
        .data(function(d) {return d;}).enter().append("text")
        .attr("x", function(d) { return d.x + 3 })
        .attr("y", function(d) { return d.y +d.height - 10 })
        .text(function(d) {return d.text})
        .style("stroke", "grey")
        .style("font-size", "10px")
</code>```

This code draws a grid and achieves to put headers in the first column for every row, but I have no idea how to draw a rectangle for each element of value array.

Body:
I'm trying to make a grid layout with a chart in every cell.

I'm doing it like this:

    function gridData (arr) {
        var data = new Array();
        var xpos = 1;
        var ypos = 1;
        var width = 50;
        var height = 50;

        for (var row = 0; row < 4; row++) {
            data.push( new Array() );

            for (var column = 0; column < 10; column++) {
                 data[row].push({
                    x: xpos,
                    y: ypos,
                    width: width,
                    height: height,
                    text: (column === 0) ? "header" : "",
                    value : (column != 0 ) ? [4,5,10,8] : ""
                })
                xpos += width;
            }
            xpos = 1;
            ypos += height;
        }
        return data;
    }

where text and values will be replaced with real values. Values would be 4 vertical bars in a vertical bar chart representing quarters of the year.

My d3 code so far:

    var row = svg.selectAll(".row")
        .data(gridData())
        .enter().append("g")
        .attr("class", "row");

    row.selectAll(".square")
        .data(function(d) { return d; })
        .enter().append("rect")
        .attr("x", function(d) { return d.x; })
        .attr("y", function(d) { return d.y; })
        .attr("width", function(d) { return d.width; })
        .attr("height", function(d) { return d.height; })
        .style("fill", "#fff")
        .style("stroke", "#222");

    row.selectAll('.label')
        .data(function(d) {return d;}).enter().append("text")
        .attr("x", function(d) { return d.x + 3 })
        .attr("y", function(d) { return d.y +d.height - 10 })
        .text(function(d) {return d.text})
        .style("stroke", "grey")
        .style("font-size", "10px")

This code draws a grid and achieves to put headers in the first column for every row, but I have no idea how to draw a rectangle for each element of value array.


问:
Unable to send a message to the connected user when signalR trigger raises in Upstream configuration
The following code successfully receives "connected" events from signalR upstream when a user connects, proving that the configuration in .NET 6.0 and dotnet-isolated mode are correct:

    [Function("OnConnected")]
    [SignalROutput(HubName = HubName)]
    public async Task<MyMessage> OnConnectedAsync([SignalRTrigger(HubName, "connections", "connected")] SignalRInvocationContext invocationContext)
    {
        _logger?.LogInformation("Connection established: {@InvocationContext}", invocationContext);
        string someMessage = await DoSomethingAsync();
        return new MyMessage
        {
            Arguments = new[]
            {
                new
                {
                 message = someMessage
                }
            },
            Target = "onConnected"
        };
    }
```
<p>The client code has been subscribed after the successful negotiation to the signalR hub listening to receiving "onConnected" event per the following code:</p>
<pre class="lang-cs prettyprint-override"><code>
        connection.On("onConnected", (Action<object>)(message =>
        {
            var packet = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(message.ToString());
        }));
</code>```

connection is a HubConnection object type in the code snippet above.

The problem is that when the upstream serverless function is called the client code above does not recieve "onConnected" event and it won't execute.

I expected to receieve the "onConnected" event in the client side code. Also, how can I send a message to a group of users?

Body:
The following code successfully receives "connected" events from signalR upstream when a user connects, proving that the configuration in .NET 6.0 and dotnet-isolated mode are correct:

    [Function("OnConnected")]
    [SignalROutput(HubName = HubName)]
    public async Task<MyMessage> OnConnectedAsync([SignalRTrigger(HubName, "connections", "connected")] SignalRInvocationContext invocationContext)
    {
        _logger?.LogInformation("Connection established: {@InvocationContext}", invocationContext);
        string someMessage = await DoSomethingAsync();
        return new MyMessage
        {
            Arguments = new[]
            {
                new
                {
                 message = someMessage
                }
            },
            Target = "onConnected"
        };
    }

The client code has been subscribed after the successful negotiation to the signalR hub listening to receiving "onConnected" event per the following code:

        connection.On("onConnected", (Action<object>)(message =>
        {
            var packet = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(message.ToString());
        }));

connection is a HubConnection object type in the code snippet above.

The problem is that when the upstream serverless function is called the client code above does not recieve "onConnected" event and it won't execute.

I expected to receieve the "onConnected" event in the client side code. Also, how can I send a message to a group of users?