问:
error: supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies
Have a very basic Java/Kotlin dependency issue when we have chained dependencies. I posted a similar question before, but now I removed Gradle from the equation and tried directly with java/kotlin. Have

```<code>Main --> Lib2 --> Lib1
</code>```

Lib1.java:

```<code>package com.test.lib1;

public interface Lib1 {
}
</code>```

Lib2.java:

```<code>package com.test.lib2;

public interface Lib2 extends com.test.lib1.Lib1 {
    public String msg = "Hello message from Lib2";
}
</code>```

JavaMain.java:

```<code>package com.test.main;

import com.test.lib2.Lib2;

public class JavaMain {
    public static void main(String[] args) {
        System.out.println("++++ Java TEST: " + Lib2.msg);
    }
}
</code>```

When I run this, it works and prints ++++ Java TEST: Hello message from Lib2. However when I build this Kotlin program compilation fails.

KotlinTest.kt:

```<code>package com.test.main

import com.test.lib2.Lib2

fun main() {
    println("++++ KT TEST: " + Lib2.msg)
}
</code>```

Error I get: "error: supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath: class com.test.lib2.Lib2, unresolved supertypes: com.test.lib1.Lib1".

Here is the shell script I used to build/run:

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

set -e

rm -rf build1 build2
mkdir build1 build2

echo "Building Lib1 ..."
javac -d build1 Lib1.java
(cd build1; jar cvf Lib1.jar *; cd ..)

echo "Building Lib2 ..."
javac -cp build1 -d build2 Lib2.java
(cd build2; jar cvf Lib2.jar *; cd ..)

if [ "$1" == "kotlin" ]; then
    echo ""
    echo "Building kotlin program ..."
    kotlinc -cp build2 KotlinTest.kt
    #kotlinc -cp build2:build1 KotlinTest.kt
    kotlin com.test.main.KotlinTest
else
    echo ""
    echo "Building java program ..."
    rm -rf main
    mkdir main
    javac -cp build2/Lib2.jar -d main JavaMain.java

    echo "Running Java program ..."
    java -cp build2/Lib2.jar:main com.test.main.JavaMain
fi
</code>```

Why Java and Kotlin are behaving differently? The fact that Lib2 uses Lib1 shouldn't be entirely contained with Lib2, and the Main class shouldn't be worrying about Lib1 at all? Java version tried both 1.8 and 11, Kotlin version 1.7.21.

Body:
Have a very basic Java/Kotlin dependency issue when we have chained dependencies. I posted a similar question before, but now I removed Gradle from the equation and tried directly with java/kotlin. Have

Main --> Lib2 --> Lib1

Lib1.java:

package com.test.lib1;

public interface Lib1 {
}

Lib2.java:

package com.test.lib2;

public interface Lib2 extends com.test.lib1.Lib1 {
    public String msg = "Hello message from Lib2";
}

JavaMain.java:

package com.test.main;

import com.test.lib2.Lib2;

public class JavaMain {
    public static void main(String[] args) {
        System.out.println("++++ Java TEST: " + Lib2.msg);
    }
}

When I run this, it works and prints ++++ Java TEST: Hello message from Lib2. However when I build this Kotlin program compilation fails.

KotlinTest.kt:

package com.test.main

import com.test.lib2.Lib2

fun main() {
    println("++++ KT TEST: " + Lib2.msg)
}

Error I get: "error: supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath: class com.test.lib2.Lib2, unresolved supertypes: com.test.lib1.Lib1".

Here is the shell script I used to build/run:

#!/bin/bash

set -e

rm -rf build1 build2
mkdir build1 build2

echo "Building Lib1 ..."
javac -d build1 Lib1.java
(cd build1; jar cvf Lib1.jar *; cd ..)

echo "Building Lib2 ..."
javac -cp build1 -d build2 Lib2.java
(cd build2; jar cvf Lib2.jar *; cd ..)

if [ "$1" == "kotlin" ]; then
    echo ""
    echo "Building kotlin program ..."
    kotlinc -cp build2 KotlinTest.kt
    #kotlinc -cp build2:build1 KotlinTest.kt
    kotlin com.test.main.KotlinTest
else
    echo ""
    echo "Building java program ..."
    rm -rf main
    mkdir main
    javac -cp build2/Lib2.jar -d main JavaMain.java

    echo "Running Java program ..."
    java -cp build2/Lib2.jar:main com.test.main.JavaMain
fi

Why Java and Kotlin are behaving differently? The fact that Lib2 uses Lib1 shouldn't be entirely contained with Lib2, and the Main class shouldn't be worrying about Lib1 at all? Java version tried both 1.8 and 11, Kotlin version 1.7.21.


来源: stackexchange

问:
on_message not responding pyrogram
im having 2 bots and there client named 'app' and 'create_app'
first one need to select topic that the user choose and the second one just retype the message that the user send

```<code>app = Client(
    "app",
    # api_id=Keys.api_id,
    # api_hash=Keys.api_hash,
    bot_token=Keys.MAIN_BOT
)

create_app = Client(
    "my_account",
    # api_id=Keys.api_id,
    # api_hash=Keys.api_hash,
    bot_token=Keys.GROUP_BOT
)
</code>```

whenever i send a message to 'create_app' bot it seems the code doesnt enter over there

```<code>@create_app.on_message(filters.text)
async def exchangeAndSend(client, msg):
    text = msg.text.lower()
    print('im here')
    if msg.from_user.id in adminList:
        for word, initial in Keys.shortsDict.items():
            text = text.replace(initial, word)
    else:
        for word, initial in Keys.shortsDict.items():
            text = text.replace(word, initial)
    await app.delete_messages(msg.chat.id, msg.id)
    await msg.reply(text=msg.from_user.first_name + ": " + text)
</code>```

im not even getting error in console, what is wrong here?

ContentLicense: CC BY-SA 4.0

Title: on_message not responding pyrogram

Body:
im having 2 bots and there client named 'app' and 'create_app'
first one need to select topic that the user choose and the second one just retype the message that the user send

app = Client(
    "app",
    # api_id=Keys.api_id,
    # api_hash=Keys.api_hash,
    bot_token=Keys.MAIN_BOT
)

create_app = Client(
    "my_account",
    # api_id=Keys.api_id,
    # api_hash=Keys.api_hash,
    bot_token=Keys.GROUP_BOT
)

whenever i send a message to 'create_app' bot it seems the code doesnt enter over there

@create_app.on_message(filters.text)
async def exchangeAndSend(client, msg):
    text = msg.text.lower()
    print('im here')
    if msg.from_user.id in adminList:
        for word, initial in Keys.shortsDict.items():
            text = text.replace(initial, word)
    else:
        for word, initial in Keys.shortsDict.items():
            text = text.replace(word, initial)
    await app.delete_messages(msg.chat.id, msg.id)
    await msg.reply(text=msg.from_user.first_name + ": " + text)

im not even getting error in console, what is wrong here?


问:
Attempting to implement get_absolute_url and receiving a NoReverseMatch error
Not able to find the error in my code. Attempting to implement get_absolute_url. I have a book I am following to write this and everything is identical to what is in the book...

Error message
Error log

models.py

blog/urls.py

mysite/urls.py

Looked over the django docs. The code for this project is on github at https://github.com/PacktPublishing/Django-4-by-example


问:
Tesseract adds unnecessary space in words, and interprets I as 1
I use Tesseract

tesseract 5.3.0-rc1-2-gf2519
leptonica-1.82.0
libgif 5.2.1 : libjpeg 8d (libjpeg-turbo 2.1.4) : libpng 1.6.39 : libtiff 4.4.0 : zlib 1.2.11 : libwebp 1.2.4 : libopenjp2 2.5.0 and testdata_best

I am trying out some OCR using Tesseract. It outputs the result, though not perfectly. When I tried the OCR on a passport, it returned with extra spaces in between words, which is completely irrelevant. On some documents, it interpreted I as 1. Are there settings to set to improve its accuracy?
This is one such example:

Expected output

P<CZESPECIMEN<<VZOR<<<<<<<<<<<<<<<<<<<<<<<<<<
99009054<4CZE6906229F16072996956220612<<<<74

Actual output

P<C ZESPE C I MEN<<VZOR<<<<<<<<-<<<<<<<<<<<<<<<<<
99009054<4C Z E6906229F16072996956220612<<<<74

Code

```<code>public static void main(String[] args) throws IOException {
        String data = "I will write this String to File in Java";
        int noOfLines = 10000;

        nu.pattern.OpenCV.loadLocally();
        Mat matImage = Imgcodecs.imread("src/main/resources/passport4.jpg");
        MatOfByte matOfByte = new MatOfByte();
        Imgcodecs.imencode(".jpg", matImage, matOfByte);
        byte[] byteArray = matOfByte.toArray();
        BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(byteArray));
        Binarization.returnBuffered(bufferedImage);
        BytePointer outText;
        TessBaseAPI api = new TessBaseAPI();
        api.SetPageSegMode(13);
        api.oem();
        api.SetVariable("--oem", "1");
        api.SetVariable("preserve_interword_spaces", "1");
        api.SetVariable("tessedit_timing_debug", "1");
        if (api.Init(null, "eng") != 0) {
            System.err.println("Could not initialize tesseract.");
            System.exit(1);
        }
        PIX image = pixRead(args.length > 0 ? args[0] : "saved.png");
        api.SetImage(image);
        outText = api.GetUTF8Text();
        System.out.println("OCR output:\n" + outText.getString());
        writeToFile.writeUsingFileWriter(outText.getString());
        api.End();
        outText.deallocate();
        pixDestroy(image);
    }
</code>```

Body:
I use Tesseract

tesseract 5.3.0-rc1-2-gf2519
leptonica-1.82.0
libgif 5.2.1 : libjpeg 8d (libjpeg-turbo 2.1.4) : libpng 1.6.39 : libtiff 4.4.0 : zlib 1.2.11 : libwebp 1.2.4 : libopenjp2 2.5.0 and testdata_best

I am trying out some OCR using Tesseract. It outputs the result, though not perfectly. When I tried the OCR on a passport, it returned with extra spaces in between words, which is completely irrelevant. On some documents, it interpreted I as 1. Are there settings to set to improve its accuracy?
This is one such example:

Expected output

P<CZESPECIMEN<<VZOR<<<<<<<<<<<<<<<<<<<<<<<<<<
99009054<4CZE6906229F16072996956220612<<<<74

Actual output

P<C ZESPE C I MEN<<VZOR<<<<<<<<-<<<<<<<<<<<<<<<<<
99009054<4C Z E6906229F16072996956220612<<<<74

Code

public static void main(String[] args) throws IOException {
        String data = "I will write this String to File in Java";
        int noOfLines = 10000;

        nu.pattern.OpenCV.loadLocally();
        Mat matImage = Imgcodecs.imread("src/main/resources/passport4.jpg");
        MatOfByte matOfByte = new MatOfByte();
        Imgcodecs.imencode(".jpg", matImage, matOfByte);
        byte[] byteArray = matOfByte.toArray();
        BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(byteArray));
        Binarization.returnBuffered(bufferedImage);
        BytePointer outText;
        TessBaseAPI api = new TessBaseAPI();
        api.SetPageSegMode(13);
        api.oem();
        api.SetVariable("--oem", "1");
        api.SetVariable("preserve_interword_spaces", "1");
        api.SetVariable("tessedit_timing_debug", "1");
        if (api.Init(null, "eng") != 0) {
            System.err.println("Could not initialize tesseract.");
            System.exit(1);
        }
        PIX image = pixRead(args.length > 0 ? args[0] : "saved.png");
        api.SetImage(image);
        outText = api.GetUTF8Text();
        System.out.println("OCR output:\n" + outText.getString());
        writeToFile.writeUsingFileWriter(outText.getString());
        api.End();
        outText.deallocate();
        pixDestroy(image);
    }


问:
QML - Selecting cells doesn't work and produces an error
I'm using TableView in QML with QAbstractTableModel in PyQt6, I'm trying to make the table cells (or rows) selectable and get its data using the code in this documentation page, the table works fine and the data shows as intended but nothing is selectable.

MyTableView.qml:

```<code>import QtQuick
import QtQuick.Controls

TableView {
    id: tableView
    boundsBehavior: Flickable.StopAtBounds
    clip: true
    model: customTableModel
    onWidthChanged: tableView.forceLayout()
    selectionModel: ItemSelectionModel {
        onCurrentChanged: {
            console.log(currentIndex)  // This works
        }
    }

    selectionBehavior: TableView.SelectRows

    columnWidthProvider: function (column) {
        return tableView.model ? tableView.width/tableView.model.columnCount() : 0
    }

    delegate: Rectangle {
        required property bool selected
        required property bool current

        implicitWidth: tableView.columnWidthProvider(column)
        implicitHeight: 40
        border.color: "black"
        border.width: 1
        color: header ? "grey" : current ? "lightblue" : "white"
        clip: true

        Text {
            text: display
            anchors.centerIn: parent
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignHCenter
            font.family: Style.font
            font.pointSize: Style.normalFont
            font.bold: header ? true : false
            color: header ? "white" : "black"
        }
    }
}
</code>```

table_model.py

```<code>class TableModel(QAbstractTableModel):
    def __init__(self, header, data, parent=None):
        super(TableModel, self).__init__(parent)
        self.header = header
        self.datatable = data
        self.datatable.insert(0, {h: h.replace("_", " ").capitalize() for h in header.values()})

    def rowCount(self, parent=QModelIndex()):
        if parent == QModelIndex():
            return len(self.datatable) if self.datatable else 0
        return 0

    def columnCount(self, parent=QModelIndex()):
        if parent == QModelIndex():
            return len(self.header)
        return 0

    def data(self, index, role=Qt.ItemDataRole.DisplayRole):
        if not index.isValid():
            return None

        # Heading
        if role == Qt.ItemDataRole.UserRole + 1:
            return index.row() == 0

        # Table Data
        if role == Qt.ItemDataRole.DisplayRole:
            row = index.row()
            col = index.column()
            data = self.datatable[row][self.header[col]]
            return str(data) if data else ""

        return None

    def roleNames(self):
        roles = {
                 Qt.ItemDataRole.DisplayRole: b"display",
                 Qt.ItemDataRole.UserRole + 1: b"header"
                }
        return roles

    def flags(self, index):
        print("flags sent")
        return Qt.ItemIsEnabled | Qt.ItemIsSelectable

</code>```

it gives these errors when I click on any table cell:

```<code>qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeRemoved(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeRemoved(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeInserted(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeInserted(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::layoutAboutToBeChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::layoutChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::modelReset()
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeRemoved(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeRemoved(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeInserted(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeInserted(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::layoutAboutToBeChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::layoutChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::modelReset()
</code>```

I've tried on Windows with Qt 6.2 and Linux with Qt 6.4.1.

Edit: using current instead of selected in qml worked for single cell selection and selected cell color, but the error still persists, and it works only for a single cell selection not row selection.

Body:
I'm using TableView in QML with QAbstractTableModel in PyQt6, I'm trying to make the table cells (or rows) selectable and get its data using the code in this documentation page, the table works fine and the data shows as intended but nothing is selectable.

MyTableView.qml:

import QtQuick
import QtQuick.Controls

TableView {
    id: tableView
    boundsBehavior: Flickable.StopAtBounds
    clip: true
    model: customTableModel
    onWidthChanged: tableView.forceLayout()
    selectionModel: ItemSelectionModel {
        onCurrentChanged: {
            console.log(currentIndex)  // This works
        }
    }

    selectionBehavior: TableView.SelectRows

    columnWidthProvider: function (column) {
        return tableView.model ? tableView.width/tableView.model.columnCount() : 0
    }

    delegate: Rectangle {
        required property bool selected
        required property bool current

        implicitWidth: tableView.columnWidthProvider(column)
        implicitHeight: 40
        border.color: "black"
        border.width: 1
        color: header ? "grey" : current ? "lightblue" : "white"
        clip: true

        Text {
            text: display
            anchors.centerIn: parent
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignHCenter
            font.family: Style.font
            font.pointSize: Style.normalFont
            font.bold: header ? true : false
            color: header ? "white" : "black"
        }
    }
}

table_model.py

class TableModel(QAbstractTableModel):
    def __init__(self, header, data, parent=None):
        super(TableModel, self).__init__(parent)
        self.header = header
        self.datatable = data
        self.datatable.insert(0, {h: h.replace("_", " ").capitalize() for h in header.values()})

    def rowCount(self, parent=QModelIndex()):
        if parent == QModelIndex():
            return len(self.datatable) if self.datatable else 0
        return 0

    def columnCount(self, parent=QModelIndex()):
        if parent == QModelIndex():
            return len(self.header)
        return 0

    def data(self, index, role=Qt.ItemDataRole.DisplayRole):
        if not index.isValid():
            return None

        # Heading
        if role == Qt.ItemDataRole.UserRole + 1:
            return index.row() == 0

        # Table Data
        if role == Qt.ItemDataRole.DisplayRole:
            row = index.row()
            col = index.column()
            data = self.datatable[row][self.header[col]]
            return str(data) if data else ""

        return None

    def roleNames(self):
        roles = {
                 Qt.ItemDataRole.DisplayRole: b"display",
                 Qt.ItemDataRole.UserRole + 1: b"header"
                }
        return roles

    def flags(self, index):
        print("flags sent")
        return Qt.ItemIsEnabled | Qt.ItemIsSelectable

it gives these errors when I click on any table cell:

qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeRemoved(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeRemoved(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeInserted(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeInserted(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::layoutAboutToBeChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::layoutChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::modelReset()
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeRemoved(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeRemoved(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeInserted(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeInserted(QModelIndex,int,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::rowsMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::columnsMoved(QModelIndex,int,int,QModelIndex,int)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::layoutAboutToBeChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::layoutChanged(QList<QPersistentModelIndex>,QAbstractItemModel::LayoutChangeHint)
qt.core.qobject.connect: QObject::disconnect: No such signal QObject::modelReset()

I've tried on Windows with Qt 6.2 and Linux with Qt 6.4.1.

Edit: using current instead of selected in qml worked for single cell selection and selected cell color, but the error still persists, and it works only for a single cell selection not row selection.


问:
Laravel localized validation error message and custom rule
in my app I want to add a regex rule to secure strong passwords and also wanto to show its localized (translated) error validation message, I have been searching but can't find a good example similar to my codebase.

My current validation rules

```<code>public static $sanctumRegister =
    [
        'password' => 'regex:/^(?=.*[a-z])(?=.*[A-Z])(=.*\d).+$/'|min:8|required|string',
    ];
</code>```

How I validate my requests

```<code>$validator = Validator::make($request->all(), AuthValidator::$sanctumRegister);
$this->validateWith($validator);
</code>```

Thanks in advance!

Body:
in my app I want to add a regex rule to secure strong passwords and also wanto to show its localized (translated) error validation message, I have been searching but can't find a good example similar to my codebase.

My current validation rules

public static $sanctumRegister =
    [
        'password' => 'regex:/^(?=.*[a-z])(?=.*[A-Z])(=.*\d).+$/'|min:8|required|string',
    ];

How I validate my requests

$validator = Validator::make($request->all(), AuthValidator::$sanctumRegister);
$this->validateWith($validator);

Thanks in advance!


问:
Cannot install any new packages due to attribute error
Whenever I try to install a package on my python project I get the following error:

```<code>File "c:\users\user\ideaprojects\finvizscrapr\env\lib\site-packages\pip\_vendor\requests\sessions.py", line 487, in prepare_request
files=request.listFiles,
AttributeError: 'Request' object has no attribute 'listFiles'
</code>```

Very strange since I've installed a lot of other packages before, but after closing down my IDE I can't install any new package using pip install <package>.

I'm using a virtual environment.

Body:
Whenever I try to install a package on my python project I get the following error:

File "c:\users\user\ideaprojects\finvizscrapr\env\lib\site-packages\pip\_vendor\requests\sessions.py", line 487, in prepare_request
files=request.listFiles,
AttributeError: 'Request' object has no attribute 'listFiles'

Very strange since I've installed a lot of other packages before, but after closing down my IDE I can't install any new package using pip install <package>.

I'm using a virtual environment.


问:
Cannot find name 'describe' when using yarn pnp and ts-jest (jest) in monorepo
I am using jazelle and yarn pnp in monorepo. but I cannot run tests like jz test. it seems that @types/jest not setup properly.

My errors:

```<code> FAIL  __tests__/autocomplete/presto/suggest.test.ts
  ● Test suite failed to run

    __tests__/autocomplete/presto/suggest.test.ts:4:8 - error TS6137: Cannot import type declaration files. Consider importing 'jest' instead of '@types/jest'.

    4 import '@types/jest';
             ~~~~~~~~~~~~~
    __tests__/autocomplete/presto/suggest.test.ts:6:1 - error TS2593: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig.

    6 describe('Presto SQL Suggest Tests', () => {
      ~~~~~~~~
    __tests__/autocomplete/presto/suggest.test.ts:7:5 - error TS2593: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig.

    7     test('Empty suggest', () => {
          ~~~~
    __tests__/autocomplete/presto/suggest.test.ts:10:9 - error TS2304: Cannot find name 'expect'.

    10         expect(result.length).toBe(0);
               ~~~~~~
</code>```

I did search and tried to fix my following files based on the suggestions searched. but unluckily, I still cannot resolve my errors.

Below are my files:

tsconfig.json

```<code>{
  "typeAcquisition": {
    "include": [
      "jest"
    ]
  },
  "compilerOptions": {
    "types": [
      "node",
      "@types/jest"
    ],
    "typeRoots": [
      "./types",
      "./node_modules/@types"
    ],
    "outDir": "target",
    "sourceMap": true,
    "inlineSources": true,
    "noImplicitAny": true,
    "strict": true,
    "noEmit": true,
    "target": "es2015",
    "module": "commonjs",
    "allowJs": true,
    "checkJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "baseUrl": ".",
    "resolveJsonModule": true,
    "experimentalDecorators": true
  },
  "include": [
    "src/**/*.*",
    "__tests__"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts",
    "**/*.test.ts"
  ],
}
</code>```

my jest.config.js

```<code>module.exports = {
  rootDir: './',
  testEnvironment: 'node',
  preset: 'ts-jest',
  transform: {
    "^.+\\.(ts|js)$": require.resolve('ts-jest')
  },
  moduleFileExtensions: [
    "ts",
    "tsx",
    "js"
  ],
  roots: [
    "<rootDir>/__tests__"
  ],
}
</code>```

and my devDependencies:

```<code>    "@types/jest": "28.1.3",
    "@types/mocha": "^2.2.42",
    "@jest/globals": "25.5.2",
    "antlr4ts-cli": "^0.5.0-alpha.4",
    "babel-eslint": "10.1.0",
    "babel-jest": "28.1.3",
    "babel-plugin-parameter-decorator": "1.0.16",
    "create-universal-package": "^4.3.0",
    "eslint": "7.32.0",
    "eslint-config-fusion": "^6.3.0",
    "eslint-config-prettier": "2.10.0",
    "eslint-plugin-baseui": "10.12.1",
    "eslint-plugin-cup": "2.0.3",
    "eslint-plugin-flowtype": "4.7.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jest": "23.20.0",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-prettier": "4.2.1",
    "eslint-plugin-react": "^7.27.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "flow-bin": "0.131.0",
    "flow-coverage-report": "0.7.0",
    "jest": "28.1.3",
    "jest-environment-jsdom": "28.1.3",
    "jest-environment-jsdom-global": "3.1.2",
</code>```

any idea? thanks

Body:
I am using jazelle and yarn pnp in monorepo. but I cannot run tests like jz test. it seems that @types/jest not setup properly.

My errors:

 FAIL  __tests__/autocomplete/presto/suggest.test.ts
  ● Test suite failed to run

    __tests__/autocomplete/presto/suggest.test.ts:4:8 - error TS6137: Cannot import type declaration files. Consider importing 'jest' instead of '@types/jest'.

    4 import '@types/jest';
             ~~~~~~~~~~~~~
    __tests__/autocomplete/presto/suggest.test.ts:6:1 - error TS2593: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig.

    6 describe('Presto SQL Suggest Tests', () => {
      ~~~~~~~~
    __tests__/autocomplete/presto/suggest.test.ts:7:5 - error TS2593: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig.

    7     test('Empty suggest', () => {
          ~~~~
    __tests__/autocomplete/presto/suggest.test.ts:10:9 - error TS2304: Cannot find name 'expect'.

    10         expect(result.length).toBe(0);
               ~~~~~~

I did search and tried to fix my following files based on the suggestions searched. but unluckily, I still cannot resolve my errors.

Below are my files:

tsconfig.json

{
  "typeAcquisition": {
    "include": [
      "jest"
    ]
  },
  "compilerOptions": {
    "types": [
      "node",
      "@types/jest"
    ],
    "typeRoots": [
      "./types",
      "./node_modules/@types"
    ],
    "outDir": "target",
    "sourceMap": true,
    "inlineSources": true,
    "noImplicitAny": true,
    "strict": true,
    "noEmit": true,
    "target": "es2015",
    "module": "commonjs",
    "allowJs": true,
    "checkJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "baseUrl": ".",
    "resolveJsonModule": true,
    "experimentalDecorators": true
  },
  "include": [
    "src/**/*.*",
    "__tests__"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts",
    "**/*.test.ts"
  ],
}

my jest.config.js

module.exports = {
  rootDir: './',
  testEnvironment: 'node',
  preset: 'ts-jest',
  transform: {
    "^.+\\.(ts|js)$": require.resolve('ts-jest')
  },
  moduleFileExtensions: [
    "ts",
    "tsx",
    "js"
  ],
  roots: [
    "<rootDir>/__tests__"
  ],
}

and my devDependencies:

    "@types/jest": "28.1.3",
    "@types/mocha": "^2.2.42",
    "@jest/globals": "25.5.2",
    "antlr4ts-cli": "^0.5.0-alpha.4",
    "babel-eslint": "10.1.0",
    "babel-jest": "28.1.3",
    "babel-plugin-parameter-decorator": "1.0.16",
    "create-universal-package": "^4.3.0",
    "eslint": "7.32.0",
    "eslint-config-fusion": "^6.3.0",
    "eslint-config-prettier": "2.10.0",
    "eslint-plugin-baseui": "10.12.1",
    "eslint-plugin-cup": "2.0.3",
    "eslint-plugin-flowtype": "4.7.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jest": "23.20.0",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-prettier": "4.2.1",
    "eslint-plugin-react": "^7.27.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "flow-bin": "0.131.0",
    "flow-coverage-report": "0.7.0",
    "jest": "28.1.3",
    "jest-environment-jsdom": "28.1.3",
    "jest-environment-jsdom-global": "3.1.2",

any idea? thanks


问:
how to implement simple alsaloop with poll mechanism and `snd_pcm_poll_descriptors`?
I'm trying to put together a simpler alsaloop software known from the ALSA repository, where both capture and playback are polled with the poll function. I want to take the benefit of polling multiple devices in the future, so poll() makes a lot of sense. I see that snd_pcm_poll_descriptors() API is meant for this exact purpose and have implemented below steps to recreate the loop:

#define BUFSIZE (48 * 2)

int main(int argc, char *argv[])
{
    int err, avail;
    struct pollfd *pfds = NULL;
    int pfds_count = 0, pcount, ccount;
    unsigned short revents;

    snd_pcm_t *playback_handle, *capture_handle;
    int buf[BUFSIZE * 2];

    // below sets all the hardware and software parameters
    // both opened with the option SND_PCM_NO_AUTO_RESAMPLE | SND_PCM_NONBLOCK
    if ((err = open_stream(&playback_handle, "default", SND_PCM_STREAM_PLAYBACK)) < 0)
        return err;

    if ((err = open_stream(&capture_handle, "default", SND_PCM_STREAM_CAPTURE)) < 0)
        return err;

    // count all the descriptors
    if ((err = snd_pcm_poll_descriptors_count(playback_handle)) < 0)
    {
        printf("Invalid poll descriptors count\n");
        return err;
    }

    pfds_count += err;
    pcount = err;

    if ((err = snd_pcm_poll_descriptors_count(capture_handle)) < 0)
    {
        printf("Invalid poll descriptors count\n");
        return err;
    }

    pfds_count += err;
    ccount = err;

    // allocate poll descriptors for all the ALSA devices
    pfds = (struct pollfd*)malloc(sizeof(struct pollfd) * pfds_count);
    if (pfds == NULL || pfds_count <= 0) {
        fprintf(stderr, "Poll FDs allocation failed.\n");
        exit(EXIT_FAILURE);
    }

    // prepare capture poll descriptors
    if ((err = snd_pcm_poll_descriptors(capture_handle, pfds, ccount)) < 0)
    {
        printf("Unable to obtain poll descriptors for capture: %s\n", snd_strerror(err));
        return err;
    }

    // prepare playback poll descriptors
    if ((err = snd_pcm_poll_descriptors(playback_handle, pfds + ccount, pcount)) < 0)
    {
        printf("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
        return err;
    }

    if ((err = snd_pcm_prepare(playback_handle)) < 0) {
        fprintf(stderr, "cannot prepare audio interface for use(%s)\n",
             snd_strerror(err));
        return err;
    }

    if ((err = snd_pcm_start(capture_handle)) < 0) {
        fprintf(stderr, "cannot prepare audio interface for use(%s)\n",
             snd_strerror(err));
        return err;
    }

    memset(buf, 0, sizeof(buf));

    // final loop
    while (1) {
        err = poll(pfds, pfds_count, 5);
        // fprintf(stdout, "poll val: %d\n", err);

        if (err < 0)
        {
            fprintf(stderr, "poll error %s", snd_strerror(err));
            return -1;
        }

        if (err == 0)
            continue;

        // check if capture devices are ready
        snd_pcm_poll_descriptors_revents(capture_handle, pfds, ccount, &revents);
        if (revents & POLLERR)
            fprintf(stderr, "capture poll error");
        if (revents & POLLIN)
        {
            avail = snd_pcm_avail_update(capture_handle);
            if (avail > 0)
            {
                if (avail > BUFSIZE)
                    avail = BUFSIZE;

                snd_pcm_readi(capture_handle, buf, avail);
            }
        }

        // check if playback devices are ready
        snd_pcm_poll_descriptors_revents(playback_handle, pfds + ccount, pcount, &revents);
        if (revents & POLLERR)
            fprintf(stderr, "playback poll error");
        if (revents & POLLOUT)
        {
            avail = snd_pcm_avail_update(playback_handle);
            if (avail > 0)
            {
                if (avail > BUFSIZE)
                    avail = BUFSIZE;

                snd_pcm_writei(playback_handle, buf, avail);
            }
        }
    }

    snd_pcm_close(playback_handle);
    snd_pcm_close(capture_handle);
    return 0;
}
```

Am I forgetting about something important? The audio is garbage, reacts for the change in amplitude on the input, but then breaks totally after a few seconds. Based on the alsaloop.c and pcm.c from the alsa-utils and alsa-lib repos, this is what I've come up with for the basic form of a loopback software.

If any of this is obviously wrong, please let me know.

Body:
I'm trying to put together a simpler alsaloop software known from the ALSA repository, where both capture and playback are polled with the poll function. I want to take the benefit of polling multiple devices in the future, so poll() makes a lot of sense. I see that snd_pcm_poll_descriptors() API is meant for this exact purpose and have implemented below steps to recreate the loop:

#define BUFSIZE (48 * 2)

int main(int argc, char *argv[])
{
    int err, avail;
    struct pollfd *pfds = NULL;
    int pfds_count = 0, pcount, ccount;
    unsigned short revents;

    snd_pcm_t *playback_handle, *capture_handle;
    int buf[BUFSIZE * 2];

    // below sets all the hardware and software parameters
    // both opened with the option SND_PCM_NO_AUTO_RESAMPLE | SND_PCM_NONBLOCK
    if ((err = open_stream(&playback_handle, "default", SND_PCM_STREAM_PLAYBACK)) < 0)
        return err;

    if ((err = open_stream(&capture_handle, "default", SND_PCM_STREAM_CAPTURE)) < 0)
        return err;

    // count all the descriptors
    if ((err = snd_pcm_poll_descriptors_count(playback_handle)) < 0)
    {
        printf("Invalid poll descriptors count\n");
        return err;
    }

    pfds_count += err;
    pcount = err;

    if ((err = snd_pcm_poll_descriptors_count(capture_handle)) < 0)
    {
        printf("Invalid poll descriptors count\n");
        return err;
    }

    pfds_count += err;
    ccount = err;

    // allocate poll descriptors for all the ALSA devices
    pfds = (struct pollfd*)malloc(sizeof(struct pollfd) * pfds_count);
    if (pfds == NULL || pfds_count <= 0) {
        fprintf(stderr, "Poll FDs allocation failed.\n");
        exit(EXIT_FAILURE);
    }

    // prepare capture poll descriptors
    if ((err = snd_pcm_poll_descriptors(capture_handle, pfds, ccount)) < 0)
    {
        printf("Unable to obtain poll descriptors for capture: %s\n", snd_strerror(err));
        return err;
    }

    // prepare playback poll descriptors
    if ((err = snd_pcm_poll_descriptors(playback_handle, pfds + ccount, pcount)) < 0)
    {
        printf("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
        return err;
    }

    if ((err = snd_pcm_prepare(playback_handle)) < 0) {
        fprintf(stderr, "cannot prepare audio interface for use(%s)\n",
             snd_strerror(err));
        return err;
    }

    if ((err = snd_pcm_start(capture_handle)) < 0) {
        fprintf(stderr, "cannot prepare audio interface for use(%s)\n",
             snd_strerror(err));
        return err;
    }

    memset(buf, 0, sizeof(buf));

    // final loop
    while (1) {
        err = poll(pfds, pfds_count, 5);
        // fprintf(stdout, "poll val: %d\n", err);

        if (err < 0)
        {
            fprintf(stderr, "poll error %s", snd_strerror(err));
            return -1;
        }

        if (err == 0)
            continue;

        // check if capture devices are ready
        snd_pcm_poll_descriptors_revents(capture_handle, pfds, ccount, &revents);
        if (revents & POLLERR)
            fprintf(stderr, "capture poll error");
        if (revents & POLLIN)
        {
            avail = snd_pcm_avail_update(capture_handle);
            if (avail > 0)
            {
                if (avail > BUFSIZE)
                    avail = BUFSIZE;

                snd_pcm_readi(capture_handle, buf, avail);
            }
        }

        // check if playback devices are ready
        snd_pcm_poll_descriptors_revents(playback_handle, pfds + ccount, pcount, &revents);
        if (revents & POLLERR)
            fprintf(stderr, "playback poll error");
        if (revents & POLLOUT)
        {
            avail = snd_pcm_avail_update(playback_handle);
            if (avail > 0)
            {
                if (avail > BUFSIZE)
                    avail = BUFSIZE;

                snd_pcm_writei(playback_handle, buf, avail);
            }
        }
    }

    snd_pcm_close(playback_handle);
    snd_pcm_close(capture_handle);
    return 0;
}

Am I forgetting about something important? The audio is garbage, reacts for the change in amplitude on the input, but then breaks totally after a few seconds. Based on the alsaloop.c and pcm.c from the alsa-utils and alsa-lib repos, this is what I've come up with for the basic form of a loopback software.

If any of this is obviously wrong, please let me know.


问:
Image import is not a valid image file

Summary

I should expect my expo-react-native + nextjs app to build after installing and adding the 'next-images' plugin just like the docs say, but at build time I am stopped by 7 occurrences of the same exact error: "Error: Image import "./assets/X.png" is not a valid image file. The image may be corrupted or an unsupported format." This error is found not only in my own code, but code from packages that I have installed (specifically react-navigation)

Environment

expo-env-info 1.0.5 environment info:
System:
OS: Linux 5.15 Debian GNU/Linux 11 (bullseye) 11 (bullseye)
Shell: 5.1.4 - /bin/bash
Binaries:
Node: 16.17.0 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/yarn
npm: 8.15.0 - /usr/local/bin/npm
Watchman: 20220528.183901.0 - /usr/local/bin/watchman
npmPackages:
expo: ^47.0.0 => 47.0.8
react: 18.1.0 => 18.1.0
react-dom: 18.1.0 => 18.1.0
react-native: 0.70.5 => 0.70.5
react-native-web: ~0.18.7 => 0.18.10
Expo Workflow: managed

Please specify your device/emulator/simulator platform, model and version

ChromeOS Version 102.0.5005.189 (Official Build) (64-bit) and CodeSandbox Projects: Latests browser version

Error output

@react-navigation/elements:154
Error: Image import "./assets/back-icon-mask.png" is not a valid image file. The image may be corrupted or an unsupported format.

./AppbarBackIcon:66
Error: Image import "../../assets/back-chevron.png" is not a valid image file. The image may be corrupted or an unsupported format.

you get the idea

Reproducible demo or steps to reproduce from a blank project

Link to repl. This repl is my dev environment with all my code removed. The repl should run automatically when it boots. If not, run the command cd north-sea-native-next/north-sea/next && yarn next dev and wait for the page to build and the error to appear

Title: Image import is not a valid image file


问:
disable emergency calling api on twillio not working
I am trying to write an API call that would disable 911 calling on a Twillio phone number.  I am following the twilio API guide using Pyhon and even on straight up curl and 911 calling is still not being disabled.  I have waited over 5 minutes and it still does not disable.  Am I missing something?

I have other API calls that I am using with the same account_sid and account_token and they all seem to work, except for this one.  I have also validated on the twillio portal that the PN number matches the 10 digit number I am trying to disable.

On the Curl and Python I am using the same account info as well as the phone number.  I see my account info being printed out, so I know my account is valid.

Is there a requirement or something I need to do prior to disabling a 911 number from a phone number?

https://www.twilio.com/docs/sip-trunking/api/emergency-calling

```<code>Curl:
TWILIO_ACCOUNT_SID=ACb0xxxxxxxxxxxxxxxxxxxxxxxxxxx1
TWILIO_AUTH_TOKEN=9etttttttttttttttttttttttttttttttc
pn_number=PN1111111111111111111111111111111111

curl -X POST "https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/IncomingPhoneNumbers/$pn_number" \
--data-urlencode "EmergencyStatus=Inactive" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN

Python:
def disable_ems_calling(self, phone_number):

    # Converts 10 digit number to twilio PN Number
    pn_sid = self.get_phone_sid(phone_number)

    try:
        incoming_phone_number = self.client \
            .incoming_phone_numbers(pn_sid) \
            .update(emergency_status='Inactive')

        print(f"\n\nphone number {phone_number} with pn_sid {pn_sid} is being deactivated\n\n")
        return incoming_phone_number.friendly_name

    except TwilioRestException as e:
        print({e})
        return jsonify({"msg": f"{e}"}), 400
</code>```

Body:
I am trying to write an API call that would disable 911 calling on a Twillio phone number.  I am following the twilio API guide using Pyhon and even on straight up curl and 911 calling is still not being disabled.  I have waited over 5 minutes and it still does not disable.  Am I missing something?

I have other API calls that I am using with the same account_sid and account_token and they all seem to work, except for this one.  I have also validated on the twillio portal that the PN number matches the 10 digit number I am trying to disable.

On the Curl and Python I am using the same account info as well as the phone number.  I see my account info being printed out, so I know my account is valid.

Is there a requirement or something I need to do prior to disabling a 911 number from a phone number?

https://www.twilio.com/docs/sip-trunking/api/emergency-calling

Curl:
TWILIO_ACCOUNT_SID=ACb0xxxxxxxxxxxxxxxxxxxxxxxxxxx1
TWILIO_AUTH_TOKEN=9etttttttttttttttttttttttttttttttc
pn_number=PN1111111111111111111111111111111111

curl -X POST "https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/IncomingPhoneNumbers/$pn_number" \
--data-urlencode "EmergencyStatus=Inactive" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN

Python:
def disable_ems_calling(self, phone_number):

    # Converts 10 digit number to twilio PN Number
    pn_sid = self.get_phone_sid(phone_number)

    try:
        incoming_phone_number = self.client \
            .incoming_phone_numbers(pn_sid) \
            .update(emergency_status='Inactive')

        print(f"\n\nphone number {phone_number} with pn_sid {pn_sid} is being deactivated\n\n")
        return incoming_phone_number.friendly_name

    except TwilioRestException as e:
        print({e})
        return jsonify({"msg": f"{e}"}), 400


问:
How to structure large queries in spark
I have recently converted an enormous SAS datastep program to pyspark and I think the query is so large that the Catalyst optimizer causes an OOM error in the driver. I am able to run the query when I increase the driver memory to 256gb, but anything less and the job fails. This happens even when I run on a dataset with very few records.

This query takes a single input dataset, performs transformations on the input columns to generate a new set of columns. There are no joins, just 1000s of intermediate calcualtions to produce a final dataset with ~800 columns.

How can I structure such a large query so that spark can run it with fewer compute resources? I am being deliberatly vague, but the new columns I am producing essentially use F.when and some array operations on columns created from F.split.

My final action query looks like below and results in a logical plan that is enormous.

cols = [<list of 800 column expressions>]

df.select(*cols).write.parquet("<path/to/file>")
```

I have read plenty about checkpointing and how that truncates the logical plan. Does the plan need to be sent to the executors and it might be too big to fit in their memory? What is a best practice way to structure an enormous query? My first thought is to break it up into many smaller queries and then do a join at the end.

Title: How to structure large queries in spark

Body:
I have recently converted an enormous SAS datastep program to pyspark and I think the query is so large that the Catalyst optimizer causes an OOM error in the driver. I am able to run the query when I increase the driver memory to 256gb, but anything less and the job fails. This happens even when I run on a dataset with very few records.

This query takes a single input dataset, performs transformations on the input columns to generate a new set of columns. There are no joins, just 1000s of intermediate calcualtions to produce a final dataset with ~800 columns.

How can I structure such a large query so that spark can run it with fewer compute resources? I am being deliberatly vague, but the new columns I am producing essentially use F.when and some array operations on columns created from F.split.

My final action query looks like below and results in a logical plan that is enormous.

cols = [<list of 800 column expressions>]

df.select(*cols).write.parquet("<path/to/file>")

I have read plenty about checkpointing and how that truncates the logical plan. Does the plan need to be sent to the executors and it might be too big to fit in their memory? What is a best practice way to structure an enormous query? My first thought is to break it up into many smaller queries and then do a join at the end.


问:
How can I make a user-selected theme apply on all pages?
I'm working on a website project, and I need a way for a user to select the theme to be light or dark. Ideally I would like the light and dark themes to be stored in different css files, and actuated by a button. I also need the styles to be applied across all pages, and to change to the selected theme no matter what page the user is on.

Also is there any way to make this possible without using databases? I'm aiming to make this site a self-contained offline package, working off of localhost. Is this at all possible? Thanks in advance


问:
Blender Grids with figures
I'm a beginner at using blender. I have a basic blender grid of 15 x 15 pixels and i want to add attach an image to every pixel. How can I do that ?

I have tried to just stick the images on the grid manually but it's not the good way to go !

P.S. If there's a python scripting way to do this, it should be okay for me too !

Title: Blender Grids with figures


问:
Electron + Node + SQLite: 'no such table: files'
In electron front end, I have a button that successfully invokes a backend function to write to the db. Using this statement

```<code>const stmt = db.prepare(
    `INSERT INTO files (filename, path, tags_auto, tags_manual, object) VALUES ("Name of files", "Path of files", "auto", "manual", "object item")`
)
</code>```

gives this error

```<code>SqliteError: no such table: files
    at Database.exec (G:\Dev\phyle\node_modules\better-sqlite3\lib\methods\wrappers.js:9:14)
    at exports.storeFiles (G:\Dev\phyle\src\sqlite\dbFiles.js:16:22)
    at AsyncFunction.getTree (G:\Dev\phyle\src\preload.js:38:10)
</code>```

"better-sqlite3": "^8.0.1", wrapper for sqlite3.

Setup invoked with

```<code>const db = require('better-sqlite3')('./phyle.db', { fileMustExist: true })
</code>```

I have already build a database using sqlite studio (file.db) with "files" table, other tables, with primary keys and what not. I put one row in the files table, but every table produces it's own "no such table" error.

The error does not change with or without fileMustExist flag, with or without a valid file.db file. There are constraints on the tables, but theyve been filled/changed since getting this message.

Bottom line is that the table is there, but this thinks it isn't.

What could be causing it to believe the tables isn't there?

Body:
In electron front end, I have a button that successfully invokes a backend function to write to the db. Using this statement

const stmt = db.prepare(
    `INSERT INTO files (filename, path, tags_auto, tags_manual, object) VALUES ("Name of files", "Path of files", "auto", "manual", "object item")`
)

gives this error

SqliteError: no such table: files
    at Database.exec (G:\Dev\phyle\node_modules\better-sqlite3\lib\methods\wrappers.js:9:14)
    at exports.storeFiles (G:\Dev\phyle\src\sqlite\dbFiles.js:16:22)
    at AsyncFunction.getTree (G:\Dev\phyle\src\preload.js:38:10)

"better-sqlite3": "^8.0.1", wrapper for sqlite3.

Setup invoked with

const db = require('better-sqlite3')('./phyle.db', { fileMustExist: true })

I have already build a database using sqlite studio (file.db) with "files" table, other tables, with primary keys and what not. I put one row in the files table, but every table produces it's own "no such table" error.

The error does not change with or without fileMustExist flag, with or without a valid file.db file. There are constraints on the tables, but theyve been filled/changed since getting this message.

Bottom line is that the table is there, but this thinks it isn't.

What could be causing it to believe the tables isn't there?


问:
Selecting USB connected iphone as audio output for Mac
I am trying to build a project that will allow me to use an iphone USB connected to a Mac as an audio output device. There are options to do this wirelessly like "AirFoil" but they all introduce latency during playback.

When connected via USB, the iphone will appear in Audio Midi Setup as a device. Currently it is only selectable as an input device. I believe it can be used as an external microphone or a midi input device. My hope is that through code, the grayed output selection could be overridden. Is this even possible?

Iphone_IO.png

From what I've read the AVAudioEngine might provide a solution to this? I have read through posts about listing all available AudioDevices by ID.

list-all-available-audio-devices

From here would I be able to set the audio output device as the iphone? Or is this something that would require a companion app running on the phone to route the audio as well? Any information would be helpful, thanks!


问:
Laravel sanctum set expiration date
I am trying to add an expiration date when a token is made, but it does not work.

I don't know if I have to do more than that I have already

In my sanctum.php I have set the exparation to:

```<code>'expiration' => 525600,
</code>```

This is my function where a token is created:

```<code>public function login(Request $request){
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|max:255'
        ]);

        $user = User::where('email', $request->email)->first();
        if (!$user || !Hash::check($request->password, $user->password)){
            return response()->json([
                'error' => 'De ingevulde gegevens zijn fout'
            ]);
        }

        $token = $user->createToken($request->email);

        return response()->json([
            'response' => $token->plainTextToken
        ], 200);

    }
</code>```

I've already tried to run: php artisan config:clear. And that did not work as well.

In my database the expires_at in the personal_access_tokens table stays null and I don't knwo why

Title: Laravel sanctum set expiration date

Body:
I am trying to add an expiration date when a token is made, but it does not work.

I don't know if I have to do more than that I have already

In my sanctum.php I have set the exparation to:

'expiration' => 525600,

This is my function where a token is created:

public function login(Request $request){
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|max:255'
        ]);

        $user = User::where('email', $request->email)->first();
        if (!$user || !Hash::check($request->password, $user->password)){
            return response()->json([
                'error' => 'De ingevulde gegevens zijn fout'
            ]);
        }

        $token = $user->createToken($request->email);

        return response()->json([
            'response' => $token->plainTextToken
        ], 200);

    }

I've already tried to run: php artisan config:clear. And that did not work as well.

In my database the expires_at in the personal_access_tokens table stays null and I don't knwo why


问:
Button in for loops Twine 2.3.14 SugarCube 2
Edit:

Solved it after some more trial and error.
I needed to "capture" the variables first:

```<code>...
<<capture _itemkey, _itemkeys, _itemkeysattributes>>
<tr>
<td><<print [_itemkeys[_j]] >> <<print [_itemkeysattributes[_k]]>></td>
<td><<print $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].cost>></td>
<td><<print $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].owned>></td>
<<print ' @@.UIButton;<<button "Use a potion">>
<<run $items[_itemkey[(' + _i + ')]][_itemkeys[(' + _j + ')]][_itemkeysattributes[(' + _k + ')]].owned -= 1>>
<<goto "' + passage() + '">><</button>>@@'>>
</tr>
<</capture>>
...
</code>```

I implemented a table with for loops.
While the table generates fine, I can't get a button that adjusts an array value to work, it just gives the following error:
"Error: <>: bad evaluation: Cannot read properties of undefined (reading 'undefined')."

printing $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].owned works, just not adjusting it via the button.

Item array looks like this:

```<code><<set $items = {
   "Potions":{
      "IQ":{
         "+":{
            purchased: false,
            class: "item",
            cost: 20,
            owned: 0,
         },
        "+ +":{
            purchased: false,
            class: "item",
            cost: 50,
            owned: 0,
         },
         "-":{
            purchased: false,
            class: "item",
            cost: 20,
            owned: 0,
         },
        "- -":{
            purchased: false,
            class: "item",
            cost: 50,
            owned: 0,
         },
      },
      "Luck":{
         "+":{
            purchased: false,
            class: "item",
            cost: 20,
            owned: 0,
         },
        "+ +":{
            purchased: false,
            class: "item",
            cost: 50,
            owned: 0,
         },
         "-":{
            purchased: false,
            class: "item",
            cost: 20,
            owned: 0,
         },
        "- -":{
            purchased: false,
            class: "item",
            cost: 50,
            owned: 0,
         },
      },
   },
}>>
</code>```

Table is then generated like this:

```<code><table style="width:100%">
<tr>
<th style="text-align:center;">Item</th>
<th style="text-align:center;">Current cost</th>
<th style="text-align:center;">Owned Quantity</th>
<th style="text-align:center;">Action</th>
</tr>
<<set _itemkey = Object.keys($items)>>
<<for _i = 0; _i < _itemkey.length; _i++>>
<<set _itemkeys = Object.keys($items[_itemkey[_i]])>>
<<for _j = 0; _j < _itemkeys.length; _j++>>
<<set _itemkeysattributes = Object.keys($items[_itemkey[_i]][_itemkeys[_j]])>>
<<for _k = 0; _k < _itemkeysattributes.length; _k++>>
<<if $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].class == "item">>
<tr>
<td><<print [_itemkeys[_j]] >> <<print [_itemkeysattributes[_k]]>></td>
<td><<print $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].cost>></td>
<td><<print $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].owned>></td>
@@#button;<<button "Use on self">>
**<<run $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].owned -= 1>> **
<</button>>@@
</tr>
<<endif>>
<</for>>
<</for>>
<</for>>
</table>
</code>```

Table with buttons

Anyone know how I can get the button to reduce the owned quantity for each item used?

Body:
Edit:

Solved it after some more trial and error.
I needed to "capture" the variables first:

...
<<capture _itemkey, _itemkeys, _itemkeysattributes>>

<<print [_itemkeys[_j]] >> <<print [_itemkeysattributes[_k]]>>
<<print $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].cost>>
<<print $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].owned>>
<<print ' @@.UIButton;<<button "Use a potion">>
<<run $items[_itemkey[(' + _i + ')]][_itemkeys[(' + _j + ')]][_itemkeysattributes[(' + _k + ')]].owned -= 1>>
<<goto "' + passage() + '">><</button>>@@'>>

<</capture>>
...

I implemented a table with for loops.
While the table generates fine, I can't get a button that adjusts an array value to work, it just gives the following error:
"Error: <>: bad evaluation: Cannot read properties of undefined (reading 'undefined')."

printing $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].owned works, just not adjusting it via the button.

Item array looks like this:

<<set $items = {
   "Potions":{
      "IQ":{
         "+":{
            purchased: false,
            class: "item",
            cost: 20,
            owned: 0,
         },
        "+ +":{
            purchased: false,
            class: "item",
            cost: 50,
            owned: 0,
         },
         "-":{
            purchased: false,
            class: "item",
            cost: 20,
            owned: 0,
         },
        "- -":{
            purchased: false,
            class: "item",
            cost: 50,
            owned: 0,
         },
      },
      "Luck":{
         "+":{
            purchased: false,
            class: "item",
            cost: 20,
            owned: 0,
         },
        "+ +":{
            purchased: false,
            class: "item",
            cost: 50,
            owned: 0,
         },
         "-":{
            purchased: false,
            class: "item",
            cost: 20,
            owned: 0,
         },
        "- -":{
            purchased: false,
            class: "item",
            cost: 50,
            owned: 0,
         },
      },
   },
}>>

Table is then generated like this:

Item
Current cost
Owned Quantity
Action

<<set _itemkey = Object.keys($items)>>
<<for _i = 0; _i < _itemkey.length; _i++>>
<<set _itemkeys = Object.keys($items[_itemkey[_i]])>>
<<for _j = 0; _j < _itemkeys.length; _j++>>
<<set _itemkeysattributes = Object.keys($items[_itemkey[_i]][_itemkeys[_j]])>>
<<for _k = 0; _k < _itemkeysattributes.length; _k++>>
<<if $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].class == "item">>

<<print [_itemkeys[_j]] >> <<print [_itemkeysattributes[_k]]>>
<<print $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].cost>>
<<print $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].owned>>
@@#button;<<button "Use on self">>
**<<run $items[_itemkey[_i]][_itemkeys[_j]][[_itemkeysattributes[_k]]].owned -= 1>> **
<</button>>@@

<<endif>>
<</for>>
<</for>>
<</for>>

Table with buttons

Anyone know how I can get the button to reduce the owned quantity for each item used?


问:
Webclient call returns entity ID with null value when the other part correctly
I use WebClient to make calls between services by using Spring boot and Java 11. However, I receive the response entity with a null ID and the other parts have valid values. Whereas I have another call (WebClient) for another service and I receive the correct
response. How can I fix this issue in order to receive also the ID

```<code>@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Customer {

    @JsonProperty("customer_id")
    private Integer customerID;
    private String name;
    private String surname;
    private Integer balance;
}
</code>```
```<code>final String CUSTOMER_BASE_URL = "http://CUSTOMER-SERVICE/api/v1";

Customer customer = webClient.baseUrl(CUSTOMER_BASE_URL).build().get().uri("/customer/1")
                .retrieve().toEntity(Customer.class).block().getBody();
</code>```

Response:

```<code>customerID = null
name = "Renos"
surname = "Bardis"
balance = {Integer@16157} 100
</code>```

Body:
I use WebClient to make calls between services by using Spring boot and Java 11. However, I receive the response entity with a null ID and the other parts have valid values. Whereas I have another call (WebClient) for another service and I receive the correct
response. How can I fix this issue in order to receive also the ID

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Customer {

    @JsonProperty("customer_id")
    private Integer customerID;
    private String name;
    private String surname;
    private Integer balance;
}

final String CUSTOMER_BASE_URL = "http://CUSTOMER-SERVICE/api/v1";

Customer customer = webClient.baseUrl(CUSTOMER_BASE_URL).build().get().uri("/customer/1")
                .retrieve().toEntity(Customer.class).block().getBody();

Response:

customerID = null
name = "Renos"
surname = "Bardis"
balance = {Integer@16157} 100


问:
function performs differently when calling it via onValueChange
I have a react native component that allows me to fire a function called updateTags when it is pressed.

```<code><Checkbox
    style={styles.checkbox}
    value={item.isChecked}
    onValueChange={() => updateTags(item.id)}
/>
</code>```

The function essentially updates an object list to reflect just the checkboxes that have been toggled to active or inactive. I've no problem when utilizing the function in this way.

The problem is that users will revisit a settings page and need their prior choices pre-selected. To do that, I run this

```<code>const setPriorTags = () => {
    data.tags.map((item, index) => {
        updateTags(item.id);
    });
}
</code>```

When the screen comes into focus, I run the setPriorTags() function, the nested updateTags() function behaves differently compared to when I initialized it from onValueChange() as shown above. The problem is that it updates my object list in a manner as if only one prior selection was saved, even if I have more than one. Why is the same function behaving differently, and how can I fix this?

For reference:

```<code>const [tags, setTags] = useState(SelectionOption.dietTags);

const updateTags = (id) => {
// Note: this function works as intended when I have a list of multiple checkboxes
    let temp = tags.map((tag) => {
        if (id === tag.id) {
            return { ...tag, isChecked: !tag.isChecked };
        }
        return tag;
    });

    setTags(temp);
}
</code>```

My data object for the list of all items

```<code>export const dietTags = [
    {id: 1, label: "Vegan", isChecked: false},
    {id: 2, label: "Vegetarian", isChecked: false},
    {id: 3, label: "Pescatarian", isChecked: false},
    {id: 4, label: "Carnivore", isChecked: false}
]
</code>```

the list of pre-selected items gets stored in data from an outside data source (Firebase). Example output of data.tags:

```<code>[
    {"id": 1, "isChecked": true, "label": "Vegan"},
    {"id": 3, "isChecked": true, "label": "Pescatarian"}
]
</code>```

The desired output after running setPriorTags() is this:

```<code>[
    {id: 1, label: "Vegan", isChecked: true},
    {id: 2, label: "Vegetarian", isChecked: false},
    {id: 3, label: "Pescatarian", isChecked: true},
    {id: 4, label: "Carnivore", isChecked: false}
]
</code>```

Right now, the output of the function within .map() looks like this (because Pescatarian was the last item in the list):

```<code>[
    {id: 1, label: "Vegan", isChecked: false},
    {id: 2, label: "Vegetarian", isChecked: false},
    {id: 3, label: "Pescatarian", isChecked: true},
    {id: 4, label: "Carnivore", isChecked: false}
]
</code>```

Body:
I have a react native component that allows me to fire a function called updateTags when it is pressed.

<Checkbox
    style={styles.checkbox}
    value={item.isChecked}
    onValueChange={() => updateTags(item.id)}
/>

The function essentially updates an object list to reflect just the checkboxes that have been toggled to active or inactive. I've no problem when utilizing the function in this way.

The problem is that users will revisit a settings page and need their prior choices pre-selected. To do that, I run this

const setPriorTags = () => {
    data.tags.map((item, index) => {
        updateTags(item.id);
    });
}

When the screen comes into focus, I run the setPriorTags() function, the nested updateTags() function behaves differently compared to when I initialized it from onValueChange() as shown above. The problem is that it updates my object list in a manner as if only one prior selection was saved, even if I have more than one. Why is the same function behaving differently, and how can I fix this?

For reference:

const [tags, setTags] = useState(SelectionOption.dietTags);

const updateTags = (id) => {
// Note: this function works as intended when I have a list of multiple checkboxes
    let temp = tags.map((tag) => {
        if (id === tag.id) {
            return { ...tag, isChecked: !tag.isChecked };
        }
        return tag;
    });

    setTags(temp);
}

My data object for the list of all items

export const dietTags = [
    {id: 1, label: "Vegan", isChecked: false},
    {id: 2, label: "Vegetarian", isChecked: false},
    {id: 3, label: "Pescatarian", isChecked: false},
    {id: 4, label: "Carnivore", isChecked: false}
]

the list of pre-selected items gets stored in data from an outside data source (Firebase). Example output of data.tags:

[
    {"id": 1, "isChecked": true, "label": "Vegan"},
    {"id": 3, "isChecked": true, "label": "Pescatarian"}
]

The desired output after running setPriorTags() is this:

[
    {id: 1, label: "Vegan", isChecked: true},
    {id: 2, label: "Vegetarian", isChecked: false},
    {id: 3, label: "Pescatarian", isChecked: true},
    {id: 4, label: "Carnivore", isChecked: false}
]

Right now, the output of the function within .map() looks like this (because Pescatarian was the last item in the list):

[
    {id: 1, label: "Vegan", isChecked: false},
    {id: 2, label: "Vegetarian", isChecked: false},
    {id: 3, label: "Pescatarian", isChecked: true},
    {id: 4, label: "Carnivore", isChecked: false}
]


问:
Display in woocommerce order management page custom made <input fields> for shipping methods
I have created the following code which I have added to the PHP function to create two input fields placed just below the fixed-rate shipping method on the check out page. In these two input fields customers can enter their shipping provider and account number.

The input fields work perfectly, the problem is that when the order is placed, the values entered (shipping provider name and account number) in these two fields do not appear in the order details on woocommerce.

Can you please advise me how I can make the two fields appear on the woocommerce order management page so that I know what customers have entered?

code:

```<code>function checkout_shipping_additional_field( $method, $index )
{
    if( $method->get_id() == 'flat_rate:35' ){
        echo '<br>
        <input type="text" id="Name" name="Name" placeholder="Shipping Provider">
        <input type="text" id="Name" name="Name" placeholder="Account Number">';

    }
}
</code>```

Body:
I have created the following code which I have added to the PHP function to create two input fields placed just below the fixed-rate shipping method on the check out page. In these two input fields customers can enter their shipping provider and account number.

The input fields work perfectly, the problem is that when the order is placed, the values entered (shipping provider name and account number) in these two fields do not appear in the order details on woocommerce.

Can you please advise me how I can make the two fields appear on the woocommerce order management page so that I know what customers have entered?

code:

function checkout_shipping_additional_field( $method, $index )
{
    if( $method->get_id() == 'flat_rate:35' ){
        echo '

        <input type="text" id="Name" name="Name" placeholder="Shipping Provider">
        <input type="text" id="Name" name="Name" placeholder="Account Number">';

    }
}


问:
Why is the intersection distance the same of all objects, even though they have different positions?
We have three spheres

```<code>const object1 = new THREE.Mesh(
    new THREE.SphereGeometry(0.5, 16, 16),
    new THREE.MeshBasicMaterial({ color: '#ff0000' })
)
object1.position.x = - 2

const object2 = new THREE.Mesh(
    new THREE.SphereGeometry(0.5, 16, 16),
    new THREE.MeshBasicMaterial({ color: '#ff0000' })
)

const object3 = new THREE.Mesh(
    new THREE.SphereGeometry(0.5, 16, 16),
    new THREE.MeshBasicMaterial({ color: '#ff0000' })
)
object3.position.x = 2
</code>```

And a raycaster

```<code>const raycaster = new THREE.Raycaster();

const rayOrigin = new THREE.Vector3(-3, 0, 0);
const rayDirection = new THREE.Vector3(1, 0, 0);

raycaster.set(rayOrigin, rayDirection);

const intersects = raycaster.intersectObjects([object1, object2, object3])
console.log(intersects)
</code>```

Logging the intersects array, we get this:

```<code>0: {distance: 2.5, point: Vector3, object: Mesh, uv: Vector2, face: {…}, …}
1: {distance: 2.5, point: Vector3, object: Mesh, uv: Vector2, face: {…}, …}
2: {distance: 2.5, point: Vector3, object: Mesh, uv: Vector2, face: {…}, …}
length: 3
</code>```

Why is the distance the same for all spheres? Shouldn't the distances be 0.5, 2.5 and 4.5 respectively? What am I missing?

Body:
We have three spheres

const object1 = new THREE.Mesh(
    new THREE.SphereGeometry(0.5, 16, 16),
    new THREE.MeshBasicMaterial({ color: '#ff0000' })
)
object1.position.x = - 2

const object2 = new THREE.Mesh(
    new THREE.SphereGeometry(0.5, 16, 16),
    new THREE.MeshBasicMaterial({ color: '#ff0000' })
)

const object3 = new THREE.Mesh(
    new THREE.SphereGeometry(0.5, 16, 16),
    new THREE.MeshBasicMaterial({ color: '#ff0000' })
)
object3.position.x = 2

And a raycaster

const raycaster = new THREE.Raycaster();

const rayOrigin = new THREE.Vector3(-3, 0, 0);
const rayDirection = new THREE.Vector3(1, 0, 0);

raycaster.set(rayOrigin, rayDirection);

const intersects = raycaster.intersectObjects([object1, object2, object3])
console.log(intersects)

Logging the intersects array, we get this:

0: {distance: 2.5, point: Vector3, object: Mesh, uv: Vector2, face: {…}, …}
1: {distance: 2.5, point: Vector3, object: Mesh, uv: Vector2, face: {…}, …}
2: {distance: 2.5, point: Vector3, object: Mesh, uv: Vector2, face: {…}, …}
length: 3

Why is the distance the same for all spheres? Shouldn't the distances be 0.5, 2.5 and 4.5 respectively? What am I missing?


问:
Read Pulse value from Coin selector using Rasbperry PI 4 in C# Console Application
Hello guy i have problem in my code it always says low even i already insert coin in Coin Selector

```<code>using System;
using System.Device.Gpio;
using System.Threading;

try
{

    Thread.Sleep(1000);
    int pin = 16;
    using var controller = new GpioController();
    controller.OpenPin(pin, PinMode.Input);

    while (true)
    {
        String ButtonState = controller.Read(pin).ToString();
        Console.WriteLine(ButtonState); //checking the state if the digital value is changing
        Thread.Sleep(1000);
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
    Thread.Sleep(10000);
}

</code>```

This is my current code and I already configure the coin selector.. How can i read the pulse value from the selector?

My wiring is the coin wire is connected to gpio pins (like gpio 16)

I already tried different types of wiring and code but still not working

Body:
Hello guy i have problem in my code it always says low even i already insert coin in Coin Selector

using System;
using System.Device.Gpio;
using System.Threading;

try
{

    Thread.Sleep(1000);
    int pin = 16;
    using var controller = new GpioController();
    controller.OpenPin(pin, PinMode.Input);

    while (true)
    {
        String ButtonState = controller.Read(pin).ToString();
        Console.WriteLine(ButtonState); //checking the state if the digital value is changing
        Thread.Sleep(1000);
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
    Thread.Sleep(10000);
}

This is my current code and I already configure the coin selector.. How can i read the pulse value from the selector?

My wiring is the coin wire is connected to gpio pins (like gpio 16)

I already tried different types of wiring and code but still not working


问:
my python program don't connect to my data base
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1")

when I execute my program I get this problem if anyone can help please ,

```<code>def insert():
     nomcomplet=entryName.get()
     adresse=entryadr.get()

     saison=entrySEM.get()

     nombre_de_chambre=entryCHEM.get()

     if nomcomplet == "" or adresse == "" or saison == "" or nombre_de_chambre == "" :
         messagebox.showinfo("insert status","all field are requireds")
     else :
         con= pymysql.connect(host='localhost',port=3307,user="root" ,password="", db="miniprojet",local_infile=True)
         cursor = con.cursor()
         cursor.execute("insert into `moha` (nomcomplet,adresse,saison,nombre_de_chambre)")
         cursor.execute("commit");

         MessageBox.showinfo("insert status", "inserted successfully")
         con.close();
</code>```

that's the fonction of connection

Body:
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1")

when I execute my program I get this problem if anyone can help please ,

def insert():
     nomcomplet=entryName.get()
     adresse=entryadr.get()

     saison=entrySEM.get()

     nombre_de_chambre=entryCHEM.get()

     if nomcomplet == "" or adresse == "" or saison == "" or nombre_de_chambre == "" :
         messagebox.showinfo("insert status","all field are requireds")
     else :
         con= pymysql.connect(host='localhost',port=3307,user="root" ,password="", db="miniprojet",local_infile=True)
         cursor = con.cursor()
         cursor.execute("insert into `moha` (nomcomplet,adresse,saison,nombre_de_chambre)")
         cursor.execute("commit");

         MessageBox.showinfo("insert status", "inserted successfully")
         con.close();

that's the fonction of connection


问:
Transposing and stacking
Please how to transform my dataset from the unstacked to the stacked?

unstacked

stacked

Thank you.

I tried transposing, cbind, library(data.table), but none seems working

Title: Transposing and stacking


问:
Running mpirun on a go-program that runs as a linux service exists with code 1
Short description of the setup:
I have a go executable running as a linux service on a compute engine instance on GCP.
This go program should start a other executable in a cluster with mpirun but the command always fails with code 1.

No its getting wired, I print out the command before I run it. If I trigger the command manually via ssh on the server it works flawlessly. So mpi seems to be setup correctly.

```<code>func (r *EngineRunner) clusterCommand(executable string) (string, []string) {
  slots := len(r.nodeManager.Nodes) + 1
  return "mpirun", []string{
    "--oversubscribe",
    "--hostfile",
    constants.GetMPIHostFilePath(),
    "-np",
    strconv.Itoa(slots),
    executable,
  }
}

// OpenStockfishSession returns already open session or creates a new one. If a new one is created second param is true.
func (r *EngineRunner) OpenStockfishSession(mode string, session string) (*EngineSession, bool, error) {
    r.sessionLock.Lock()
    defer r.sessionLock.Unlock()

    fullSessionKey := EngineNameStockfish + "/" + mode + "/" + session

    if s, ok := r.sessions[fullSessionKey]; ok {
        return s, false, nil
    }

    var cmd *exec.Cmd
    if mode == ModeMaster {
        println("run: " + GetStockfishBinaryPath())
        cmd = exec.Command(GetStockfishBinaryPath())
    } else if mode == ModeCluster {
        com, args := r.clusterCommand(GetStockfishBinaryPath())
        println("run: " + com + " " + strings.Join(args, " "))
        cmd = exec.Command(com, args...)
    } else {
        return nil, false, errors.New("invalid mode")
    }

    stderr, err := cmd.StderrPipe()
    if err != nil {
        return nil, false, err
    }

    stdin, err := cmd.StdinPipe()
    if err != nil {
        return nil, false, err
    }

    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return nil, false, err
    }

    // Start the command
    if err := cmd.Start(); err != nil {
        return nil, false, err
    }

    newSession := &EngineSession{
        cmd:    cmd,
        StdIn:  stdin,
        StdOut: stdout,
    }

    r.sessions[fullSessionKey] = newSession

    go func() {
        defer func() {
            delete(r.sessions, fullSessionKey)
        }()
        if err := cmd.Wait(); err != nil {
            println("error while waiting for stockfish process", err.Error())
            stderrStr, _ := io.ReadAll(stderr)
            stdoutStr, _ := io.ReadAll(stdout)
            println("Stderr: " + string(stderrStr))
            println("Stdout: " + string(stdoutStr))
        }
    }()

    return newSession, true, nil
}
</code>```

The printed command looks like this:

```<code>mpirun --oversubscribe --hostfile /usr/sbin/cec_rd/mpi_hostfile -np 3 /usr/sbin/cec_rd/engines/stockfish/stockfish
</code>```

The paths seem to be correct and also mpi is setup correctly, as if I copy this command and run it via ssh it works...

Hope someone has an idea as I am kind of done, cheers

Body:
Short description of the setup:
I have a go executable running as a linux service on a compute engine instance on GCP.
This go program should start a other executable in a cluster with mpirun but the command always fails with code 1.

No its getting wired, I print out the command before I run it. If I trigger the command manually via ssh on the server it works flawlessly. So mpi seems to be setup correctly.

func (r *EngineRunner) clusterCommand(executable string) (string, []string) {
  slots := len(r.nodeManager.Nodes) + 1
  return "mpirun", []string{
    "--oversubscribe",
    "--hostfile",
    constants.GetMPIHostFilePath(),
    "-np",
    strconv.Itoa(slots),
    executable,
  }
}

// OpenStockfishSession returns already open session or creates a new one. If a new one is created second param is true.
func (r *EngineRunner) OpenStockfishSession(mode string, session string) (*EngineSession, bool, error) {
    r.sessionLock.Lock()
    defer r.sessionLock.Unlock()

    fullSessionKey := EngineNameStockfish + "/" + mode + "/" + session

    if s, ok := r.sessions[fullSessionKey]; ok {
        return s, false, nil
    }

    var cmd *exec.Cmd
    if mode == ModeMaster {
        println("run: " + GetStockfishBinaryPath())
        cmd = exec.Command(GetStockfishBinaryPath())
    } else if mode == ModeCluster {
        com, args := r.clusterCommand(GetStockfishBinaryPath())
        println("run: " + com + " " + strings.Join(args, " "))
        cmd = exec.Command(com, args...)
    } else {
        return nil, false, errors.New("invalid mode")
    }

    stderr, err := cmd.StderrPipe()
    if err != nil {
        return nil, false, err
    }

    stdin, err := cmd.StdinPipe()
    if err != nil {
        return nil, false, err
    }

    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return nil, false, err
    }

    // Start the command
    if err := cmd.Start(); err != nil {
        return nil, false, err
    }

    newSession := &EngineSession{
        cmd:    cmd,
        StdIn:  stdin,
        StdOut: stdout,
    }

    r.sessions[fullSessionKey] = newSession

    go func() {
        defer func() {
            delete(r.sessions, fullSessionKey)
        }()
        if err := cmd.Wait(); err != nil {
            println("error while waiting for stockfish process", err.Error())
            stderrStr, _ := io.ReadAll(stderr)
            stdoutStr, _ := io.ReadAll(stdout)
            println("Stderr: " + string(stderrStr))
            println("Stdout: " + string(stdoutStr))
        }
    }()

    return newSession, true, nil
}

The printed command looks like this:

mpirun --oversubscribe --hostfile /usr/sbin/cec_rd/mpi_hostfile -np 3 /usr/sbin/cec_rd/engines/stockfish/stockfish

The paths seem to be correct and also mpi is setup correctly, as if I copy this command and run it via ssh it works...

Hope someone has an idea as I am kind of done, cheers


问:
lasso regression for larger datasets using dask
I'm attempting to perform a lasso regression for a larger than main memory dataset by using Dask, but there doesn't seem to be a cleanly documented way to do so.

I did previously find a somewhat related question but no actual answer.

Looking into how scikit sets up the Lasso regression, I thought I could set it up the same way. For example, here is one approach I tried

from dask_ml.datasets import make_regression
import dask_glm.families
import dask_glm.regularizers
import dask_glm.algorithms
import pandas as pd

# dask dataframes
X, y = make_regression(n_samples=1000, chunks=100)

# pandas dataframes
df_X = X.compute()
df_y = y.compute()

family = dask_glm.families.Normal()
regularizer = dask_glm.regularizers.ElasticNet(weight=1)
b = dask_glm.algorithms.gradient_descent(X=X, y=y, max_iter=100000, family=family, regularizer=regularizer, alpha=0.01, normalize=False, fit_intercept=False)
print(b)

reg = linear_model.Lasso(alpha=0.01, fit_intercept=False)
reg.fit(df_X, df_y)
print(reg.coef_)
```
<p>However, the coefficients don't match up at all, and the dask version's coefficients seem more unstable than scikit's.</p>
<p>Here's another approach I tried, this time based on a comment from this GH issue</p>
<pre class="lang-py prettyprint-override"><code>from dask_ml.datasets import make_regression
from dask_glm.regularizers import L1
from dask_glm.estimators import LinearRegression

X, y = make_regression(n_samples=1000, chunks=100)

lr = LinearRegression(regularizer=L1())
lr.fit(X, y)
print(lr.coef_)
</code>```

Again, the coefficients seem very unstable.

Ideally there would already be an implementation of Lasso using Dask for this, but I can't seem to find much on the internet except for running LassoCV with dask as the backend to joblib, which is a little different than I want.

Body:
I'm attempting to perform a lasso regression for a larger than main memory dataset by using Dask, but there doesn't seem to be a cleanly documented way to do so.

I did previously find a somewhat related question but no actual answer.

Looking into how scikit sets up the Lasso regression, I thought I could set it up the same way. For example, here is one approach I tried

from dask_ml.datasets import make_regression
import dask_glm.families
import dask_glm.regularizers
import dask_glm.algorithms
import pandas as pd

# dask dataframes
X, y = make_regression(n_samples=1000, chunks=100)

# pandas dataframes
df_X = X.compute()
df_y = y.compute()

family = dask_glm.families.Normal()
regularizer = dask_glm.regularizers.ElasticNet(weight=1)
b = dask_glm.algorithms.gradient_descent(X=X, y=y, max_iter=100000, family=family, regularizer=regularizer, alpha=0.01, normalize=False, fit_intercept=False)
print(b)

reg = linear_model.Lasso(alpha=0.01, fit_intercept=False)
reg.fit(df_X, df_y)
print(reg.coef_)

However, the coefficients don't match up at all, and the dask version's coefficients seem more unstable than scikit's.

Here's another approach I tried, this time based on a comment from this GH issue

from dask_ml.datasets import make_regression
from dask_glm.regularizers import L1
from dask_glm.estimators import LinearRegression

X, y = make_regression(n_samples=1000, chunks=100)

lr = LinearRegression(regularizer=L1())
lr.fit(X, y)
print(lr.coef_)

Again, the coefficients seem very unstable.

Ideally there would already be an implementation of Lasso using Dask for this, but I can't seem to find much on the internet except for running LassoCV with dask as the backend to joblib, which is a little different than I want.


问:
accurately check if user is using TWA
I'm trying to recognize if user is using the TWA app or not.

simple solution is to check if:

```<code>document.referrer.includes('android-app://<com.package.app>')
</code>```

But this is not working if you reload a page or open a page via another one. So I want a better solution.

We know if you run a link like this outside of the TWA app :

```<code>'example://check-app?action=check'
</code>```

it returns an error:

Failed to launch 'example://check-app?action=check' because the scheme
does not have a registered handler.

I think if we can catch this error we can recognize if user is using TWA or not. So I wrote this:

```<code>try {
    window.location.href = 'example://check-app?action=check'
} catch(err) {
    console.log(err)
}
</code>```

But it does't triger the catch at all.

is there any way to catch this error or check acuratly if user is using a TWA app.

Note: using sessionStorage is not a ideal way to do this. and you know why right?

Title: accurately check if user is using TWA

Body:
I'm trying to recognize if user is using the TWA app or not.

simple solution is to check if:

document.referrer.includes('android-app://<com.package.app>')

But this is not working if you reload a page or open a page via another one. So I want a better solution.

We know if you run a link like this outside of the TWA app :

'example://check-app?action=check'

it returns an error:

Failed to launch 'example://check-app?action=check' because the scheme
does not have a registered handler.

I think if we can catch this error we can recognize if user is using TWA or not. So I wrote this:

try {
    window.location.href = 'example://check-app?action=check'
} catch(err) {
    console.log(err)
}

But it does't triger the catch at all.

is there any way to catch this error or check acuratly if user is using a TWA app.

Note: using sessionStorage is not a ideal way to do this. and you know why right?


问:
add API currency convert to postres table in python
I have an exercise to do:

Through library psycopg2 connect with my database and get top 10 customers along with their credit limit:

```<code>import psycopg2

connection = psycopg2.connect(
    host='host',
    user='user',
    password='password',
    dbname='db_name',
)

cursor = connection.cursor()
cursor.execute('SELECT customername, creditlimit FROM customers order by 2 desc limit 10')

for row in cursor:
    row[0]
    row[1]
    print(f"{row[0]}: {row[1]} USD")
</code>```

This is the result of the query above:

As per next step I need to connect with API and convert this creditlimit to different currencies (EUR, JPY, GBP), so the final output will be like that:

```<code>Euro+ Shopping Channel: 227600.00 USD / 187183.93EUR / 24017262.40 JPY /160578.63 GBP
...
</code>```

This is the code for API (the key is valid, feel free to test):

```<code>headers = {
    "apikey": "b6iGXz0JZcr2iyV0SeLcd0dEpqOr8ngK"
}

currency = ['EUR', 'JPY', 'GBP']

params = {
    "from": "USD",
    "to": 'EUR',
    "amount": row[1]
}

url = "https://api.apilayer.com/exchangerates_data/convert"

response = requests.get(url, headers=headers, params=params)

if response.status_code == 200:
    data = response.json()
</code>```

I connected with API, but I have difficulties to append it to my sql data, please advise.

Body:
I have an exercise to do:

Through library psycopg2 connect with my database and get top 10 customers along with their credit limit:

import psycopg2

connection = psycopg2.connect(
    host='host',
    user='user',
    password='password',
    dbname='db_name',
)

cursor = connection.cursor()
cursor.execute('SELECT customername, creditlimit FROM customers order by 2 desc limit 10')

for row in cursor:
    row[0]
    row[1]
    print(f"{row[0]}: {row[1]} USD")

This is the result of the query above:

As per next step I need to connect with API and convert this creditlimit to different currencies (EUR, JPY, GBP), so the final output will be like that:

Euro+ Shopping Channel: 227600.00 USD / 187183.93EUR / 24017262.40 JPY /160578.63 GBP
...

This is the code for API (the key is valid, feel free to test):

headers = {
    "apikey": "b6iGXz0JZcr2iyV0SeLcd0dEpqOr8ngK"
}

currency = ['EUR', 'JPY', 'GBP']

params = {
    "from": "USD",
    "to": 'EUR',
    "amount": row[1]
}

url = "https://api.apilayer.com/exchangerates_data/convert"

response = requests.get(url, headers=headers, params=params)

if response.status_code == 200:
    data = response.json()

I connected with API, but I have difficulties to append it to my sql data, please advise.


问:
Why unittest.mock.mock_add_spec removes existing mock methods?
Why after using unittest.mock.mock add_spec methods of mock are disappearing?

```<code>from unittest.mock import Mock

m = Mock(spec=str)
print(hasattr(m, 'lower'))  # True
m.mock_add_spec(['foo'],)
print(hasattr(m, 'lower'))  # False
print(hasattr(m, 'foo'))  # True
</code>```

From the docs:

Only attributes on the spec can be fetched as attributes from the
mock.

TBH I don't quite get this line but obviously method with name "add" should not shrink the count of methods :)

Python version:

```<code>Python 3.10.9 (main, Dec  7 2022, 01:12:00) [GCC 9.4.0] on linux
</code>```

Body:
Why after using unittest.mock.mock add_spec methods of mock are disappearing?

from unittest.mock import Mock

m = Mock(spec=str)
print(hasattr(m, 'lower'))  # True
m.mock_add_spec(['foo'],)
print(hasattr(m, 'lower'))  # False
print(hasattr(m, 'foo'))  # True

From the docs:

Only attributes on the spec can be fetched as attributes from the
mock.

TBH I don't quite get this line but obviously method with name "add" should not shrink the count of methods :)

Python version:

Python 3.10.9 (main, Dec  7 2022, 01:12:00) [GCC 9.4.0] on linux


问:
How can I connect a WPF application to the Azure SignalR Service
I am working on a WPF application that I'd love to connect to the Azure SignalR Service that I created an instance of. There isn't anything that I can find that directly addresses this scenario. I can setup a BlazorServer and connect that way. But, i'd rather not host the server and use Azure.

Any idea of how that might look?

For example, I attempt this and it does not work:

```<code>HubConnection? connection;
connection = new HubConnectionBuilder()
                .WithUrl("https://scisachat.service.signalr.net/client/?hub=draftchat")
                .WithAutomaticReconnect()
                .Build();

connection.On<string, string>("ReceiveMessage", (user, message) =>
{
    this.Dispatcher.Invoke(() =>
    {
       var newMessage = $"{user}: {message}";
       Messages.Items.Add(newMessage);
       Messages.Items.Add($"Connected on {DateTime.Now}");
    });
});

try
{
   await connection.StartAsync();
   Messages.Items.Add("Connection Started");
   openConnection.IsEnabled = false;
   sendMessage.IsEnabled = true;
}
catch (Exception ex)
{
   Messages.Items.Add(ex.Message);
}
</code>```

I tried to connect to the Azure SignalR service as opposed to my chat hub on a localhost. It fails spectacularly.

Body:
I am working on a WPF application that I'd love to connect to the Azure SignalR Service that I created an instance of. There isn't anything that I can find that directly addresses this scenario. I can setup a BlazorServer and connect that way. But, i'd rather not host the server and use Azure.

Any idea of how that might look?

For example, I attempt this and it does not work:

HubConnection? connection;
connection = new HubConnectionBuilder()
                .WithUrl("https://scisachat.service.signalr.net/client/?hub=draftchat")
                .WithAutomaticReconnect()
                .Build();

connection.On<string, string>("ReceiveMessage", (user, message) =>
{
    this.Dispatcher.Invoke(() =>
    {
       var newMessage = $"{user}: {message}";
       Messages.Items.Add(newMessage);
       Messages.Items.Add($"Connected on {DateTime.Now}");
    });
});

try
{
   await connection.StartAsync();
   Messages.Items.Add("Connection Started");
   openConnection.IsEnabled = false;
   sendMessage.IsEnabled = true;
}
catch (Exception ex)
{
   Messages.Items.Add(ex.Message);
}

I tried to connect to the Azure SignalR service as opposed to my chat hub on a localhost. It fails spectacularly.