问:
Reading eID with NFC crushing in production build but it works in debug mode
I have a React-Native application and I implemented a 3rd party eID NFC Reader SDK. This 3rd SDK is using NFCPassportReader library and CoreNFC package also. I'm trying to read Turkish Citizenship eID with this module. My problem this module is working properly in debug mode but It's crushing in release version. I've added a crush log related to this issue and I've added tagReaderSession implementation code. I've added my "com.apple.developer.nfc.readersession.iso7816.select-identifiers" configuration code also.
Does anybody have an idea about that problem?

```<code>Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000000
Exception Codes: 0x0000000000000001, 0x0000000000000000
VM Region Info: 0 is not in any region.  Bytes before following region: 4340301824
      REGION TYPE                 START - END      [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      UNUSED SPACE AT START
--->
      __TEXT                   102b3c000-10603c000 [ 53.0M] r-x/r-x SM=COW  ...ePieMobileDev
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [9236]

Triggered by Thread:  8
</code>```
```<code>Thread 8 name:   Dispatch queue: com.apple.corenfc.readersession.delegate
Thread 8 Crashed:
</code>```
```<code>public func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
        Log.debug( "tagReaderSession:didDetect - \(tags[0])" )
        if tags.count > 1 {
            Log.debug( "tagReaderSession:more than 1 tag detected! - \(tags)" )

            let errorMessage = NFCViewDisplayMessage.error(.MoreThanOneTagFound)
            self.invalidateSession(errorMessage: errorMessage, error: NFCPassportReaderError.MoreThanOneTagFound)
            return
        }

        let tag = tags.first!
        var passportTag: NFCISO7816Tag
        switch tags.first! {
        case let .iso7816(tag):
            passportTag = tag
        default:
            Log.debug( "tagReaderSession:invalid tag detected!!!" )

            let errorMessage = NFCViewDisplayMessage.error(NFCPassportReaderError.TagNotValid)
            self.invalidateSession(errorMessage:errorMessage, error: NFCPassportReaderError.TagNotValid)
            return
        }

        // Connect to tag
        Log.debug( "tagReaderSession:connecting to tag - \(tag)" )
        session.connect(to: tag) { [unowned self] (error: Error?) in
            if error != nil {
                Log.debug( "tagReaderSession:failed to connect to tag - \(error?.localizedDescription ?? "Unknown error")" )
                let errorMessage = NFCViewDisplayMessage.error(NFCPassportReaderError.ConnectionError)
                self.invalidateSession(errorMessage: errorMessage, error: NFCPassportReaderError.ConnectionError)
                return
            }

            Log.debug( "tagReaderSession:connected to tag - starting authentication" )
            self.updateReaderSessionMessage( alertMessage: NFCViewDisplayMessage.authenticatingWithPassport(0) )

            self.tagReader = TagReader(tag:passportTag)

            if let newAmount = self.dataAmountToReadOverride {
                self.tagReader?.overrideDataAmountToRead(newAmount: newAmount)
            }

            self.tagReader!.progress = { [unowned self] (progress) in
                if let dgId = self.currentlyReadingDataGroup {
                    self.updateReaderSessionMessage( alertMessage: NFCViewDisplayMessage.readingDataGroupProgress(dgId, progress) )
                } else {
                    self.updateReaderSessionMessage( alertMessage: NFCViewDisplayMessage.authenticatingWithPassport(progress) )
                }
            }

            DispatchQueue.global().async {
                self.startReading( )
            }
        }
    }
</code>```
```<code><key>NFCReaderUsageDescription</key>
<string>Read the NFC chip of ePassports</string>
<key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
<array>
    <string>A0000002471001</string>
</array>
</code>```

Video recording of this issue:
https://vimeo.com/784270897

I can run the application in debug mode without any problems, but when I start reading nfc in release mode, the application crashes.

Body:
I have a React-Native application and I implemented a 3rd party eID NFC Reader SDK. This 3rd SDK is using NFCPassportReader library and CoreNFC package also. I'm trying to read Turkish Citizenship eID with this module. My problem this module is working properly in debug mode but It's crushing in release version. I've added a crush log related to this issue and I've added tagReaderSession implementation code. I've added my "com.apple.developer.nfc.readersession.iso7816.select-identifiers" configuration code also.
Does anybody have an idea about that problem?

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000000
Exception Codes: 0x0000000000000001, 0x0000000000000000
VM Region Info: 0 is not in any region.  Bytes before following region: 4340301824
      REGION TYPE                 START - END      [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      UNUSED SPACE AT START
--->
      __TEXT                   102b3c000-10603c000 [ 53.0M] r-x/r-x SM=COW  ...ePieMobileDev
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [9236]

Triggered by Thread:  8

Thread 8 name:   Dispatch queue: com.apple.corenfc.readersession.delegate
Thread 8 Crashed:

public func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
        Log.debug( "tagReaderSession:didDetect - \(tags[0])" )
        if tags.count > 1 {
            Log.debug( "tagReaderSession:more than 1 tag detected! - \(tags)" )

            let errorMessage = NFCViewDisplayMessage.error(.MoreThanOneTagFound)
            self.invalidateSession(errorMessage: errorMessage, error: NFCPassportReaderError.MoreThanOneTagFound)
            return
        }

        let tag = tags.first!
        var passportTag: NFCISO7816Tag
        switch tags.first! {
        case let .iso7816(tag):
            passportTag = tag
        default:
            Log.debug( "tagReaderSession:invalid tag detected!!!" )

            let errorMessage = NFCViewDisplayMessage.error(NFCPassportReaderError.TagNotValid)
            self.invalidateSession(errorMessage:errorMessage, error: NFCPassportReaderError.TagNotValid)
            return
        }

        // Connect to tag
        Log.debug( "tagReaderSession:connecting to tag - \(tag)" )
        session.connect(to: tag) { [unowned self] (error: Error?) in
            if error != nil {
                Log.debug( "tagReaderSession:failed to connect to tag - \(error?.localizedDescription ?? "Unknown error")" )
                let errorMessage = NFCViewDisplayMessage.error(NFCPassportReaderError.ConnectionError)
                self.invalidateSession(errorMessage: errorMessage, error: NFCPassportReaderError.ConnectionError)
                return
            }

            Log.debug( "tagReaderSession:connected to tag - starting authentication" )
            self.updateReaderSessionMessage( alertMessage: NFCViewDisplayMessage.authenticatingWithPassport(0) )

            self.tagReader = TagReader(tag:passportTag)

            if let newAmount = self.dataAmountToReadOverride {
                self.tagReader?.overrideDataAmountToRead(newAmount: newAmount)
            }

            self.tagReader!.progress = { [unowned self] (progress) in
                if let dgId = self.currentlyReadingDataGroup {
                    self.updateReaderSessionMessage( alertMessage: NFCViewDisplayMessage.readingDataGroupProgress(dgId, progress) )
                } else {
                    self.updateReaderSessionMessage( alertMessage: NFCViewDisplayMessage.authenticatingWithPassport(progress) )
                }
            }

            DispatchQueue.global().async {
                self.startReading( )
            }
        }
    }

<key>NFCReaderUsageDescription</key>
<string>Read the NFC chip of ePassports</string>
<key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
<array>
    <string>A0000002471001</string>
</array>

Video recording of this issue:
https://vimeo.com/784270897

I can run the application in debug mode without any problems, but when I start reading nfc in release mode, the application crashes.


来源: stackexchange

问:
I have deployed vue-cli app to gh pages. Loading ok. But after refreshing a 404-error occurs
I have made an app based on vue-cli 3 and vue-router, deployed it to gh pages and saved the link. When I click on the link, the app loads normal. But if I click on refresh/reload, a 404-error occurs.
My link: https://alexandrchek.github.io/filmrock/index.html

I tried to find the answer in the net. But I have not find a description of the same problem. There are no descriptions of problems with refreshing.
Why does it happen? Help me to fix this problem, please.

ContentLicense: CC BY-SA 4.0


问:
Builder.setMaxResolution can only be called from within the same library group
I got a warning, but I don't know what to do.

```<code>Builder.setMaxResolution can only be called from within the same library group (referenced groupId=androidx.camera from groupId=sample)
</code>```

Body:
I got a warning, but I don't know what to do.

Builder.setMaxResolution can only be called from within the same library group (referenced groupId=androidx.camera from groupId=sample)


问:
Extract Tabluar data from an image python
The problem here is whenever I am trying to turn the image to CSV, I always have a problem with the words and spaces itself because they are not equal to turning this text into CSV directly. I used OpenCV and tesseract to make this process but something is missing, here's the Image I am using

here's the code that I am using

```<code>import cv2
import pytesseract
import numpy as np

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# Load image, grayscale, Otsu's threshold
image = cv2.imread('Image1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Repair horizontal table lines
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,1))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)

# Remove horizontal lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (55,2))
detect_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), 9)

# Remove vertical lines
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,55))
detect_vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detect_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), 9)

# Perform OCR
data = pytesseract.image_to_string(image, lang='eng',config='--psm 6')
print(data)
</code>```

the result of this is

```<code>BC
est Result Flag Units Reference Interval
ite Blood Count 1.5L x 10-3/mL 4.0-10.5
‘ed Blood Count 3.50L x 10-6/mL 4.70-6.10
lemoglobin 10.8L g/dL 14.0-18.0
lematocrit 34.4L % 42.0-52.0
telets 302 x 10-3/mL 140-415
‘olys 23L % 45-76
ymphs 68H % 17-44
lonocytes 7 % 3-10
‘Os 2 % 0-4
> % 02
‘olys (absolute) 34L x 10-3/mL 18-7.8
ymphs (absolute) 1.0 x 10-3/mL 0.7-4.5
lonocytes (absolute) 0.1 x 10-3/mL 0.1-1.0
‘os (absolute) 0.1 x 10-3/mL 0.0-0.4
(absolute) 0.0 x 10-3/mL 0.0-0.2
</code>```

I want an even table Just like the image

Body:
The problem here is whenever I am trying to turn the image to CSV, I always have a problem with the words and spaces itself because they are not equal to turning this text into CSV directly. I used OpenCV and tesseract to make this process but something is missing, here's the Image I am using

here's the code that I am using

import cv2
import pytesseract
import numpy as np

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# Load image, grayscale, Otsu's threshold
image = cv2.imread('Image1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Repair horizontal table lines
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,1))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)

# Remove horizontal lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (55,2))
detect_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), 9)

# Remove vertical lines
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,55))
detect_vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detect_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), 9)

# Perform OCR
data = pytesseract.image_to_string(image, lang='eng',config='--psm 6')
print(data)

the result of this is

BC
est Result Flag Units Reference Interval
ite Blood Count 1.5L x 10-3/mL 4.0-10.5
‘ed Blood Count 3.50L x 10-6/mL 4.70-6.10
lemoglobin 10.8L g/dL 14.0-18.0
lematocrit 34.4L % 42.0-52.0
telets 302 x 10-3/mL 140-415
‘olys 23L % 45-76
ymphs 68H % 17-44
lonocytes 7 % 3-10
‘Os 2 % 0-4
> % 02
‘olys (absolute) 34L x 10-3/mL 18-7.8
ymphs (absolute) 1.0 x 10-3/mL 0.7-4.5
lonocytes (absolute) 0.1 x 10-3/mL 0.1-1.0
‘os (absolute) 0.1 x 10-3/mL 0.0-0.4
(absolute) 0.0 x 10-3/mL 0.0-0.2

I want an even table Just like the image


问:
PreSignUp failed with SyntaxError: Cannot use import statement outside a module in Cognito PreSignup Lambda
I am trying to create a new user with a Cognito PreSignup Lambda trigger, but I am getting the error PreSignUp failed with error SyntaxError: Cannot use import statement outside a module.

In the CloudWatch logs I see the following error message:

```<code>2022-12-25T21:39:04.238Z    undefined   ERROR   Uncaught Exception  {
    "errorType": "Runtime.UserCodeSyntaxError",
    "errorMessage": "SyntaxError: Cannot use import statement outside a module",
    "stack": [
        "Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module",
        "    at _loadUserApp (/var/runtime/UserFunction.js:222:13)",
        "    at Object.module.exports.load (/var/runtime/UserFunction.js:300:17)",
        "    at Object.<anonymous> (/var/runtime/index.js:43:34)",
        "    at Module._compile (internal/modules/cjs/loader.js:1085:14)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)",
        "    at Module.load (internal/modules/cjs/loader.js:950:32)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:790:12)",
        "    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)",
        "    at internal/main/run_main_module.js:17:47"
    ]
}
</code>```

I have tried adding 'type': 'module' in the package.json file, but that caused several additional errors such as 'Module not found: Error: Can't resolve './App' in …/'api/src' Did you mean 'App.js'?.

Below is my index.js file:

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css'
import { Amplify } from 'aws-amplify';
import config from './aws-exports';

Amplify.configure(config);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();
</code>```

How can I fix this error and successfully create a new user with my Cognito PreSignup Lambda trigger?

Body:
I am trying to create a new user with a Cognito PreSignup Lambda trigger, but I am getting the error PreSignUp failed with error SyntaxError: Cannot use import statement outside a module.

In the CloudWatch logs I see the following error message:

2022-12-25T21:39:04.238Z    undefined   ERROR   Uncaught Exception  {
    "errorType": "Runtime.UserCodeSyntaxError",
    "errorMessage": "SyntaxError: Cannot use import statement outside a module",
    "stack": [
        "Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module",
        "    at _loadUserApp (/var/runtime/UserFunction.js:222:13)",
        "    at Object.module.exports.load (/var/runtime/UserFunction.js:300:17)",
        "    at Object.<anonymous> (/var/runtime/index.js:43:34)",
        "    at Module._compile (internal/modules/cjs/loader.js:1085:14)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)",
        "    at Module.load (internal/modules/cjs/loader.js:950:32)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:790:12)",
        "    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)",
        "    at internal/main/run_main_module.js:17:47"
    ]
}

I have tried adding 'type': 'module' in the package.json file, but that caused several additional errors such as 'Module not found: Error: Can't resolve './App' in …/'api/src' Did you mean 'App.js'?.

Below is my index.js file:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css'
import { Amplify } from 'aws-amplify';
import config from './aws-exports';

Amplify.configure(config);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

How can I fix this error and successfully create a new user with my Cognito PreSignup Lambda trigger?


问:
How to use class variable from pyqt5 script in another python file
I have a simple pyqt5 script that makes the following UI:
UI

The python file for this code is named 'Test.py' and is as follows:

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 400)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(150, 90, 91, 31))
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(240, 100, 113, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(250, 150, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.function)       #<<<<<<<< MY INPUT

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "Job Number"))
        self.pushButton.setText(_translate("Form", "Press it"))

    def function(self):                                   #<<<<<<<< MY INPUT
        self.text = self.lineEdit.text()                   #<<<<<<<< MY INPUT
        return self.text                                    #<<<<<<<< MY INPUT

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
</code>```

I simply want to use the 'self.text' value that is generated on a different python file called 'Test1.py'.

I tried tried the following in the 'Test1.py' file:

```<code>from Test import Ui_Form

obj = Ui_Form()
obj.function()
</code>```

But I keep getting the following error:
AttributeError: 'Ui_Form' object has no attribute 'lineEdit'

Body:
I have a simple pyqt5 script that makes the following UI:
UI

The python file for this code is named 'Test.py' and is as follows:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 400)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(150, 90, 91, 31))
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(240, 100, 113, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(250, 150, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.function)       #<<<<<<<< MY INPUT

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "Job Number"))
        self.pushButton.setText(_translate("Form", "Press it"))

    def function(self):                                   #<<<<<<<< MY INPUT
        self.text = self.lineEdit.text()                   #<<<<<<<< MY INPUT
        return self.text                                    #<<<<<<<< MY INPUT

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

I simply want to use the 'self.text' value that is generated on a different python file called 'Test1.py'.

I tried tried the following in the 'Test1.py' file:

from Test import Ui_Form

obj = Ui_Form()
obj.function()

But I keep getting the following error:
AttributeError: 'Ui_Form' object has no attribute 'lineEdit'


问:
How to find out the accuracy of each class for BertForSequenceClassification model
I would like to know if there are methods in BERT that can show the accuracy for each individual class (car brand).

I use the BertForSequenceClassification model, which classifies cars by brand based on a short description. I managed to train the model itself and get the overall accuracy for all classes.


问:
SQL Server Always Encrypted with the JDBC not working
I'm working on an enterprise application and for some security reason I have to enable Always Encrypted. DBA and Production IT team did what needed from their side:

I can generate this script from using SQL server management studio under security -> always encrypted key

```<code>USE [DE_NAME]
/****** Object:  ColumnMasterKey [*****]    Script Date: 23/12/2022 17:30:17 ******/
CREATE COLUMN MASTER KEY [*****]
WITH
(
    KEY_STORE_PROVIDER_NAME = N'AZURE_KEY_VAULT',
    KEY_PATH = N'https://xxxxxxxxx.vault.azure.net/keys/******/####'
)
GO
</code>```

What mean that Alaways Encrypted is configured in the DB?

Production IT team :

Create Keyvault

Create a Service Principal/application Registration in Azure AD

register Name(clientId) and secret in KeyPass

At keyvault level added role Assignement

From my side, I added the conf as descripted in Microsoft documentation:

https://learn.microsoft.com/en-us/sql/connect/jdbc/using-always-encrypted-with-the-jdbc-driver?view=sql-server-ver16

Application inf :

Spring boot

Java 8

mssql diver : 9.2.1.jre8

I added mssql-jdbc_auth-9.2.1.x64.dll and sqljdbc_auth.dll to -Djava.library.path

Test code :

```<code> try (Connection sourceConnection = DriverManager.getConnection("jdbc:sqlserver://server;DatabaseName=db_name;encrypt=true;trustServerCertificate=true;integratedSecurity=true;columnEncryptionSetting=Enabled;keyVaultProviderClientId=xxxxxxxx-xxxx-xxxx-xxxx-xx71xx1axxd3;keyVaultProviderClientKey=XXX7X~XXXMv21mXqXxX4FBi7XoXmxxxXDSZXw")) {

    PreparedStatement stmt = sourceConnection.prepareStatement("INSERT INTO Table_name(id, aaa, bbb, ccc, ddd, eee) VALUES (?, ?, ?, ?, ?, ?)");

    stmt.setInt(1, 999999);
    stmt.setString(2, "local_test_0");
    stmt.setInt(3, 989898);
    stmt.setString(4, "local_test_0");
    stmt.setString(5, "local_test_0");
    stmt.setString(6, "local_test_0");//col encrypted

    stmt.executeUpdate();

} catch (SQLException e) {
    e.printStackTrace();
}
</code>```

When I run this code I get the following error message :

```<code>com.microsoft.sqlserver.jdbc.SQLServerException: Operand type clash: varchar(12) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK-XXXX-Shared-XX-XX', column_encryption_key_database_name = 'XXXX') collation_name = 'SQL_Latin1_General_CP1_CI_AS' is incompatible with nvarchar(132) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK-XXXX-Shared-XX-XX', column_encryption_key_database_name = 'XXXX')
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1632)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:602)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:524)
</code>```

It's like the driver didn't encrypt data before inserting it.

Could you help please ?

Body:
I'm working on an enterprise application and for some security reason I have to enable Always Encrypted. DBA and Production IT team did what needed from their side:

I can generate this script from using SQL server management studio under security -> always encrypted key

USE [DE_NAME]
/****** Object:  ColumnMasterKey [*****]    Script Date: 23/12/2022 17:30:17 ******/
CREATE COLUMN MASTER KEY [*****]
WITH
(
    KEY_STORE_PROVIDER_NAME = N'AZURE_KEY_VAULT',
    KEY_PATH = N'https://xxxxxxxxx.vault.azure.net/keys/******/####'
)
GO

What mean that Alaways Encrypted is configured in the DB?

Production IT team :

Create Keyvault

Create a Service Principal/application Registration in Azure AD

register Name(clientId) and secret in KeyPass

At keyvault level added role Assignement

From my side, I added the conf as descripted in Microsoft documentation:

https://learn.microsoft.com/en-us/sql/connect/jdbc/using-always-encrypted-with-the-jdbc-driver?view=sql-server-ver16

Application inf :

Spring boot

Java 8

mssql diver : 9.2.1.jre8

I added mssql-jdbc_auth-9.2.1.x64.dll and sqljdbc_auth.dll to -Djava.library.path

Test code :

 try (Connection sourceConnection = DriverManager.getConnection("jdbc:sqlserver://server;DatabaseName=db_name;encrypt=true;trustServerCertificate=true;integratedSecurity=true;columnEncryptionSetting=Enabled;keyVaultProviderClientId=xxxxxxxx-xxxx-xxxx-xxxx-xx71xx1axxd3;keyVaultProviderClientKey=XXX7X~XXXMv21mXqXxX4FBi7XoXmxxxXDSZXw")) {

    PreparedStatement stmt = sourceConnection.prepareStatement("INSERT INTO Table_name(id, aaa, bbb, ccc, ddd, eee) VALUES (?, ?, ?, ?, ?, ?)");

    stmt.setInt(1, 999999);
    stmt.setString(2, "local_test_0");
    stmt.setInt(3, 989898);
    stmt.setString(4, "local_test_0");
    stmt.setString(5, "local_test_0");
    stmt.setString(6, "local_test_0");//col encrypted

    stmt.executeUpdate();

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

When I run this code I get the following error message :

com.microsoft.sqlserver.jdbc.SQLServerException: Operand type clash: varchar(12) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK-XXXX-Shared-XX-XX', column_encryption_key_database_name = 'XXXX') collation_name = 'SQL_Latin1_General_CP1_CI_AS' is incompatible with nvarchar(132) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK-XXXX-Shared-XX-XX', column_encryption_key_database_name = 'XXXX')
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1632)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:602)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:524)

It's like the driver didn't encrypt data before inserting it.

Could you help please ?


问:
How can I pass dictionary data gotten from API request into iOS charts?
edit: I could get the keys and values separately like this. am I on the correct way ?

keys, values

how can i get these results in the console passed into my charts x(dates) and y axis(rates) ?

Console response

This is the func i get these results

```<code>func updateChart () {

    let date = Date()
    let endDate = formatter.string(from: date)
    let startDate = Calendar.current.date(byAdding: .day, value: -9, to: date)
    let startDatee = formatter.string(from: startDate ?? Date())
    print(endDate)
    print(startDatee)
    let result: () = currencyManager.fetchRatesForTimeframe(from: from, to: to, startDate: startDatee, endDate: endDate)
    print(result)
   }
</code>```

and this is my previously created and hardcoded charts

```<code>override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        lineChart.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 240)
        lineChart.center = view.center
        view.addSubview(lineChart)

       var entries = [ChartDataEntry]()

        for x in 0..<10 {

            entries.append(ChartDataEntry(x: Double(x), y: Double(x)))
        }

        let set = LineChartDataSet(entries: entries)

        set.colors = ChartColorTemplates.material()

        let data = LineChartData(dataSet: set)
        lineChart.data = data

</code>```

}

Body:
edit: I could get the keys and values separately like this. am I on the correct way ?

keys, values

how can i get these results in the console passed into my charts x(dates) and y axis(rates) ?

Console response

This is the func i get these results

func updateChart () {

    let date = Date()
    let endDate = formatter.string(from: date)
    let startDate = Calendar.current.date(byAdding: .day, value: -9, to: date)
    let startDatee = formatter.string(from: startDate ?? Date())
    print(endDate)
    print(startDatee)
    let result: () = currencyManager.fetchRatesForTimeframe(from: from, to: to, startDate: startDatee, endDate: endDate)
    print(result)
   }

and this is my previously created and hardcoded charts

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        lineChart.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 240)
        lineChart.center = view.center
        view.addSubview(lineChart)

       var entries = [ChartDataEntry]()

        for x in 0..<10 {

            entries.append(ChartDataEntry(x: Double(x), y: Double(x)))
        }

        let set = LineChartDataSet(entries: entries)

        set.colors = ChartColorTemplates.material()

        let data = LineChartData(dataSet: set)
        lineChart.data = data

}


问:
Why is my segmentation output appear as a boundary convolutional filter instead of an output mask
So I am building a neural network to look at medical CT images and try to create a segmentation mask of the heart within chest CT imaging. Ive trainied the neural network with a DICE score around 80%. The inputs and masks are all standardized and appropriate, but the output of my model appears to be making a mask that is able to create a silhoute of all soft tissue within the body, instead of just the heart alone. Does anyone know where I may be messing up?

Images:
Input Data ex.
Input Mask ex.

Prediction of model on an image that was used to train the model:
model.predict() output

Model code:

```<code>

def dense_unet_256(inputs, filters, depth):
#Model Creation

    # Define kwargs dictionary
    kwargs = {
        'kernel_size': (1, 3, 3),
        'padding': 'same',
        'bias_initializer': 'zeros'
    }

    # Define lambda functions#
    conv = lambda x, filters, strides: layers.Conv3D(filters=int(filters), strides=(1, strides, strides), **kwargs)(x)
    norm = lambda x: layers.BatchNormalization()(x)
    relu = lambda x: layers.LeakyReLU()(x)

    # Define stride-1, stride-2 blocks#
    conv1 = lambda filters, x: relu(norm(conv(x, filters, strides=1)))
    conv2 = lambda filters, x: relu(norm(conv(x, filters, strides=2)))

    # Define single transpose#
    tran = lambda x, filters, strides: layers.Conv3DTranspose(filters=int(filters), strides=(1, strides,strides),**kwargs)(x)

    # Define transpose block#
    tran2 = lambda filters, x: relu(norm(tran(x, filters, strides=2)))
    concat = lambda a, b: layers.Concatenate()([a, b])

    # Define Dense Block#
    def dense_block(filters, input, DB_depth):
        ext = 2 + DB_depth
        outside_layer = input
        for _ in range(0, int(ext)):
            inside_layer = conv1(filters, outside_layer)
            outside_layer = concat(outside_layer, inside_layer)
        return outside_layer

    def td_block(conv1_filters, conv2_filters, input, DB_depth):
        TD = conv1(conv1_filters, conv2(conv2_filters, input))
        DB = dense_block(conv1_filters, TD, DB_depth)
        return DB

    def tu_block(conv1_filters, tran2_filters, input, td_input, DB_depth):
        TU = conv1(conv1_filters, tran2(tran2_filters, input))
        C = concat(TU, td_input)
        DB = dense_block(conv1_filters, C, DB_depth)
        return DB

    TD1 = td_block(filters * 1, filters * 1, inputs, depth)
    TD2 = td_block(filters * 1.5, filters * 1, TD1, 1+depth)
    TD3 = td_block(filters * 2, filters * 1.5, TD2, 2+depth)
    TD4 = td_block(filters * 2.5, filters * 2, TD3, 3+depth)
    TD5 = td_block(filters * 3, filters * 2.5, TD4, 4+depth)

    TU1 = tu_block(filters * 2.5, filters * 3, TD5, TD4, 4+depth)
    TU2 = tu_block(filters * 2, filters * 2.5, TU1, TD3, 3+depth )
    TU3 = tu_block(filters * 1.5, filters * 2, TU2, TD2, 2+depth)
    TU4 = tu_block(filters * 1, filters * 1.5, TU3, TD1, 1+depth)
    TU5 = tran2(filters * 1, TU4)
    logits = {}
    logits['lbl'] = layers.Conv3D(filters=2, name = 'lbl', **kwargs)(TU5)
    model = Model(inputs=inputs, outputs=logits['lbl'])
    return model

</code>```

Ive tried training with different loss and metric functions without much change, I've confirmed that the image and masks going into training only identify the heart. I have done some hyperparamter tuning with epochs and learning rate, which with some tweaking have made the output mask of the heart a slightly different value when compared to chest wall tissue, but the ranges are not standardized between images so using a clip to create the mask wont work. I personally feel like it has something to do with the activation of the loaded model, but I am unsure exactly how to prove that. Any advice would be apprecaited!

Merry Christmas and Happy Holidays everyone!

Body:
So I am building a neural network to look at medical CT images and try to create a segmentation mask of the heart within chest CT imaging. Ive trainied the neural network with a DICE score around 80%. The inputs and masks are all standardized and appropriate, but the output of my model appears to be making a mask that is able to create a silhoute of all soft tissue within the body, instead of just the heart alone. Does anyone know where I may be messing up?

Images:
Input Data ex.
Input Mask ex.

Prediction of model on an image that was used to train the model:
model.predict() output

Model code:

def dense_unet_256(inputs, filters, depth):
#Model Creation

    # Define kwargs dictionary
    kwargs = {
        'kernel_size': (1, 3, 3),
        'padding': 'same',
        'bias_initializer': 'zeros'
    }

    # Define lambda functions#
    conv = lambda x, filters, strides: layers.Conv3D(filters=int(filters), strides=(1, strides, strides), **kwargs)(x)
    norm = lambda x: layers.BatchNormalization()(x)
    relu = lambda x: layers.LeakyReLU()(x)

    # Define stride-1, stride-2 blocks#
    conv1 = lambda filters, x: relu(norm(conv(x, filters, strides=1)))
    conv2 = lambda filters, x: relu(norm(conv(x, filters, strides=2)))

    # Define single transpose#
    tran = lambda x, filters, strides: layers.Conv3DTranspose(filters=int(filters), strides=(1, strides,strides),**kwargs)(x)

    # Define transpose block#
    tran2 = lambda filters, x: relu(norm(tran(x, filters, strides=2)))
    concat = lambda a, b: layers.Concatenate()([a, b])

    # Define Dense Block#
    def dense_block(filters, input, DB_depth):
        ext = 2 + DB_depth
        outside_layer = input
        for _ in range(0, int(ext)):
            inside_layer = conv1(filters, outside_layer)
            outside_layer = concat(outside_layer, inside_layer)
        return outside_layer

    def td_block(conv1_filters, conv2_filters, input, DB_depth):
        TD = conv1(conv1_filters, conv2(conv2_filters, input))
        DB = dense_block(conv1_filters, TD, DB_depth)
        return DB

    def tu_block(conv1_filters, tran2_filters, input, td_input, DB_depth):
        TU = conv1(conv1_filters, tran2(tran2_filters, input))
        C = concat(TU, td_input)
        DB = dense_block(conv1_filters, C, DB_depth)
        return DB

    TD1 = td_block(filters * 1, filters * 1, inputs, depth)
    TD2 = td_block(filters * 1.5, filters * 1, TD1, 1+depth)
    TD3 = td_block(filters * 2, filters * 1.5, TD2, 2+depth)
    TD4 = td_block(filters * 2.5, filters * 2, TD3, 3+depth)
    TD5 = td_block(filters * 3, filters * 2.5, TD4, 4+depth)

    TU1 = tu_block(filters * 2.5, filters * 3, TD5, TD4, 4+depth)
    TU2 = tu_block(filters * 2, filters * 2.5, TU1, TD3, 3+depth )
    TU3 = tu_block(filters * 1.5, filters * 2, TU2, TD2, 2+depth)
    TU4 = tu_block(filters * 1, filters * 1.5, TU3, TD1, 1+depth)
    TU5 = tran2(filters * 1, TU4)
    logits = {}
    logits['lbl'] = layers.Conv3D(filters=2, name = 'lbl', **kwargs)(TU5)
    model = Model(inputs=inputs, outputs=logits['lbl'])
    return model

Ive tried training with different loss and metric functions without much change, I've confirmed that the image and masks going into training only identify the heart. I have done some hyperparamter tuning with epochs and learning rate, which with some tweaking have made the output mask of the heart a slightly different value when compared to chest wall tissue, but the ranges are not standardized between images so using a clip to create the mask wont work. I personally feel like it has something to do with the activation of the loaded model, but I am unsure exactly how to prove that. Any advice would be apprecaited!

Merry Christmas and Happy Holidays everyone!


问:
Sierpinski triangle Christmas Cracker
`

```<code>import numpy as np
import math
import scipy
from matplotlib import pyplot as plt
import random

x_tri_points = [-20, 0, 20]
y_tri_points = [0, 40, 0]
numb = [0, 1, 2]
tri_vert_1 = [-20, 0]
tri_vert_2 = [0, 40]
tri_vert_3 = [20, 0]

random_num = random.randint(0, 2)

for i in numb:
    plt.plot(x_tri_points[i], y_tri_points[i], marker="o", markersize=2, markeredgecolor="red", markerfacecolor="green")
def sierpinski(n):
    x = (0, n, n)
    last_coord = [20, 0]
    for i in x:
        random_num = random.randint(0, 2)
        if random_num == 0:
            trans_vert = [((last_coord[0]-tri_vert_1[0])/2), ((last_coord[1]-tri_vert_1[1])/2)]
        elif random_num == 1:
            trans_vert = [((last_coord[0]-tri_vert_2[0])/2), ((last_coord[1]-tri_vert_2[1])/2)]
        elif random_num == 2:
            trans_vert = [((last_coord[0]-tri_vert_3[0])/2), ((last_coord[1]-tri_vert_3[1])/2)]
        plt.plot(trans_vert[0], trans_vert[1], marker="o", markersize=2, markeredgecolor="red", markerfacecolor="green")
        last_coord = trans_vert
sierpinski(100)
</code>```

`

I am trying to make a fairly simple, if very clumsy, loop to create a Sierpinski triangle effect. This idea is to pick one of the triangle's original three vertices and go half way between the last drawn point and the random point. Something is wrong and I'm not sure what, please could you take a look:

Title: Sierpinski triangle Christmas Cracker

Body:
`

import numpy as np
import math
import scipy
from matplotlib import pyplot as plt
import random

x_tri_points = [-20, 0, 20]
y_tri_points = [0, 40, 0]
numb = [0, 1, 2]
tri_vert_1 = [-20, 0]
tri_vert_2 = [0, 40]
tri_vert_3 = [20, 0]

random_num = random.randint(0, 2)

for i in numb:
    plt.plot(x_tri_points[i], y_tri_points[i], marker="o", markersize=2, markeredgecolor="red", markerfacecolor="green")
def sierpinski(n):
    x = (0, n, n)
    last_coord = [20, 0]
    for i in x:
        random_num = random.randint(0, 2)
        if random_num == 0:
            trans_vert = [((last_coord[0]-tri_vert_1[0])/2), ((last_coord[1]-tri_vert_1[1])/2)]
        elif random_num == 1:
            trans_vert = [((last_coord[0]-tri_vert_2[0])/2), ((last_coord[1]-tri_vert_2[1])/2)]
        elif random_num == 2:
            trans_vert = [((last_coord[0]-tri_vert_3[0])/2), ((last_coord[1]-tri_vert_3[1])/2)]
        plt.plot(trans_vert[0], trans_vert[1], marker="o", markersize=2, markeredgecolor="red", markerfacecolor="green")
        last_coord = trans_vert
sierpinski(100)

`

I am trying to make a fairly simple, if very clumsy, loop to create a Sierpinski triangle effect. This idea is to pick one of the triangle's original three vertices and go half way between the last drawn point and the random point. Something is wrong and I'm not sure what, please could you take a look:


问:
Retrieve data from the observer, to read from jetpack Datastore

I am trying to read a string saved with preference Datastore.  Data within the brackets (parametros.texto) is correct and properly shown in textviewTextoA, but shows empty in textviewTextoB outside the block.

```<code>preferenceManager.parameterTextoFlow.asLiveData().observe(this) {
    parametros.texto = it
    textviewTextoA.text = parametros.texto
}
textviewTextoB.text = parametros.texto
</code>```

Took me a while to isolate the problem and suspect this was a scope issue.

I have tried sending an object into the reading function and load up the results there but has not worked.

All I need is a way to extract the parametros.texto value from the block so it would show in textviewTextoB.text

Body:
I am trying to read a string saved with preference Datastore.  Data within the brackets (parametros.texto) is correct and properly shown in textviewTextoA, but shows empty in textviewTextoB outside the block.

preferenceManager.parameterTextoFlow.asLiveData().observe(this) {
    parametros.texto = it
    textviewTextoA.text = parametros.texto
}
textviewTextoB.text = parametros.texto

Took me a while to isolate the problem and suspect this was a scope issue.

I have tried sending an object into the reading function and load up the results there but has not worked.

All I need is a way to extract the parametros.texto value from the block so it would show in textviewTextoB.text


问:
Could not build wheels for repast4py, which is required to install pyproject.toml-based projects
I want to install repast4py in windows with pip. I enter the 'pip install repast4py' in cmd, but this error displays:Could not build wheels for repast4py, which is required to install pyproject.toml-based projects (Building wheel for repast4py (pyproject.toml) did not run successfull)

```<code>C:\Windows\system32>pip install repast4py
Collecting repast4py
  Using cached repast4py-1.0.5b1.tar.gz (79 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Collecting networkx>=2.6.2
  Using cached networkx-2.8.8-py3-none-any.whl (2.0 MB)
Requirement already satisfied: torch in c:\users\h.zibaei\appdata\local\programs\python\python310\lib\site-packages (from repast4py) (1.13.1)
Collecting numba
  Using cached numba-0.56.4-cp310-cp310-win_amd64.whl (2.5 MB)
Requirement already satisfied: mpi4py in c:\users\h.zibaei\appdata\local\programs\python\python310\lib\site-packages (from repast4py) (3.1.4)
Requirement already satisfied: numpy>=1.18.0 in c:\users\h.zibaei\appdata\local\programs\python\python310\lib\site-packages (from repast4py) (1.24.0)
Collecting pyyaml
  Using cached PyYAML-6.0-cp310-cp310-win_amd64.whl (151 kB)
Collecting Cython
  Using cached Cython-0.29.32-py2.py3-none-any.whl (986 kB)
Collecting numpy>=1.18.0
  Using cached numpy-1.23.5-cp310-cp310-win_amd64.whl (14.6 MB)
Requirement already satisfied: setuptools in c:\users\h.zibaei\appdata\local\programs\python\python310\lib\site-packages (from numba->repast4py) (65.6.3)
Collecting llvmlite<0.40,>=0.39.0dev0
  Using cached llvmlite-0.39.1-cp310-cp310-win_amd64.whl (23.2 MB)
Collecting typing_extensions
  Using cached typing_extensions-4.4.0-py3-none-any.whl (26 kB)
Building wheels for collected packages: repast4py
  Building wheel for repast4py (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for repast4py (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [21 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-310
      creating build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\context.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\core.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\geometry.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\logging.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\network.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\parameters.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\random.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\schedule.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\space.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\util.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\value_layer.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\__init__.py -> build\lib.win-amd64-cpython-310\repast4py
      running build_ext
      building 'repast4py._core' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for repast4py
Failed to build repast4py
ERROR: Could not build wheels for repast4py, which is required to install pyproject.toml-based projects
</code>```

thanks for answer

I install visual studio 2022, python 10.8

Body:
I want to install repast4py in windows with pip. I enter the 'pip install repast4py' in cmd, but this error displays:Could not build wheels for repast4py, which is required to install pyproject.toml-based projects (Building wheel for repast4py (pyproject.toml) did not run successfull)

C:\Windows\system32>pip install repast4py
Collecting repast4py
  Using cached repast4py-1.0.5b1.tar.gz (79 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Collecting networkx>=2.6.2
  Using cached networkx-2.8.8-py3-none-any.whl (2.0 MB)
Requirement already satisfied: torch in c:\users\h.zibaei\appdata\local\programs\python\python310\lib\site-packages (from repast4py) (1.13.1)
Collecting numba
  Using cached numba-0.56.4-cp310-cp310-win_amd64.whl (2.5 MB)
Requirement already satisfied: mpi4py in c:\users\h.zibaei\appdata\local\programs\python\python310\lib\site-packages (from repast4py) (3.1.4)
Requirement already satisfied: numpy>=1.18.0 in c:\users\h.zibaei\appdata\local\programs\python\python310\lib\site-packages (from repast4py) (1.24.0)
Collecting pyyaml
  Using cached PyYAML-6.0-cp310-cp310-win_amd64.whl (151 kB)
Collecting Cython
  Using cached Cython-0.29.32-py2.py3-none-any.whl (986 kB)
Collecting numpy>=1.18.0
  Using cached numpy-1.23.5-cp310-cp310-win_amd64.whl (14.6 MB)
Requirement already satisfied: setuptools in c:\users\h.zibaei\appdata\local\programs\python\python310\lib\site-packages (from numba->repast4py) (65.6.3)
Collecting llvmlite<0.40,>=0.39.0dev0
  Using cached llvmlite-0.39.1-cp310-cp310-win_amd64.whl (23.2 MB)
Collecting typing_extensions
  Using cached typing_extensions-4.4.0-py3-none-any.whl (26 kB)
Building wheels for collected packages: repast4py
  Building wheel for repast4py (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for repast4py (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [21 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-310
      creating build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\context.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\core.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\geometry.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\logging.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\network.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\parameters.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\random.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\schedule.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\space.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\util.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\value_layer.py -> build\lib.win-amd64-cpython-310\repast4py
      copying src\repast4py\__init__.py -> build\lib.win-amd64-cpython-310\repast4py
      running build_ext
      building 'repast4py._core' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for repast4py
Failed to build repast4py
ERROR: Could not build wheels for repast4py, which is required to install pyproject.toml-based projects

thanks for answer

I install visual studio 2022, python 10.8


问:
Creating a HLSL shader that simply flips X coordinate?
I am trying to find a mirror shader for MPC-HC. Would make old known videos feel slightly more fresh, as long as it doesn't have a lot of writing in it..

All I could find was FlipY.hlsl that flips the wrong coordinate (upside down) to be used for ceiling mounted projectors I guess. I am looking to modify this to flip the X coordinate instead but this code is unknown to me.

```<code>sampler s0 : register(s0);
float4 p0 : register(c0);
float4 p1 : register(c1);

#define width (p0[0])
#define height (p0[1])
#define counter (p0[2])
#define clock (p0[3])
#define one_over_width (p1[0])
#define one_over_height (p1[1])

float4 main(float2 tex : TEXCOORD0) : COLOR
{
  float2 pnt;
    pnt.x=tex.x;
    pnt.y=1.0-tex.y;
    float4 c0 = tex2D(s0, pnt);
    return c0;
}
</code>```

Please help me understand what to do here.

Body:
I am trying to find a mirror shader for MPC-HC. Would make old known videos feel slightly more fresh, as long as it doesn't have a lot of writing in it..

All I could find was FlipY.hlsl that flips the wrong coordinate (upside down) to be used for ceiling mounted projectors I guess. I am looking to modify this to flip the X coordinate instead but this code is unknown to me.

sampler s0 : register(s0);
float4 p0 : register(c0);
float4 p1 : register(c1);

#define width (p0[0])
#define height (p0[1])
#define counter (p0[2])
#define clock (p0[3])
#define one_over_width (p1[0])
#define one_over_height (p1[1])

float4 main(float2 tex : TEXCOORD0) : COLOR
{
  float2 pnt;
    pnt.x=tex.x;
    pnt.y=1.0-tex.y;
    float4 c0 = tex2D(s0, pnt);
    return c0;
}

Please help me understand what to do here.


问:
How do you mock a ContentResolver for Android 33?
I want to make sure that the below method only returns what it is supposed to by writing a test for it.

internal fun getMusicFromMediaStore(contentResolver: ContentResolver): List<MusicFile>
```
<p>The problem I am facing is that every thing I have found explaining how to do this so far is way out of date.</p>
<p>I start here in the official documentation for Android,
https://developer.android.com/training/testing/other-components/content-providers, and a note says "Note: This document focuses on ProviderTestCase2 which is being replaced by the experimental ProviderTestRule." That note links to this, https://developer.android.com/reference/androidx/test/rule/provider/ProviderTestRule, which says "This class is deprecated ... relies on deprecated android.test.mock. Consider using a real provider, or implementing a fake ContentProvider specific to your use case."</p>
<p>I ended up trying to use the provider provided by Mokito 4.1.0, but the code I wrote does not work correctly. This is how I populate the ContentResolver with entries.</p>
<pre class="lang-kotlin prettyprint-override"><code>    /**
     * Inserts music into the ContentResolver;
     * it is specifically the MediaStore's audio database that is populated.
     *
     * @param id The id of the row in the MediaStore.
     * @param displayName The display name row in the MediaStore.
     * @param isMusic True if the MediaStore entry is to be considered music.
     */
    private fun insert(id: Long, displayName: String, isMusic: Int) {
        val contentValues = ContentValues()
        contentValues.put(MediaStore.Audio.Media._ID, id)
        contentValues.put(MediaStore.Audio.Media.DISPLAY_NAME, displayName)
        contentValues.put(MediaStore.Audio.Media.IS_MUSIC, isMusic)
        val app = RuntimeEnvironment.getApplication()
        app.contentResolver.insert(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            contentValues
        )
    }
</code>```

It is supposed to return a non-empty cursor here, but it does not

            // The query parameters
            val projection = arrayOf(
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.DISPLAY_NAME,
                MediaStore.Audio.Media.IS_MUSIC
            )
            val selection = "${MediaStore.Audio.Media.IS_MUSIC} != ?"
            val selectionArgs = arrayOf("0")
            val sortOrder = "${MediaStore.Audio.Media.DISPLAY_NAME} ASC"

            // The cursor that is empty
            contentResolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                projection,
                selection,
                selectionArgs,
                sortOrder
            )
```

Body:
I want to make sure that the below method only returns what it is supposed to by writing a test for it.

internal fun getMusicFromMediaStore(contentResolver: ContentResolver): List<MusicFile>

The problem I am facing is that every thing I have found explaining how to do this so far is way out of date.

I start here in the official documentation for Android,
https://developer.android.com/training/testing/other-components/content-providers, and a note says "Note: This document focuses on ProviderTestCase2 which is being replaced by the experimental ProviderTestRule." That note links to this, https://developer.android.com/reference/androidx/test/rule/provider/ProviderTestRule, which says "This class is deprecated ... relies on deprecated android.test.mock. Consider using a real provider, or implementing a fake ContentProvider specific to your use case."

I ended up trying to use the provider provided by Mokito 4.1.0, but the code I wrote does not work correctly. This is how I populate the ContentResolver with entries.

    /**
     * Inserts music into the ContentResolver;
     * it is specifically the MediaStore's audio database that is populated.
     *
     * @param id The id of the row in the MediaStore.
     * @param displayName The display name row in the MediaStore.
     * @param isMusic True if the MediaStore entry is to be considered music.
     */
    private fun insert(id: Long, displayName: String, isMusic: Int) {
        val contentValues = ContentValues()
        contentValues.put(MediaStore.Audio.Media._ID, id)
        contentValues.put(MediaStore.Audio.Media.DISPLAY_NAME, displayName)
        contentValues.put(MediaStore.Audio.Media.IS_MUSIC, isMusic)
        val app = RuntimeEnvironment.getApplication()
        app.contentResolver.insert(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            contentValues
        )
    }

It is supposed to return a non-empty cursor here, but it does not

            // The query parameters
            val projection = arrayOf(
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.DISPLAY_NAME,
                MediaStore.Audio.Media.IS_MUSIC
            )
            val selection = "${MediaStore.Audio.Media.IS_MUSIC} != ?"
            val selectionArgs = arrayOf("0")
            val sortOrder = "${MediaStore.Audio.Media.DISPLAY_NAME} ASC"

            // The cursor that is empty
            contentResolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                projection,
                selection,
                selectionArgs,
                sortOrder
            )


问:
Using Python Social Auth with Flask-Login
https://python-social-auth.readthedocs.io/en/latest/configuration/flask.html says "The application works quite well with Flask-Login" however it does not specify what exactly is needed to be implemented and setup.

I used the code snippets from https://github.com/maxcountryman/flask-login to create a tiny PoC of Flask-Login. The user database is a simple dictionary here. It works fine.

# https://github.com/maxcountryman/flask-login
import flask
import flask_login

app = flask.Flask(__name__)
app.secret_key = 'throwaway97b1d9abffce3c5dbf1d3d79079166eede16ca098550'
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
users = {'foo@bar.tld': {'password': 'secret'}}

class User(flask_login.UserMixin):
    pass

@login_manager.user_loader
def user_loader(email):
    if email not in users:
        return

    user = User()
    user.id = email
    return user

@login_manager.request_loader
def request_loader(request):
    email = request.form.get('email')
    if email not in users:
        return

    user = User()
    user.id = email
    return user

@app.route('/login', methods=['GET', 'POST'])
def login():
    if flask.request.method == 'GET':
        return '''
<form action='login' method='POST'>
<input type='text' name='email' id='email' placeholder='email'/>
<input type='password' name='password' id='password' placeholder='password'/>
<input type='submit' name='submit'/>
</form>
'''
    email = flask.request.form['email']
    if email in users and flask.request.form['password'] == users[email]['password']:
        user = User()
        user.id = email
        flask_login.login_user(user)
        return flask.redirect(flask.url_for('protected'))

    return 'Bad login'

@app.route('/protected')
@flask_login.login_required
def protected():
    return 'Logged in as: ' + flask_login.current_user.id

@app.route('/logout')
def logout():
    flask_login.logout_user()
    return 'Logged out'

@login_manager.unauthorized_handler
def unauthorized_handler():
    return 'Unauthorized', 401
```

What do I need to change and add to be able to login to that Flask-Login using a authentication method from Python Social Auth, e. g. a properly set up Discourse forum? The goal would be accessing /protected and seeing information that was received from the serviced used via PSA to login.

Body:
https://python-social-auth.readthedocs.io/en/latest/configuration/flask.html says "The application works quite well with Flask-Login" however it does not specify what exactly is needed to be implemented and setup.

I used the code snippets from https://github.com/maxcountryman/flask-login to create a tiny PoC of Flask-Login. The user database is a simple dictionary here. It works fine.

# https://github.com/maxcountryman/flask-login
import flask
import flask_login

app = flask.Flask(__name__)
app.secret_key = 'throwaway97b1d9abffce3c5dbf1d3d79079166eede16ca098550'
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
users = {'foo@bar.tld': {'password': 'secret'}}

class User(flask_login.UserMixin):
    pass

@login_manager.user_loader
def user_loader(email):
    if email not in users:
        return

    user = User()
    user.id = email
    return user

@login_manager.request_loader
def request_loader(request):
    email = request.form.get('email')
    if email not in users:
        return

    user = User()
    user.id = email
    return user

@app.route('/login', methods=['GET', 'POST'])
def login():
    if flask.request.method == 'GET':
        return '''
<form action='login' method='POST'>
<input type='text' name='email' id='email' placeholder='email'/>
<input type='password' name='password' id='password' placeholder='password'/>
<input type='submit' name='submit'/>
</form>
'''
    email = flask.request.form['email']
    if email in users and flask.request.form['password'] == users[email]['password']:
        user = User()
        user.id = email
        flask_login.login_user(user)
        return flask.redirect(flask.url_for('protected'))

    return 'Bad login'

@app.route('/protected')
@flask_login.login_required
def protected():
    return 'Logged in as: ' + flask_login.current_user.id

@app.route('/logout')
def logout():
    flask_login.logout_user()
    return 'Logged out'

@login_manager.unauthorized_handler
def unauthorized_handler():
    return 'Unauthorized', 401

What do I need to change and add to be able to login to that Flask-Login using a authentication method from Python Social Auth, e. g. a properly set up Discourse forum? The goal would be accessing /protected and seeing information that was received from the serviced used via PSA to login.


问:
Add an object to a point cloud scene using Python?
Does anyone know a way to add a point cloud object (chair) to an existing point cloud scene (a bedroom with multiple objects) using Python or Matlab? I have some scenes and I want to add more objects to those scenes. The scenes are from SUN-RGBD data. Thank you.</p>


问:
Calling "Generate Forecast Metrics" No plan with planId[12345] exists
I call this API:

```<code>def main(client, customer_id, keyword_plan_id):
    keyword_plan_service = client.get_service("KeywordPlanService")
    resource_name = keyword_plan_service.keyword_plan_path(
        customer_id, keyword_plan_id
    )

    response = keyword_plan_service.generate_forecast_metrics(
        keyword_plan=resource_name
    )

    for i, forecast in enumerate(response.keyword_forecasts):
        print(f"#{i+1} Keyword ID: {forecast.keyword_plan_ad_group_keyword}")

        metrics = forecast.keyword_forecast

        click_val = metrics.clicks
        clicks = f"{click_val:.2f}" if click_val else "unspecified"
        print(f"Estimated total clicks: {clicks}")

        imp_val = metrics.impressions
        impressions = f"{imp_val:.2f}" if imp_val else "unspecified"
        print(f"Estimated total impressions: {impressions}")

        cpc_val = metrics.average_cpc
        cpc = f"{cpc_val:.2f}" if cpc_val else "unspecified"
        print(f"Estimated average cpc: {cpc}\n")

</code>```

Based on the UI:
https://ads.google.com/aw/budgetplanner/edit?ocid=1111111&planId=12345&returnTo=%2Faw%2Fperformance%3Focid%343423432

And get this error:

Request made: ClientCustomerId: None, Host: googleads.googleapis.com, Method: /google.ads.googleads.v11.services.KeywordPlanService/GenerateForecastMetrics, RequestId: ctjc0IYRWmhgSVs616rQ9Q, IsFault: True, FaultMessage: No plan with planId[12345] exists
Request with ID "ctjc0IYRWmhgSVs616rQ9Q" failed with status "INVALID_ARGUMENT" and includes the following errors:
Error with message "No plan with planId[12345] exists".

Why is a performance planner id doesn't work? It seems this is the only Generate Forecast Metrics way. Is it restricted to KW planner only?

Body:
I call this API:

def main(client, customer_id, keyword_plan_id):
    keyword_plan_service = client.get_service("KeywordPlanService")
    resource_name = keyword_plan_service.keyword_plan_path(
        customer_id, keyword_plan_id
    )

    response = keyword_plan_service.generate_forecast_metrics(
        keyword_plan=resource_name
    )

    for i, forecast in enumerate(response.keyword_forecasts):
        print(f"#{i+1} Keyword ID: {forecast.keyword_plan_ad_group_keyword}")

        metrics = forecast.keyword_forecast

        click_val = metrics.clicks
        clicks = f"{click_val:.2f}" if click_val else "unspecified"
        print(f"Estimated total clicks: {clicks}")

        imp_val = metrics.impressions
        impressions = f"{imp_val:.2f}" if imp_val else "unspecified"
        print(f"Estimated total impressions: {impressions}")

        cpc_val = metrics.average_cpc
        cpc = f"{cpc_val:.2f}" if cpc_val else "unspecified"
        print(f"Estimated average cpc: {cpc}\n")

Based on the UI:
https://ads.google.com/aw/budgetplanner/edit?ocid=1111111&planId=12345&returnTo=%2Faw%2Fperformance%3Focid%343423432

And get this error:

Request made: ClientCustomerId: None, Host: googleads.googleapis.com, Method: /google.ads.googleads.v11.services.KeywordPlanService/GenerateForecastMetrics, RequestId: ctjc0IYRWmhgSVs616rQ9Q, IsFault: True, FaultMessage: No plan with planId[12345] exists
Request with ID "ctjc0IYRWmhgSVs616rQ9Q" failed with status "INVALID_ARGUMENT" and includes the following errors:
Error with message "No plan with planId[12345] exists".

Why is a performance planner id doesn't work? It seems this is the only Generate Forecast Metrics way. Is it restricted to KW planner only?


问:
nginx reverse proxy always redirects including the port, how to remove
I am trying to redirect calls from 127.0.0.1:3001 to subdomain.example.com but I am unable to achieve this. It only works when I add port to the domain i specified. subdomain.example.com:3001 this works. How do I ignore the port.

Below  is my conf

```<code>upstream backend {
  server 127.0.0.1:3001;
}
server {
    listen 80;
    server_name subdomain.example.com;

    location / {
        proxy_pass http://backend/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forward-Proto http;
        proxy_set_header X-Nginx-Proxy true;

        proxy_redirect off;
    }
}
</code>```

This is hosts configuration at /etc/hosts

```<code>127.0.0.1  localhost
123.456.789.0  subdomain.example.com
</code>```

Is there anything that I am missing, I just couldn't figure out how to get the port to be ignored.

Body:
I am trying to redirect calls from 127.0.0.1:3001 to subdomain.example.com but I am unable to achieve this. It only works when I add port to the domain i specified. subdomain.example.com:3001 this works. How do I ignore the port.

Below  is my conf

upstream backend {
  server 127.0.0.1:3001;
}
server {
    listen 80;
    server_name subdomain.example.com;

    location / {
        proxy_pass http://backend/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forward-Proto http;
        proxy_set_header X-Nginx-Proxy true;

        proxy_redirect off;
    }
}

This is hosts configuration at /etc/hosts

127.0.0.1  localhost
123.456.789.0  subdomain.example.com

Is there anything that I am missing, I just couldn't figure out how to get the port to be ignored.


问:
Error in file(con, "w") : cannot open the connection [Cannot run sample R code from book]
I just installed R and RStudio, then ran the following sample code from a textbook:

# Install Packages
install.packages(fpp3)

# Load Packages
library(fpp3)

# Plot one time serices
aus_retail %>%
  filter(`Series ID` == 'A3349640L') %>%
  autoplot(Turnover)

# Produce some forecasts
aus_retail %>%
  filter(`Series ID` == 'A3349640L') %>%
  model(ETS(Turnover)) %>%
  forecast(h = '2 years')
```
<p>I get this error:</p>
<pre class="lang-r prettyprint-override"><code>Error in file(con, "w") : cannot open the connection
In addition: Warning message:
In file(con, "w") :
  cannot open file 'C:/Users/Cindy SC/OneDrive/Documents/.active-rstudio-document': No such file or directory
</code>```

When I do getwd() I get:

> getwd()
[1] "C:/Users/Cindy SC/Documents/R"
```

I have already looked through the following pages, but their solutions don't seem to be what I need (I could be wrong and misunderstand what I am looking at):
R: Error in file(con, "r") : cannot open the connection
Error in file(con, "w") : cannot open the connection [Using R-Studio to plot interactive bar graphs using rCharts, knitr]
Change temporary directory
Cannot run scripts in Rstudio

I also don't know why it is looking for active-rstudio-document.  It is not a file or folder I created and when I searched my computer for it, it didn't show up anywhere.

Any help would be greatly appreciated.  Thank you.

UPDATE:  I reread the advice on Change temporary directory and the second solution seems to have solved this issue...only to introduce another issue, but I won't present it here.  I did have to edit both an Rprofile and an Renviron file to make it work.

Body:
I just installed R and RStudio, then ran the following sample code from a textbook:

# Install Packages
install.packages(fpp3)

# Load Packages
library(fpp3)

# Plot one time serices
aus_retail %>%
  filter(`Series ID` == 'A3349640L') %>%
  autoplot(Turnover)

# Produce some forecasts
aus_retail %>%
  filter(`Series ID` == 'A3349640L') %>%
  model(ETS(Turnover)) %>%
  forecast(h = '2 years')

I get this error:

Error in file(con, "w") : cannot open the connection
In addition: Warning message:
In file(con, "w") :
  cannot open file 'C:/Users/Cindy SC/OneDrive/Documents/.active-rstudio-document': No such file or directory

When I do getwd() I get:

> getwd()
[1] "C:/Users/Cindy SC/Documents/R"

I have already looked through the following pages, but their solutions don't seem to be what I need (I could be wrong and misunderstand what I am looking at):
R: Error in file(con, "r") : cannot open the connection
Error in file(con, "w") : cannot open the connection [Using R-Studio to plot interactive bar graphs using rCharts, knitr]
Change temporary directory
Cannot run scripts in Rstudio

I also don't know why it is looking for active-rstudio-document.  It is not a file or folder I created and when I searched my computer for it, it didn't show up anywhere.

Any help would be greatly appreciated.  Thank you.

UPDATE:  I reread the advice on Change temporary directory and the second solution seems to have solved this issue...only to introduce another issue, but I won't present it here.  I did have to edit both an Rprofile and an Renviron file to make it work.


问:
Is there any automatic way to solve it? "unrecognized module type"
so, I've been trying to compile CafeX for some time, however, it always gives me an error, and when I finished fixing an error and went to test it again to see if it worked, it presented me with +20 identical errors, "xx/yy/zz/Android.bp:xx:x unrecognized module type"
and before I try to remove one by one, I would like to know if there is a more automatic way to do this, so as not to waste time

I tried to compile the CafeX system for my device, I hoped I didn't get any errors


问:
how to solve for "raise ValueError("Cannot convert {0!r} to Excel".format(value))"
I'm trying to create a script that references an excel spreadsheet for IP addresses, checks their DNS and write the results into another spreadsheet.

`

```<code>import openpyxl
import socket

wb = openpyxl.load_workbook('/Documents/ip_addresses.xlsx')

sheet = wb.worksheets[0]
for i, row in enumerate(sheet.iter_rows(min_row=2)):
 cell = row[0]

 try:
     ptr_record = socket.gethostbyaddr(cell.value)
 except socket.herror:
     sheet.cell(row=i+2, column=2).value = 'No PTR record found'
     continue

 sheet.cell(row=i+2, column=2).value = ptr_record
wb.save('/Documents/ip_addresses_results.xlsx')
</code>```

`

however, I can't seem to get around this error

`

```<code>Traceback (most recent call last):
  File "/Documents/script.py", line 18, in <module>
    sheet.cell(row=i+2, column=2).value = ptr_record
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/openpyxl/cell/cell.py", line 215, in value
    self._bind_value(value)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/openpyxl/cell/cell.py", line 184, in _bind_value
    raise ValueError("Cannot convert {0!r} to Excel".format(value))
</code>```

`

I think it's because openpyxl cannot convert the value of the result into the excel cell (perhaps it's too long, or because it contains periods (.) in the value), but I don't know how to fix it.

Body:
I'm trying to create a script that references an excel spreadsheet for IP addresses, checks their DNS and write the results into another spreadsheet.

`

import openpyxl
import socket

wb = openpyxl.load_workbook('/Documents/ip_addresses.xlsx')

sheet = wb.worksheets[0]
for i, row in enumerate(sheet.iter_rows(min_row=2)):
 cell = row[0]

 try:
     ptr_record = socket.gethostbyaddr(cell.value)
 except socket.herror:
     sheet.cell(row=i+2, column=2).value = 'No PTR record found'
     continue

 sheet.cell(row=i+2, column=2).value = ptr_record
wb.save('/Documents/ip_addresses_results.xlsx')

`

however, I can't seem to get around this error

`

Traceback (most recent call last):
  File "/Documents/script.py", line 18, in <module>
    sheet.cell(row=i+2, column=2).value = ptr_record
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/openpyxl/cell/cell.py", line 215, in value
    self._bind_value(value)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/openpyxl/cell/cell.py", line 184, in _bind_value
    raise ValueError("Cannot convert {0!r} to Excel".format(value))

`

I think it's because openpyxl cannot convert the value of the result into the excel cell (perhaps it's too long, or because it contains periods (.) in the value), but I don't know how to fix it.


问:
Apache James Log4j2 duplicate appender definitions
After configuring Apache James 3.7.2 with spring wiring, I noticed that the log4j2 xml configuration file defines the MAILETCONTAINER appender 4 times.

https://github.com/apache/james-project/blob/3.7.x/server/apps/spring-app/src/main/resources/log4j2.xml

```<code><RollingFile name="MAILETCONTAINER" fileName="${logDir}/james_mailetcontainer.log"
<RollingFile name="MAILETCONTAINER" fileName="${logDir}/james_mailetcontainer.log"
<RollingFile name="MAILETCONTAINER" fileName="${logDir}/james_mailetcontainer.log"
<RollingFile name="MAILETCONTAINER" fileName="${logDir}/james_mailetcontainer.log"
</code>```
```<code><Logger name="org.apache.james.mailetcontainer" additivity="false">
<Logger name="org.apache.james.mailetcontainer" additivity="false">
<Logger name="org.apache.james.mailetcontainer" additivity="false">
<Logger name="org.apache.james.mailetcontainer" additivity="false">
</code>```

Is this simply a misconfiguration?

I have deleted the duplicate entries on my local server and the logging behaviour appears to not have been adversely affected.

Body:
After configuring Apache James 3.7.2 with spring wiring, I noticed that the log4j2 xml configuration file defines the MAILETCONTAINER appender 4 times.

https://github.com/apache/james-project/blob/3.7.x/server/apps/spring-app/src/main/resources/log4j2.xml

<RollingFile name="MAILETCONTAINER" fileName="${logDir}/james_mailetcontainer.log"
<RollingFile name="MAILETCONTAINER" fileName="${logDir}/james_mailetcontainer.log"
<RollingFile name="MAILETCONTAINER" fileName="${logDir}/james_mailetcontainer.log"
<RollingFile name="MAILETCONTAINER" fileName="${logDir}/james_mailetcontainer.log"

<Logger name="org.apache.james.mailetcontainer" additivity="false">
<Logger name="org.apache.james.mailetcontainer" additivity="false">
<Logger name="org.apache.james.mailetcontainer" additivity="false">
<Logger name="org.apache.james.mailetcontainer" additivity="false">

Is this simply a misconfiguration?

I have deleted the duplicate entries on my local server and the logging behaviour appears to not have been adversely affected.


问:
pytorch-lightning example throws assertion error
I'm using the following code out of the box from this url: https://lightning-transformers.readthedocs.io/en/latest/tasks/nlp/question_answering.html

```<code>import pytorch_lightning as pl
from transformers import AutoTokenizer

from lightning_transformers.task.nlp.question_answering import (
    QuestionAnsweringTransformer,
    SquadDataModule,
)

tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path="bert-base-uncased")
model = QuestionAnsweringTransformer(pretrained_model_name_or_path="bert-base-uncased")
dm = SquadDataModule(
    batch_size=1,
    dataset_config_name="plain_text",
    max_length=384,
    version_2_with_negative=False,
    null_score_diff_threshold=0.0,
    doc_stride=128,
    n_best_size=20,
    max_answer_length=30,
    tokenizer=tokenizer,
)
trainer = pl.Trainer(accelerator="auto", devices="auto", max_epochs=1)

trainer.fit(model, dm)
</code>```

which throws this error

```<code>AssertionError                            Traceback (most recent call last)
<ipython-input-2-0b608c02a52e> in <module>
     14 trainer = pl.Trainer(accelerator="auto", devices="auto", max_epochs=1)
     15
---> 16 trainer.fit(model, dm)

16 frames
/usr/local/lib/python3.8/dist-packages/lightning_transformers/task/nlp/question_answering/datasets/squad/processing.py in postprocess_qa_predictions(examples, features, predictions, version_2_with_negative, n_best_size, max_answer_length, null_score_diff_threshold, output_dir, prefix)
    245     all_start_logits, all_end_logits, example_ids = predictions
    246
--> 247     assert len(predictions[0]) == len(features), f"Got {len(predictions[0])} predictions and {len(features)} features."
    248
    249     # Build a map example to its corresponding features.

AssertionError: Got 2 predictions and 10784 features.
</code>```

I was simply trying to get a single example from the documentation to run within google colab before investigating further if this would meet my use case, but I see an error when I try to use the example as is, which is disheartening to consider investigating it.  Nothing comes up when I google "AssertionError: Got 2 predictions and 10784 features."

Body:
I'm using the following code out of the box from this url: https://lightning-transformers.readthedocs.io/en/latest/tasks/nlp/question_answering.html

import pytorch_lightning as pl
from transformers import AutoTokenizer

from lightning_transformers.task.nlp.question_answering import (
    QuestionAnsweringTransformer,
    SquadDataModule,
)

tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path="bert-base-uncased")
model = QuestionAnsweringTransformer(pretrained_model_name_or_path="bert-base-uncased")
dm = SquadDataModule(
    batch_size=1,
    dataset_config_name="plain_text",
    max_length=384,
    version_2_with_negative=False,
    null_score_diff_threshold=0.0,
    doc_stride=128,
    n_best_size=20,
    max_answer_length=30,
    tokenizer=tokenizer,
)
trainer = pl.Trainer(accelerator="auto", devices="auto", max_epochs=1)

trainer.fit(model, dm)

which throws this error

AssertionError                            Traceback (most recent call last)
<ipython-input-2-0b608c02a52e> in <module>
     14 trainer = pl.Trainer(accelerator="auto", devices="auto", max_epochs=1)
     15
---> 16 trainer.fit(model, dm)

16 frames
/usr/local/lib/python3.8/dist-packages/lightning_transformers/task/nlp/question_answering/datasets/squad/processing.py in postprocess_qa_predictions(examples, features, predictions, version_2_with_negative, n_best_size, max_answer_length, null_score_diff_threshold, output_dir, prefix)
    245     all_start_logits, all_end_logits, example_ids = predictions
    246
--> 247     assert len(predictions[0]) == len(features), f"Got {len(predictions[0])} predictions and {len(features)} features."
    248
    249     # Build a map example to its corresponding features.

AssertionError: Got 2 predictions and 10784 features.

I was simply trying to get a single example from the documentation to run within google colab before investigating further if this would meet my use case, but I see an error when I try to use the example as is, which is disheartening to consider investigating it.  Nothing comes up when I google "AssertionError: Got 2 predictions and 10784 features."


问:
New to Combine; dataTaskPublisher doesn't seem to execute
I am fairly inexperienced with Combine, so I could be making a simple mistake in the following code.  For some reason, it seems that the dataTaskPublisher isn't even executing.  Could someone tell me why?

```<code>import Foundation
import Combine

enum GitHubAPIError: Error, LocalizedError {
    case urlError(URLError)
    case responseError(Int)
    case decodingError(DecodingError)
    case genericError

    var localizedDescription: String {
        switch self {
            case .urlError(let error):
            return error.localizedDescription
            case .decodingError(let error):
            return error.localizedDescription
            case .responseError(let status):
            return "Bad response code: \(status)"
            case .genericError:
            return "An unknown error has occurred"
        }
    }
}

struct User: Codable {
    let login: String
    let url: String
}

private var vmCancellable = Set<AnyCancellable>()

class NetworkManager {

    static let shared = NetworkManager()
    private let urlSession = URLSession.shared
    private let jsonDecoder = JSONDecoder()
    var dataTaskPublisherSubscription: AnyCancellable?
    private init() {}

    private let baseURL = "https://api.github.com"

    func fetchFollowers(for userID: String) -> Future<[User], GitHubAPIError> {
        print(" In NetworkManager -> fetchFollowers(for: \(userID))")
        return Future<[User], GitHubAPIError> {[unowned self] promise in
            guard let url = URL(string: self.baseURL + "/users/" + userID + "/followers") else {
                return promise(.failure(.urlError(URLError(URLError.unsupportedURL))))
            }
            print(" In NetworkManager -> fetchFollowers -> URL is \(url.absoluteString)")

            dataTaskPublisherSubscription = urlSession.dataTaskPublisher(for: url)
                .print()
                .tryMap { (data, response) -> Data in
                    print(" In NetworkManager -> fetchFollowers -> dataTaskPublisher -> inside try map")
                    guard let httpResponse = response as? HTTPURLResponse, 200...299 ~= httpResponse.statusCode else {
                        if let httpResponse = response as? HTTPURLResponse {
                            print(" In NetworkManager -> fetchFollowers -> dataTaskPublisher -> inside try map -> throwing an error  -> status code: \(httpResponse.statusCode)")
                        }
                        throw GitHubAPIError.responseError((response as? HTTPURLResponse)?.statusCode ?? 500)
                    }
                    print(" In NetworkManager -> fetchFollowers -> dataTaskPublisher -> inside try map -> data received")

                    return data
                }
                .decode(type: User.self, decoder: jsonDecoder)
                .receive(on: RunLoop.main)
                .sink(receiveCompletion: { (completion) in
                    print(" In NetworkManager -> fetchFollowers -> dataTaskPublisher -> inside sink receive completion...")
                    if case let .failure(error) = completion {
                        switch error {
                            case let urlError as URLError:
                            promise(.failure(.urlError(urlError)))
                            case let decodingError as DecodingError:
                            promise(.failure(.decodingError(decodingError)))
                            case let apiError as GitHubAPIError:
                            promise(.failure(apiError))
                            default:
                            promise(.failure(.genericError))
                        }
                    }
                }, receiveValue: {
                    promise(.success([$0]))
                    self.dataTaskPublisherSubscription?.cancel()
                })
        }
    }
}

class SearchUserViewModel {
    let networkManagerInstance = NetworkManager.shared
    var followers: [User] = []

    func fetchFollowers(for userID: String) {
        print(" In SearchUserViewModel -> fetchFollowers(for: \(userID))")
        networkManagerInstance.fetchFollowers(for: userID)
            .print()
            .sink { completion in
                print(" In SearchUserViewModel -> sink completion...")
                switch completion {
                    case .failure(let err):
                    print(" In SearchUserViewModel -> case failure -> Error is \(err.localizedDescription)")
                    case .finished:
                    print(" In SearchUserViewModel -> case finished -> Finished")
                }
            }
            receiveValue: { [weak self] followers in
                print(" In SearchUserViewModel -> receiveValue completion")
                self?.followers = followers
                print(" In SearchUserViewModel -> receiveValue completion -> self?.followers contains \(self?.followers.count ?? 0) followers")
            }
        .store(in: &vmCancellable)

        sleep(1)
    }

}

let vm = SearchUserViewModel()
vm.fetchFollowers(for: "sallen0400A")
</code>```

All I ever see in the console is that it's printing out the URL, such as:
 URL is https://api.github.com/users/sallen0400/followers

However, nothing happens after that.

As a side note, I'm keeping a reference to the URLSession in the NetworkManager as I was under the impression that the cause of this issue might be that the session is going out of scope.  But, this solution doesn't seem to be valid.

It seems that only when I added a 1 second sleep in the SearchUserViewModel's fetchFollowers method, then it works.  But I don't get why.  Something is being deallocated prematurely, but I'm not sure how to tell what that is.

Why?

Body:
I am fairly inexperienced with Combine, so I could be making a simple mistake in the following code.  For some reason, it seems that the dataTaskPublisher isn't even executing.  Could someone tell me why?

import Foundation
import Combine

enum GitHubAPIError: Error, LocalizedError {
    case urlError(URLError)
    case responseError(Int)
    case decodingError(DecodingError)
    case genericError

    var localizedDescription: String {
        switch self {
            case .urlError(let error):
            return error.localizedDescription
            case .decodingError(let error):
            return error.localizedDescription
            case .responseError(let status):
            return "Bad response code: \(status)"
            case .genericError:
            return "An unknown error has occurred"
        }
    }
}

struct User: Codable {
    let login: String
    let url: String
}

private var vmCancellable = Set<AnyCancellable>()

class NetworkManager {

    static let shared = NetworkManager()
    private let urlSession = URLSession.shared
    private let jsonDecoder = JSONDecoder()
    var dataTaskPublisherSubscription: AnyCancellable?
    private init() {}

    private let baseURL = "https://api.github.com"

    func fetchFollowers(for userID: String) -> Future<[User], GitHubAPIError> {
        print(" In NetworkManager -> fetchFollowers(for: \(userID))")
        return Future<[User], GitHubAPIError> {[unowned self] promise in
            guard let url = URL(string: self.baseURL + "/users/" + userID + "/followers") else {
                return promise(.failure(.urlError(URLError(URLError.unsupportedURL))))
            }
            print(" In NetworkManager -> fetchFollowers -> URL is \(url.absoluteString)")

            dataTaskPublisherSubscription = urlSession.dataTaskPublisher(for: url)
                .print()
                .tryMap { (data, response) -> Data in
                    print(" In NetworkManager -> fetchFollowers -> dataTaskPublisher -> inside try map")
                    guard let httpResponse = response as? HTTPURLResponse, 200...299 ~= httpResponse.statusCode else {
                        if let httpResponse = response as? HTTPURLResponse {
                            print(" In NetworkManager -> fetchFollowers -> dataTaskPublisher -> inside try map -> throwing an error  -> status code: \(httpResponse.statusCode)")
                        }
                        throw GitHubAPIError.responseError((response as? HTTPURLResponse)?.statusCode ?? 500)
                    }
                    print(" In NetworkManager -> fetchFollowers -> dataTaskPublisher -> inside try map -> data received")

                    return data
                }
                .decode(type: User.self, decoder: jsonDecoder)
                .receive(on: RunLoop.main)
                .sink(receiveCompletion: { (completion) in
                    print(" In NetworkManager -> fetchFollowers -> dataTaskPublisher -> inside sink receive completion...")
                    if case let .failure(error) = completion {
                        switch error {
                            case let urlError as URLError:
                            promise(.failure(.urlError(urlError)))
                            case let decodingError as DecodingError:
                            promise(.failure(.decodingError(decodingError)))
                            case let apiError as GitHubAPIError:
                            promise(.failure(apiError))
                            default:
                            promise(.failure(.genericError))
                        }
                    }
                }, receiveValue: {
                    promise(.success([$0]))
                    self.dataTaskPublisherSubscription?.cancel()
                })
        }
    }
}

class SearchUserViewModel {
    let networkManagerInstance = NetworkManager.shared
    var followers: [User] = []

    func fetchFollowers(for userID: String) {
        print(" In SearchUserViewModel -> fetchFollowers(for: \(userID))")
        networkManagerInstance.fetchFollowers(for: userID)
            .print()
            .sink { completion in
                print(" In SearchUserViewModel -> sink completion...")
                switch completion {
                    case .failure(let err):
                    print(" In SearchUserViewModel -> case failure -> Error is \(err.localizedDescription)")
                    case .finished:
                    print(" In SearchUserViewModel -> case finished -> Finished")
                }
            }
            receiveValue: { [weak self] followers in
                print(" In SearchUserViewModel -> receiveValue completion")
                self?.followers = followers
                print(" In SearchUserViewModel -> receiveValue completion -> self?.followers contains \(self?.followers.count ?? 0) followers")
            }
        .store(in: &vmCancellable)

        sleep(1)
    }

}

let vm = SearchUserViewModel()
vm.fetchFollowers(for: "sallen0400A")

All I ever see in the console is that it's printing out the URL, such as:
 URL is https://api.github.com/users/sallen0400/followers

However, nothing happens after that.

As a side note, I'm keeping a reference to the URLSession in the NetworkManager as I was under the impression that the cause of this issue might be that the session is going out of scope.  But, this solution doesn't seem to be valid.

It seems that only when I added a 1 second sleep in the SearchUserViewModel's fetchFollowers method, then it works.  But I don't get why.  Something is being deallocated prematurely, but I'm not sure how to tell what that is.

Why?


问:
how do i check inputs during sleep?
im a c++ beginner and im trying to make a flappy game out of scratch, im doing good but don't know how to check input during the sleep function from window.h

```<code>while (GameStarted) {
        std::cin >> answer;
        Sleep(DurationOfATick);
        system("CLS");
        if (answer.size() != 1) {
            Player.SetPosition(Player.GetPosition().x, Player.GetPosition().y - 1);
        }
        else {
            Player.SetPosition(Player.GetPosition().x, Player.GetPosition().y + 1);
        }
        DrawFrame(Player, YPositionDrawn);
        TicksCounted++;
        std::cout << "Tick!" << TicksCounted << '\n';
    }
</code>```

I tried to add a std::cin << answer but for some reason it paused until it had a input, any help??

Title: how do i check inputs during sleep?

Body:
im a c++ beginner and im trying to make a flappy game out of scratch, im doing good but don't know how to check input during the sleep function from window.h

while (GameStarted) {
        std::cin >> answer;
        Sleep(DurationOfATick);
        system("CLS");
        if (answer.size() != 1) {
            Player.SetPosition(Player.GetPosition().x, Player.GetPosition().y - 1);
        }
        else {
            Player.SetPosition(Player.GetPosition().x, Player.GetPosition().y + 1);
        }
        DrawFrame(Player, YPositionDrawn);
        TicksCounted++;
        std::cout << "Tick!" << TicksCounted << '\n';
    }

I tried to add a std::cin << answer but for some reason it paused until it had a input, any help??