问:
Why doesn't the snippet of show/hide password work for me in nasa-login-register-form
I generated a snippet so that I can add the show password feature to my login form. It turns out that when I use it on the my-account page it works perfectly. But when I try to use it the same way in the login modal, the code breaks and ends up rendering the content at the bottom of the page, even below the footer.

The snippet I have created show hidden password mode by default and switch to plain text mode (so you can see it) as soon as you click on an  tag:

```<code>add_action( 'show_pass', function () { ?>
<script>
    let password = document.getElementById('password');
    let viewPassword = document.getElementById('viewPassword');
    let click = false;

    viewPassword.addEventListener('click', (e)=>{
      if(!click){
        password.type = 'text'
        click = true
      }else if(click){
        password.type = 'password'
        click = false
      }
    })
</script>
<?php } );
</code>```

The do_action is executed when the "show password"  tag is clicked. This part of the code is executed in the template: woocommerce/myaccount/form-login.
The code where it is implemented CORRECTLY is this:

```<code>    <p class="form-row form-row-wide">
                <span>
                    <label for="<?php echo esc_attr($nasa_keyPass); ?>" class="inline-block left rtl-right">
                        <?php esc_html_e('Password', 'elessi-theme'); ?> <span class="required">*</span>
                    </label>
                    <a class="lost_password inline-block right rtl-left" href="<?php echo esc_url(wc_lostpassword_url()); ?>"><?php esc_html_e('Lost?', 'elessi-theme'); ?></a>
                </span>

                <input class="woocommerce-Input woocommerce-Input--text input-text" type="password" name="<?php echo esc_attr($nasa_keyPass); ?>" id="<?php echo esc_attr($nasa_keyPass); ?>" autocomplete="current-password" />
                <div class="show-pass">
                  <a id="viewPassword" style="display: flex; justify-content: end; text-decoration: underline; margin-top: -10px; margin-bottom: -20px;">**<?php do_action('show_pass'); ?>**Mostrar contraseña</a>
                </div>
            </p>
</code>```

And this is where the do_action implementation isn't working. It is in the nasa-login-register-form template and what happens is that when one adds the php code in the same place as the other form, not only does it not work as such, but it also breaks the modal and renders only up to the password input part. The rest of the form that is not rendered is later found at the bottom of the web page, even below the footer.

The code where it is implemented and is not working is this:

```<code><p class="form-row form-row-wide">
                <span>
                    <label for="<?php echo esc_attr($nasa_keyPass); ?>" class="inline-block left rtl-right">
                        <?php esc_html_e('Password', 'elessi-theme'); ?> <span class="required">*</span>
                    </label>
                    <a class="lost_password inline-block right rtl-left" href="<?php echo esc_url(wc_lostpassword_url()); ?>"><?php esc_html_e('Lost?', 'elessi-theme'); ?></a>
                </span>

                <input class="woocommerce-Input woocommerce-Input--text input-text" type="password" name="<?php echo esc_attr($nasa_keyPass); ?>" id="<?php echo esc_attr($nasa_keyPass); ?>" autocomplete="current-password" />
                <a id="viewPassword" class="inline-block right rtl-left" style="margin-top: -10px; margin-bottom: 10px">**<?php do_action('show_pass'); ?>**Mostrar contrase単a</a>
            </p>
</code>```

I hope you can instruct me on what part is failing and why the code breaks when the do_action is located in the same place.

Body:
I generated a snippet so that I can add the show password feature to my login form. It turns out that when I use it on the my-account page it works perfectly. But when I try to use it the same way in the login modal, the code breaks and ends up rendering the content at the bottom of the page, even below the footer.

The snippet I have created show hidden password mode by default and switch to plain text mode (so you can see it) as soon as you click on an  tag:

add_action( 'show_pass', function () { ?>

<?php } );

The do_action is executed when the "show password"  tag is clicked. This part of the code is executed in the template: woocommerce/myaccount/form-login.
The code where it is implemented CORRECTLY is this:

                    <label for="<?php echo esc_attr($nasa_keyPass); ?>" class="inline-block left rtl-right">
                        <?php esc_html_e('Password', 'elessi-theme'); ?> *

                    <a class="lost_password inline-block right rtl-left" href="<?php echo esc_url(wc_lostpassword_url()); ?>"><?php esc_html_e('Lost?', 'elessi-theme'); ?>

                <input class="woocommerce-Input woocommerce-Input--text input-text" type="password" name="<?php echo esc_attr($nasa_keyPass); ?>" id="<?php echo esc_attr($nasa_keyPass); ?>" autocomplete="current-password" />

                  **<?php do_action('show_pass'); ?>**Mostrar contraseña

And this is where the do_action implementation isn't working. It is in the nasa-login-register-form template and what happens is that when one adds the php code in the same place as the other form, not only does it not work as such, but it also breaks the modal and renders only up to the password input part. The rest of the form that is not rendered is later found at the bottom of the web page, even below the footer.

The code where it is implemented and is not working is this:

                    <label for="<?php echo esc_attr($nasa_keyPass); ?>" class="inline-block left rtl-right">
                        <?php esc_html_e('Password', 'elessi-theme'); ?> *

                    <a class="lost_password inline-block right rtl-left" href="<?php echo esc_url(wc_lostpassword_url()); ?>"><?php esc_html_e('Lost?', 'elessi-theme'); ?>

                <input class="woocommerce-Input woocommerce-Input--text input-text" type="password" name="<?php echo esc_attr($nasa_keyPass); ?>" id="<?php echo esc_attr($nasa_keyPass); ?>" autocomplete="current-password" />
                **<?php do_action('show_pass'); ?>**Mostrar contrase単a

I hope you can instruct me on what part is failing and why the code breaks when the do_action is located in the same place.


来源: stackexchange

问:
Basic Android OS on low end smart watch to transfer information using Bluetooth
Is there a way to purchase a low end smart watch, replace the os with android (not Wear OS) and develop a custom app for it? It is a single purpose device, so I don't need any of the extras that come with Wear OS, but I need much longer battery life and ability to pair w/multiple phones (not simultaneous connection, but quick switching). I need to pair the phone using bluetooth, connect to it from an app (either Android or iOS), send an image/text, initiate a vibration, and send back an ack, with info. Ideally send heart rate as well.

I'm really not sure how to get started. I know how to develop apps in android studio and Wear OS as well, but it's taking me a long time to figure this out and I was hoping somebody might have done it before.

This seemed promising, but it wasn't the exact use case. It would even be great to test on some non smart watch android device or board.

ContentLicense: CC BY-SA 4.0


问:
What i need to do for fix problem in result code?
```<code>#include <math.h>
#include <stdio.h>

float Fact(int x) {
    if (x == 1 || x == 0)
        return 1;
    else
        return x * Fact(x - 1);
}

int main() {
    float c;
    float d;
    float y;
    for(int n = 0; n < 10; n++) {
        c = 3 * (pow(n, n));
        y = Fact(n);
        d = y / c;
        printf("Result: %f", d);
    }
}
</code>```

FAILED: untitled1
: && /usr/bin/cc -g  CMakeFiles/untitled1.dir/main.c.o -o untitled1   && :
/usr/bin/ld: CMakeFiles/untitled1.dir/main.c.o: in function `main':
/home/unoiko/CLionProjects/untitled1/main.c:16: undefined reference to `pow'
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
```

Don't know where misstake

Body:
#include <math.h>
#include <stdio.h>

float Fact(int x) {
    if (x == 1 || x == 0)
        return 1;
    else
        return x * Fact(x - 1);
}

int main() {
    float c;
    float d;
    float y;
    for(int n = 0; n < 10; n++) {
        c = 3 * (pow(n, n));
        y = Fact(n);
        d = y / c;
        printf("Result: %f", d);
    }
}

FAILED: untitled1
: && /usr/bin/cc -g  CMakeFiles/untitled1.dir/main.c.o -o untitled1   && :
/usr/bin/ld: CMakeFiles/untitled1.dir/main.c.o: in function `main':
/home/unoiko/CLionProjects/untitled1/main.c:16: undefined reference to `pow'
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

Don't know where misstake


问:
How to drag & drop the element from one window to another window?
We have a scenario to automate where we have to drag an element from one window & drop it into another window.

We have tried a few options using Actions class but that didnt work out because after we click & hold the item, we need to switch to another window before dropping it. So once we switch, it loses the item. We are using Selenium with Java. Does anyone know any possible solution for it?


问:
Error "is also present at [org.jitsi.react:jitsi-meet-sdk:3.3.0] AndroidManifest.xml:34:9-41 value=(@string/app_name)." Flutter
I build video call using jitsi when run the code then show this error.
"E:\video\android\app\src\debug\AndroidManifest.xml Error:
Attribute application@label value=(video) from (unknown)
is also present at [org.jitsi.react:jitsi-meet-sdk:3.3.0] AndroidManifest.xml:34:9-41 value=(@string/app_name).
Suggestion: add 'tools:replace="android:label"' to  element at AndroidManifest.xml:9:4-39:19 to override."

my AndroidManifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.video">
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   <application
        android:label="video"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>
</code>```

app Level build.gradle

```<code>   defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.video"
        // 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 24
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }
</code>```

android build.gradle

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

    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.2'
        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>```

installed packages

code

```<code>import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:jitsi_meet/jitsi_meet.dart';
import 'package:share/share.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final _formKey = GlobalKey<FormState>();
  late String roomCode;

  joinVideoConferrencingRoom() async {
    String serverUrl;
    if (_formKey.currentState!.validate()) {
      serverUrl = "https://meet.jit.si";

      Map<FeatureFlagEnum, bool> featureFlags = {
        FeatureFlagEnum.WELCOME_PAGE_ENABLED: false,
      };

      // Define meetings options here
      var options = JitsiMeetingOptions(room: roomCode)
        ..serverURL = serverUrl
        ..userDisplayName = "dasun"
        ..userEmail = 'tharindudasun0@gmail.com'
        ..featureFlags.addAll(featureFlags);

      debugPrint("JitsiMeetingOptions: $options");
      await JitsiMeet.joinMeeting(options,
          listener: JitsiMeetingListener(
              onConferenceWillJoin: (message) {
                debugPrint("${options.room} will join with message: $message");
              },
              onConferenceJoined: (message) {
                debugPrint("${options.room} joined with message: $message");
              },
              onConferenceTerminated: (message) {
                debugPrint("${options.room} terminated with message: $message");
              },
              genericListeners: [
                JitsiGenericListener(
                    eventName: 'readyToClose',
                    callback: (dynamic message) {
                      debugPrint("readyToClose callback");
                    })
              ]));
    } else {
      print("please enter some code to join");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 90.0, right: 90),
            child: TextFormField(
              decoration: InputDecoration(hintText: "Enter Secret Code"),
              onChanged: (val) {
                roomCode = val;
                print(val);
              },
              validator: (val) {
                if (val == null || val.isEmpty) {
                  return "cant't be empty!";
                } else {
                  val = "";
                  return null;
                }
              },
            ),
          ),
          SizedBox(
            height: 25,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () {
                  joinVideoConferrencingRoom();
                },
                child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.green,
                        borderRadius: BorderRadius.circular(29)),
                    height: 50,
                    width: MediaQuery.of(context).size.width / 2.4,
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            CupertinoIcons.video_camera,
                            size: 36,
                            color: Colors.amber,
                          ),
                          SizedBox(
                            width: 9,
                          ),
                          Text(
                            "Join",
                            style: TextStyle(color: Colors.white, fontSize: 18),
                          ),
                        ])),
              ),
              SizedBox(
                width: 19,
              ),
              GestureDetector(
                onTap: () {
                  if (_formKey.currentState!.validate()) {
                    Share.share("$roomCode");
                  } else {
                    // ignore: avoid_print
                    print("Please provide some room code");
                  }
                },
                child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.amber,
                        borderRadius: BorderRadius.circular(29)),
                    height: 50,
                    width: MediaQuery.of(context).size.width / 2.4,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.share,
                          color: Colors.green,
                        ),
                        SizedBox(
                          width: 15,
                        ),
                        Text(
                          "Share",
                          style: TextStyle(color: Colors.black, fontSize: 17),
                        ),
                      ],
                    )),
              ),
            ],
          )
        ],
      ),
    );
  }
}
</code>```

How I resolve this error?

Body:
I build video call using jitsi when run the code then show this error.
"E:\video\android\app\src\debug\AndroidManifest.xml Error:
Attribute application@label value=(video) from (unknown)
is also present at [org.jitsi.react:jitsi-meet-sdk:3.3.0] AndroidManifest.xml:34:9-41 value=(@string/app_name).
Suggestion: add 'tools:replace="android:label"' to  element at AndroidManifest.xml:9:4-39:19 to override."

my AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.video">
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   <application
        android:label="video"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

app Level build.gradle

   defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.video"
        // 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 24
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

android build.gradle

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

    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.2'
        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
}

installed packages

code

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:jitsi_meet/jitsi_meet.dart';
import 'package:share/share.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final _formKey = GlobalKey<FormState>();
  late String roomCode;

  joinVideoConferrencingRoom() async {
    String serverUrl;
    if (_formKey.currentState!.validate()) {
      serverUrl = "https://meet.jit.si";

      Map<FeatureFlagEnum, bool> featureFlags = {
        FeatureFlagEnum.WELCOME_PAGE_ENABLED: false,
      };

      // Define meetings options here
      var options = JitsiMeetingOptions(room: roomCode)
        ..serverURL = serverUrl
        ..userDisplayName = "dasun"
        ..userEmail = 'tharindudasun0@gmail.com'
        ..featureFlags.addAll(featureFlags);

      debugPrint("JitsiMeetingOptions: $options");
      await JitsiMeet.joinMeeting(options,
          listener: JitsiMeetingListener(
              onConferenceWillJoin: (message) {
                debugPrint("${options.room} will join with message: $message");
              },
              onConferenceJoined: (message) {
                debugPrint("${options.room} joined with message: $message");
              },
              onConferenceTerminated: (message) {
                debugPrint("${options.room} terminated with message: $message");
              },
              genericListeners: [
                JitsiGenericListener(
                    eventName: 'readyToClose',
                    callback: (dynamic message) {
                      debugPrint("readyToClose callback");
                    })
              ]));
    } else {
      print("please enter some code to join");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 90.0, right: 90),
            child: TextFormField(
              decoration: InputDecoration(hintText: "Enter Secret Code"),
              onChanged: (val) {
                roomCode = val;
                print(val);
              },
              validator: (val) {
                if (val == null || val.isEmpty) {
                  return "cant't be empty!";
                } else {
                  val = "";
                  return null;
                }
              },
            ),
          ),
          SizedBox(
            height: 25,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () {
                  joinVideoConferrencingRoom();
                },
                child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.green,
                        borderRadius: BorderRadius.circular(29)),
                    height: 50,
                    width: MediaQuery.of(context).size.width / 2.4,
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            CupertinoIcons.video_camera,
                            size: 36,
                            color: Colors.amber,
                          ),
                          SizedBox(
                            width: 9,
                          ),
                          Text(
                            "Join",
                            style: TextStyle(color: Colors.white, fontSize: 18),
                          ),
                        ])),
              ),
              SizedBox(
                width: 19,
              ),
              GestureDetector(
                onTap: () {
                  if (_formKey.currentState!.validate()) {
                    Share.share("$roomCode");
                  } else {
                    // ignore: avoid_print
                    print("Please provide some room code");
                  }
                },
                child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.amber,
                        borderRadius: BorderRadius.circular(29)),
                    height: 50,
                    width: MediaQuery.of(context).size.width / 2.4,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.share,
                          color: Colors.green,
                        ),
                        SizedBox(
                          width: 15,
                        ),
                        Text(
                          "Share",
                          style: TextStyle(color: Colors.black, fontSize: 17),
                        ),
                      ],
                    )),
              ),
            ],
          )
        ],
      ),
    );
  }
}

How I resolve this error?


问:
How to implement client-server interaction with an android application via a server?
It is planned to create an android application on kotlin. There is a button in one of the activities. When you click on this button, a certain message is sent to a remote server. The google maps api keys are stored on the remote server. Based on this message, an automatic request is generated to the Google Maps server from my server. The result is returned to my server, from where it is automatically forwarded to the android application.
How optimal is this approach in terms of api protection?
If it is optimal, then how best to implement it from the server side. Now I have an empty virtual server on Ubuntu 20.04 with api.txt the document where the keys are stored.


问:
Schtasks command line folderpath with spaces
I want to copy and replace a file from one folder to another folder via the command line using copy and schtasks. I'm having trouble with the spaces in the folderpaths. For some reason I get an: ERROR: Invalid argument/option. The spaces are between "test 1" and "test 2"

This is my line:

```<code>schtasks /create /tn CopyFile /tr "copy "C:\Users\pc\desktop\test 1\test2022.xlsx" "C:\Users\pc\desktop\test 2\test2022.xlsx"" /sc MINUTE /mo 1
</code>```

I also tried this with xcopy but got the same result:

```<code>"xcopy /y"
</code>```

What am I doing wrong? Thank you in advance!

Body:
I want to copy and replace a file from one folder to another folder via the command line using copy and schtasks. I'm having trouble with the spaces in the folderpaths. For some reason I get an: ERROR: Invalid argument/option. The spaces are between "test 1" and "test 2"

This is my line:

schtasks /create /tn CopyFile /tr "copy "C:\Users\pc\desktop\test 1\test2022.xlsx" "C:\Users\pc\desktop\test 2\test2022.xlsx"" /sc MINUTE /mo 1

I also tried this with xcopy but got the same result:

"xcopy /y"

What am I doing wrong? Thank you in advance!


问:
I couldn't achieve throttle effect in 'mouseover' addEventListener. 'e' is coming as undefined in logMousePosition function
Here below I have attached my code. please anyone guide me If I made any error in my code. give explanation on what is the issue here ?

I have worked in React js setState and I couldn't find any mistakes in my code. hard to understand  what is the problem here ?

Thanks.

```<code>import React, {useState, useEffect, useLayoutEffect} from 'react';

function HookMouse(props) {

    const [x, setX] = useState(0)
    const [y, setY] = useState(0)

    const logMousePosition = e => {
        console.log("Event",e)

        setX(e.clientX)
        setY(e.clientY)
    }

    const throttle = (fn, delay) => {
        console.log(fn,delay)
        let shouldPause = false;
        return function() {
            console.log("Function",fn)
            if(shouldPause) return;
            fn();
            shouldPause = true;
            setTimeout(()=>{
                shouldPause = false;
            },delay)

        }
    }

    const betterFunc = throttle(logMousePosition,250);

    useEffect(() => {
        console.log('useEffect Called')

        window.addEventListener('mousemove', betterFunc)

        //cleanup code return function
        //If don't return it won't remove subscribers, timers, eventhandlers
        return () => {
            console.log('Component Unmounted')
            window.addEventListener('mousemove', betterFunc)

        }
    }, []) //empty array block for just initial render after that it will not render again and again

    return (
        <div>
            Hooks X - {x} Y - {y}
        </div>
    );
}

export default HookMouse;
</code>```

Body:
Here below I have attached my code. please anyone guide me If I made any error in my code. give explanation on what is the issue here ?

I have worked in React js setState and I couldn't find any mistakes in my code. hard to understand  what is the problem here ?

Thanks.

import React, {useState, useEffect, useLayoutEffect} from 'react';

function HookMouse(props) {

    const [x, setX] = useState(0)
    const [y, setY] = useState(0)

    const logMousePosition = e => {
        console.log("Event",e)

        setX(e.clientX)
        setY(e.clientY)
    }

    const throttle = (fn, delay) => {
        console.log(fn,delay)
        let shouldPause = false;
        return function() {
            console.log("Function",fn)
            if(shouldPause) return;
            fn();
            shouldPause = true;
            setTimeout(()=>{
                shouldPause = false;
            },delay)

        }
    }

    const betterFunc = throttle(logMousePosition,250);

    useEffect(() => {
        console.log('useEffect Called')

        window.addEventListener('mousemove', betterFunc)

        //cleanup code return function
        //If don't return it won't remove subscribers, timers, eventhandlers
        return () => {
            console.log('Component Unmounted')
            window.addEventListener('mousemove', betterFunc)

        }
    }, []) //empty array block for just initial render after that it will not render again and again

    return (

            Hooks X - {x} Y - {y}

    );
}

export default HookMouse;


问:
How do I use StreamReader to assign values from a .txt file to a 2D array in Visual Studio?
In this program, I have to assign values to a 2D array by retrieving data from the following text file:

Product 1$Vanilla Ice Cream$20$1.99

Product 2$Glazed Donut$10$2.50

Product 3$Small Muffin$25$2.99

Product 4$Large Muffin$20$3.99

Product 5$Small Lollipop$40$1

Product 6$Large Lollipop$30$2

Each row is a different product, and the "$" separates the different facts about the products. For example, Product 1 is Vanilla Ice Cream, there are of it 20 available, and it costs 1.99 dollars.

```<code>        For intRow = 0 To 4
            strLine = inFile.ReadLine()
            For intCol = 0 To 5
                strFields(intRow, intCol) = Split(","c)(intCol)
                ListBox1.Items.Add(strFields)
            Next
        Next
</code>```

Here's the code I've tried so far. First, I'm trying to read the data from the first row, and then the data from each column as the variable corresponding to the row increases.

Body:
In this program, I have to assign values to a 2D array by retrieving data from the following text file:

Product 1$Vanilla Ice Cream$20$1.99

Product 2$Glazed Donut$10$2.50

Product 3$Small Muffin$25$2.99

Product 4$Large Muffin$20$3.99

Product 5$Small Lollipop$40$1

Product 6$Large Lollipop$30$2

Each row is a different product, and the "$" separates the different facts about the products. For example, Product 1 is Vanilla Ice Cream, there are of it 20 available, and it costs 1.99 dollars.

        For intRow = 0 To 4
            strLine = inFile.ReadLine()
            For intCol = 0 To 5
                strFields(intRow, intCol) = Split(","c)(intCol)
                ListBox1.Items.Add(strFields)
            Next
        Next

Here's the code I've tried so far. First, I'm trying to read the data from the first row, and then the data from each column as the variable corresponding to the row increases.


问:
How to retrieve the mongodb data before updating them?
I need to write a nodejs api where I need to create and update a logo.

The create works fine, but while updating the logo with a given id, the previous logo should get deleted and update with the new logo. We can use fs.unlink to delete the logo; but while using fs.unlink, the code deleted the updated logo; how do I fix this?

If I somehow knew the previous logo's name, then I could delete it.

```<code>const data = await PRISMA.ref_types.update({
      where: { id: id },
      data: {
                business_name: business_name,
                business_logo: File_Name,
                business_type: business_type,
                address: address,
                timezone: timezone,
                currency: currency,
                ref: headerData?.ref
            },
    });

  // Update the existing image record in the database
  const existingImage = await PRISMA.ref_types.findFirst({
                    where: { id }, select: {
                        business_logo: true
                    }
                })

  // find the image
  const a = Object.entries(existingImage)
  const b = a[0][1]
  const fileName = b.split('/').pop()
  console.log("dsadsad", fileName)

  // Delete the old image file
  fs.unlinkSync('uploads/' + headerData?.ref + '/settings/' + fileName)
  let found = await PRISMA.languages.findFirst({
                    where: { ref: headerData.ref }
                })
</code>```

Body:
I need to write a nodejs api where I need to create and update a logo.

The create works fine, but while updating the logo with a given id, the previous logo should get deleted and update with the new logo. We can use fs.unlink to delete the logo; but while using fs.unlink, the code deleted the updated logo; how do I fix this?

If I somehow knew the previous logo's name, then I could delete it.

const data = await PRISMA.ref_types.update({
      where: { id: id },
      data: {
                business_name: business_name,
                business_logo: File_Name,
                business_type: business_type,
                address: address,
                timezone: timezone,
                currency: currency,
                ref: headerData?.ref
            },
    });

  // Update the existing image record in the database
  const existingImage = await PRISMA.ref_types.findFirst({
                    where: { id }, select: {
                        business_logo: true
                    }
                })

  // find the image
  const a = Object.entries(existingImage)
  const b = a[0][1]
  const fileName = b.split('/').pop()
  console.log("dsadsad", fileName)

  // Delete the old image file
  fs.unlinkSync('uploads/' + headerData?.ref + '/settings/' + fileName)
  let found = await PRISMA.languages.findFirst({
                    where: { ref: headerData.ref }
                })


问:
How to access and stock different string in the line of a text file in C

Hi, so i have a file that contains multiple lines. Those lines are composed by the name of an object or a thing and his category between [ ]. the object can have 1 or multiple categories. Here is an example of a line of this file:  spare wheel [car] [toyota] or this cruise [boat]

I would like to read the file to get the name of the object and it's categories if they are more than one and how can i stock them somewhere where i could have access to both the name and the categories for each line. Is there a way to do that ?

I don't really know how to start but maybe an array of struct could work ?

Thanks


问:
How do I convert strings of numbers, coming from a .txt file into an int array using stoi::("string")
I've been trying to take a .txt document with three number entries, read those entries as strings and convert those entries in ints, then put them into an int array, but had no success in doing so and i have no clue as to why. Note that the entries as well as some variable names are pre determined by the assignment, additionally we have to use the std::stoi("string") command, which i am not familiar with nor has any syntax been provided to us (which is especially strange since we are usually not allowed to stray to far from the lecture material)
What I excpected to happen is that the numbers from the .txt file were converted into an array, however what actually happened is that an "unhandled exception" (my apologies if that term does not make sanes we have to programm in our native language) occured and the string library opened itself, marking the error on line 107. The problematic line in my code seems to be "auftraegearray[i++] = std::stoi(MengeanAuftraegen);"</p>
```<code>int main()
{
    std::fstream Auftraege;
    Auftraege.open("Auftraege37.txt", std::ios::out);
    Auftraege << "10" << std::endl;
    Auftraege << "1" << std::endl;
    Auftraege << "20" << std::endl;
    Auftraege.close();

    int i = 0;
    int auftraegearray[4];
    std::string MengeanAuftraegen;
    Auftraege.open("Auftraege37.txt", std::ios::in);
    while (!Auftraege.eof())
    {
        getline(Auftraege, MengeanAuftraegen);
        std::cout << MengeanAuftraegen << std::endl;
        auftraegearray[i++] = std::stoi(MengeanAuftraegen);

    }

    Auftraege.close();
</code>```

Body:
I've been trying to take a .txt document with three number entries, read those entries as strings and convert those entries in ints, then put them into an int array, but had no success in doing so and i have no clue as to why. Note that the entries as well as some variable names are pre determined by the assignment, additionally we have to use the std::stoi("string") command, which i am not familiar with nor has any syntax been provided to us (which is especially strange since we are usually not allowed to stray to far from the lecture material)
What I excpected to happen is that the numbers from the .txt file were converted into an array, however what actually happened is that an "unhandled exception" (my apologies if that term does not make sanes we have to programm in our native language) occured and the string library opened itself, marking the error on line 107. The problematic line in my code seems to be "auftraegearray[i++] = std::stoi(MengeanAuftraegen);"

int main()
{
    std::fstream Auftraege;
    Auftraege.open("Auftraege37.txt", std::ios::out);
    Auftraege << "10" << std::endl;
    Auftraege << "1" << std::endl;
    Auftraege << "20" << std::endl;
    Auftraege.close();

    int i = 0;
    int auftraegearray[4];
    std::string MengeanAuftraegen;
    Auftraege.open("Auftraege37.txt", std::ios::in);
    while (!Auftraege.eof())
    {
        getline(Auftraege, MengeanAuftraegen);
        std::cout << MengeanAuftraegen << std::endl;
        auftraegearray[i++] = std::stoi(MengeanAuftraegen);

    }

    Auftraege.close();


问:
Cannot convert tuple data into int in python
```<code>   I have function which reads a tuple from a .csv file.
</code>```

Idk why but it is stored as a string and when I try to convert it into int it gives me error.

It first said,  invalid literal for int() with base 10: ','
and when I tried converting it into a float and then to int, its giving me error Cannot Convert into a string

```<code>   try:
        data_black = pandas.read_csv("../../data/black_pieces_data.csv")
        dict_black = data_black.to_dict()

        pos = dict_black[f"pawn{i}"][0]   # here, pos is (1,0) for the 1st iteration

        row = int(pos[1])                 # This is being converted into int correctly
        col = int(float((pos[2])))        # I also tried col = int(pos[2]) and

                                          # it gave me ValueError saying I cannot to convert to Int.

        self.squares[row][col] = Square(row, col, Pawns("black"), "pawns")   # Don't foucs on this part.

    except FileNotFoundError:
        messagebox.showerror("Cannot Load", "There is no save file.\nCannot Load Game.")
    pass
</code>```

Any help would be greatly appreciated. Thank You!

Body:
   I have function which reads a tuple from a .csv file.

Idk why but it is stored as a string and when I try to convert it into int it gives me error.

It first said,  invalid literal for int() with base 10: ','
and when I tried converting it into a float and then to int, its giving me error Cannot Convert into a string

   try:
        data_black = pandas.read_csv("../../data/black_pieces_data.csv")
        dict_black = data_black.to_dict()

        pos = dict_black[f"pawn{i}"][0]   # here, pos is (1,0) for the 1st iteration

        row = int(pos[1])                 # This is being converted into int correctly
        col = int(float((pos[2])))        # I also tried col = int(pos[2]) and

                                          # it gave me ValueError saying I cannot to convert to Int.

        self.squares[row][col] = Square(row, col, Pawns("black"), "pawns")   # Don't foucs on this part.

    except FileNotFoundError:
        messagebox.showerror("Cannot Load", "There is no save file.\nCannot Load Game.")
    pass

Any help would be greatly appreciated. Thank You!


问:
Renaming files with for loop
as can be seen from both pictures my directory is filled with different annual reports which have for example a name such as NASDAQ_2012 for different years. I would like to write an R-code which replaces these part before the underscore and year of the annual report into the corresponding code attached to the file e.g., 179058.

File

I now can only change the files in the directory for 1 map with the following code

setwd("/Users/jenne/TU Eindhoven/Roost, Patricia - Data mining study - SHARED/Annual reports/004036")
file.rename(list.files(pattern="NYSE_DCI"), str_replace(list.files(pattern = "NYSE_DCI"),
pattern = "NYSE_DCI", "004036"))
anyone that can help me out?

Title: Renaming files with for loop


问:
Not able to render a paragraph in EJS
I am creating a blog post so when I entered a blog having two or more paragraph EJS is rendering it as plain text
This is the main app.js code
`

```<code>app.get('/posts/:topic' , (req , res)=>{

    requestedTitle = lodash.kebabCase(req.params.topic)

    posts.forEach((post)=>{

        var sortedTitle = lodash.kebabCase(post.title)

        if( sortedTitle === requestedTitle){
            console.log(post.body);
            res.render('standalone',{postTitle:post.title,postBody:post.body})
        }
        else{
            res.render('standalone',{postTitle:"Warning",postBody:"No post found by that name"})
            console.log('No match found')
        }
    })
})
</code>```

`
This is the ejs file

```<code><%- include('partials/header') %>

   <h1><%= postTitle %> </h1>
   <p> <%= postBody %> </p>

<%- include('partials/footer') %>

</code>```

I have checked post.body for more clarification but I can't find error
enter image description here
Please Help I am new here

Title: Not able to render a paragraph in EJS

Body:
I am creating a blog post so when I entered a blog having two or more paragraph EJS is rendering it as plain text
This is the main app.js code
`

app.get('/posts/:topic' , (req , res)=>{

    requestedTitle = lodash.kebabCase(req.params.topic)

    posts.forEach((post)=>{

        var sortedTitle = lodash.kebabCase(post.title)

        if( sortedTitle === requestedTitle){
            console.log(post.body);
            res.render('standalone',{postTitle:post.title,postBody:post.body})
        }
        else{
            res.render('standalone',{postTitle:"Warning",postBody:"No post found by that name"})
            console.log('No match found')
        }
    })
})

`
This is the ejs file

<%- include('partials/header') %>

<%= postTitle %>

 <%= postBody %>

<%- include('partials/footer') %>

I have checked post.body for more clarification but I can't find error
enter image description here
Please Help I am new here


问:
Problem with infinite loop in slider using jQuery
I tried making jQuery slider, which will pause on current image for couple of seconds and then move images horizontally. Also, when slider presents the last image in collection, slider should slowly get back to first image, or when marginLeft attribute reaches value of -200vw(it decreases gradually for -100vw after every image). Most of the time slider works perfectly, but there are also moments when slider ignores my if and goes above -200vw(sometimes up to -3000vw), resulting in showing no images.  The only thing that I noticed in this situation is that this problem can occur after around 5-10 minutes spent on other browser tabs.

P.S I apologize for a lack of precise details, because these are the only thing I have noticed with this problem

jQuery/Javascript

$(document).ready(function() {
  let delay           = 5300;
  let currentSlide    = 1;
  let $carousel       = $('#carousel')
  let $slideContainer = $carousel.find('.slides');
  let $width          = 100;
  let $slides         = $slideContainer.find('.slide')

  var interval = setInterval(function() {
    $slideContainer.animate({
      'marginLeft': '-=' + $width + 'vw'
    }, 1000, function() {
      currentSlide++;
      var abc = $slideContainer.width();
      if (currentSlide == $slides.length) {
        setTimeout(function() {
          $slideContainer.animate({
            'marginLeft': '+=' + ($width + 100) + 'vw'
          }, 1000, function() {
            currentSlide = 1;
            $slideContainer.css({
              'marginLeft': 0 + 'vw'
            })
          })
        }, (delay / 2.5))
      }
    })
  }, delay);
});
```
<p><strong>HTML</strong></p>
<pre class="lang-HTML prettyprint-override"><code><section id="carousel">
  <div class="slides">
    <div class="slide">
      <img src="../javaskript/images/slider/gaming1.jpg" style="height:100vh" alt="Introduction image 2 - slider" />
    </div>
    <div class="slide">
      <img src="../javaskript/images/slider/gaming2.jpg" style="height:100vh" alt="Introduction image 2 - slider">
    </div>
    <div class="slide">
      <img src="../javaskript/images/slider/scorn.jpg" style="height:100vh" alt="Introduction image 2 - slider">
    </div>
  </div>
</section>
</code>```

CSS

```<code>#carousel {
  overflow    : hidden;
  white-space : nowrap;
  width       : 300vw;
  height      : 100vh;
  }
.slides {
  display : flex;
  width   : 300vw;
  margin  : 0;
  padding : 0;
  }
.slide {
  width    : 100vw;
  overflow : hidden;
  }
</code>```

Body:
I tried making jQuery slider, which will pause on current image for couple of seconds and then move images horizontally. Also, when slider presents the last image in collection, slider should slowly get back to first image, or when marginLeft attribute reaches value of -200vw(it decreases gradually for -100vw after every image). Most of the time slider works perfectly, but there are also moments when slider ignores my if and goes above -200vw(sometimes up to -3000vw), resulting in showing no images.  The only thing that I noticed in this situation is that this problem can occur after around 5-10 minutes spent on other browser tabs.

P.S I apologize for a lack of precise details, because these are the only thing I have noticed with this problem

jQuery/Javascript

$(document).ready(function() {
  let delay           = 5300;
  let currentSlide    = 1;
  let $carousel       = $('#carousel')
  let $slideContainer = $carousel.find('.slides');
  let $width          = 100;
  let $slides         = $slideContainer.find('.slide')

  var interval = setInterval(function() {
    $slideContainer.animate({
      'marginLeft': '-=' + $width + 'vw'
    }, 1000, function() {
      currentSlide++;
      var abc = $slideContainer.width();
      if (currentSlide == $slides.length) {
        setTimeout(function() {
          $slideContainer.animate({
            'marginLeft': '+=' + ($width + 100) + 'vw'
          }, 1000, function() {
            currentSlide = 1;
            $slideContainer.css({
              'marginLeft': 0 + 'vw'
            })
          })
        }, (delay / 2.5))
      }
    })
  }, delay);
});

HTML

CSS

#carousel {
  overflow    : hidden;
  white-space : nowrap;
  width       : 300vw;
  height      : 100vh;
  }
.slides {
  display : flex;
  width   : 300vw;
  margin  : 0;
  padding : 0;
  }
.slide {
  width    : 100vw;
  overflow : hidden;
  }


问:
How to make R to be avaible in Jupiter notebook?
I have Jupiter Notebook and it sees Python3 clearly. Then I installed R, installed IRkernel using this instruction but when I used the command

```<code>IRkernel::installspec(user = FALSE)
</code>```

I got an error:

```<code>Error in IRkernel::installspec(user = FALSE) :
  jupyter-client has to be installed but “jupyter kernelspec --version” exited with code 127.
In addition: Warning message:
In system2("jupyter", c("kernelspec", "--version"), FALSE, FALSE) :
  '"jupyter"' not found
</code>```

Please help me to understand where is the mistake?
(Windows 10, Python3)

Body:
I have Jupiter Notebook and it sees Python3 clearly. Then I installed R, installed IRkernel using this instruction but when I used the command

IRkernel::installspec(user = FALSE)

I got an error:

Error in IRkernel::installspec(user = FALSE) :
  jupyter-client has to be installed but “jupyter kernelspec --version” exited with code 127.
In addition: Warning message:
In system2("jupyter", c("kernelspec", "--version"), FALSE, FALSE) :
  '"jupyter"' not found

Please help me to understand where is the mistake?
(Windows 10, Python3)


问:
how to delete firebase storage document in react native?
I'm building an app using React Native and Firebase and using firebase storage to store data within my app.

My problem is that i need to delete some documents in my app when specific events happens. I checked documentation but didnt find anything that answered my question, any help?

I tried this:

```<code>export const deletePost = (postId) => {
    firebase.storage().ref(`post/${firebase.auth().currentUser.uid}/${postId}`).delete()
}
</code>```

Body:
I'm building an app using React Native and Firebase and using firebase storage to store data within my app.

My problem is that i need to delete some documents in my app when specific events happens. I checked documentation but didnt find anything that answered my question, any help?

I tried this:

export const deletePost = (postId) => {
    firebase.storage().ref(`post/${firebase.auth().currentUser.uid}/${postId}`).delete()
}


问:
why back button only change url once with onpopstate?
I use this function to trigger back button clicked.
with this code each time I clicked back button onpopstate triggerd but only once it changes the url and when I comment this then the problem  is solved.

```<code>   $(document).ready(function() {
        window.onpopstate = function () {
            var urlmethod = get_url_method();
            console.log(urlmethod);
            if (urlmethod == "products") {
                show_main();
            } else if (urlmethod == "cart") {
                show_carts();
            } else if (urlmethod == "orders") {
                orders_click();
            }
        }
    });

</code>```

I change url in my code with this code:

```<code>  function set_url(parent_id){
        const nextState = { additionalInformation: parent_id };
        if (parent_id==0){
            window.history.pushState(nextState, "", "http://localhost");
        }else {
            var parent = data.find(item => item.term_id == parent_id);
            window.history.pushState(nextState, "", "http://localhost/brands/" + parent_id);
        }
    }
</code>```

what should I change?

Body:
I use this function to trigger back button clicked.
with this code each time I clicked back button onpopstate triggerd but only once it changes the url and when I comment this then the problem  is solved.

   $(document).ready(function() {
        window.onpopstate = function () {
            var urlmethod = get_url_method();
            console.log(urlmethod);
            if (urlmethod == "products") {
                show_main();
            } else if (urlmethod == "cart") {
                show_carts();
            } else if (urlmethod == "orders") {
                orders_click();
            }
        }
    });

I change url in my code with this code:

  function set_url(parent_id){
        const nextState = { additionalInformation: parent_id };
        if (parent_id==0){
            window.history.pushState(nextState, "", "http://localhost");
        }else {
            var parent = data.find(item => item.term_id == parent_id);
            window.history.pushState(nextState, "", "http://localhost/brands/" + parent_id);
        }
    }

what should I change?


问:
Handling multiple tables reference Id in a single column in PostgreSQL
In the PostgreSQL database, I want to manage a History table that relates to multiple modules in the application. It contains a 'common_id' field which stores the reference ids of each module, ie; different tables.

eg: If I am creating the history related to 3 tables. Profile, Event, Settings the history table will contain info as follows.

```<code>Common_id   |   Type

user_id     |  Profile

event_id    |  Event

settings_id | Settings
</code>```

And I need to query the data based on each Id. Currently, PostgreSQL creates a default foreign key reference to one of the related tables and it causes errors while inserting into other tables. Below is the code snippet.

Repository Function

```<code>createHistory: async ({ models }, args) => {
        return await models.History.create(args);
    },
</code>```

Model

```<code>'use strict';
const { Model } = require('sequelize');

module.exports = (sequelize, DataTypes) => {
    class History extends Model {
        static associate(models) {
            History.belongsTo(models.Training, {
                foreignKey: 'common_id',
                as: 'trainingId',
            });
            History.belongsTo(models.Club, {
                foreignKey: 'club_id',
                as: 'club',
            });
            History.belongsTo(models.User, {
                foreignKey: 'created_by',
                as: 'uid',
            });
        }
    }

    History.init(
        {
            message: DataTypes.STRING,
            users_associated: DataTypes.ARRAY(DataTypes.INTEGER),
            history_type: DataTypes.STRING,
        },
        {
            timestamps: true,
            sequelize,
            paranoid: true,
            modelName: 'History',
        }
    );
    return History;
};
</code>```

Body:
In the PostgreSQL database, I want to manage a History table that relates to multiple modules in the application. It contains a 'common_id' field which stores the reference ids of each module, ie; different tables.

eg: If I am creating the history related to 3 tables. Profile, Event, Settings the history table will contain info as follows.

Common_id   |   Type

user_id     |  Profile

event_id    |  Event

settings_id | Settings

And I need to query the data based on each Id. Currently, PostgreSQL creates a default foreign key reference to one of the related tables and it causes errors while inserting into other tables. Below is the code snippet.

Repository Function

createHistory: async ({ models }, args) => {
        return await models.History.create(args);
    },

Model

'use strict';
const { Model } = require('sequelize');

module.exports = (sequelize, DataTypes) => {
    class History extends Model {
        static associate(models) {
            History.belongsTo(models.Training, {
                foreignKey: 'common_id',
                as: 'trainingId',
            });
            History.belongsTo(models.Club, {
                foreignKey: 'club_id',
                as: 'club',
            });
            History.belongsTo(models.User, {
                foreignKey: 'created_by',
                as: 'uid',
            });
        }
    }

    History.init(
        {
            message: DataTypes.STRING,
            users_associated: DataTypes.ARRAY(DataTypes.INTEGER),
            history_type: DataTypes.STRING,
        },
        {
            timestamps: true,
            sequelize,
            paranoid: true,
            modelName: 'History',
        }
    );
    return History;
};


问:
How to fix a problem with Super PuTTY not opening multiple Telnet nodes in separate tabs when I attempt group select console to nodes
When I group select to console into multiple Eve-NG Telnet nodes within a lab and then select ">_Console To Selected Nodes", Super Putty opens, however, it will only open a tab for a single Telnet node.

I have created a lab in Eve-NG with two vSRX Telnet nodes that are connected via ge-0/0/1 and ge-0/0/2.  This lab also has an Eve-NG cloud image where the vSRX nodes are connected to it via ge-0/0/3. I added two GUI enabled Linux VNC hosts which are also connected to the afore mentioned cloud image and each via e0.

I set up Super PuTTY in the Windows 11 registry and then set it as the default Telnet application with the "only allow single instance" mode enabled.

Ideally, Super PuTTY should open both vSRX nodes within a single instance and each within a separate tab.

I discovered through troubleshooting that if a Super PuTTY session is already opened on the desktop, then both vSRX's will be opened in separate tabs.  Or if the "only allow single instance" mode is disabled in Super Putty, then the vSRX's are both opened but in separate Super PuTTY instances.  This behavior is not desirable.

Would anyone be able to offer any tips that I could try at solving the above issue?


问:
Socket.io transport close after client connects and sends pings. ESP32/WT32-ETH01 as client
I am absolutely bewildered right now, I have been using this library WebSocket_generic (https://github.com/khoih-prog/WebSockets_Generic) for my WT32-ETH01 and it even has examples just for the board. Ive used both the server and client examples, it connects just fine, but after three messages, or roughly 90 secs give or take it suddenly and abruptly disconnects. Give it 5 minutes it reconnects, sends some more pings and it disconnects, and does so in a cycle. Here is the serverside code:

```<code>const app = require('express');
const http = require('http').createServer(app);
const io = require('socket.io')(http);

io.on('connection', (socket) => {

  console.log('Connected');
  console.log(socket.id);
  console.log("JWT token test: ",socket.handshake.headers)

  socket.on('event_name', (data) => {

    console.log("Message from Client : ", data);

    socket.broadcast.emit("Send Message socket.broadcast.emit : ", data);
    io.emit("Send Message io.emit Broadcasted : ", data);
    socket.emit("Send Message : ", data);

  })

  socket.on('disconnect', (reason) => {

    console.log('Disconnected');
    console.log(reason);

  })

})

http.listen(8080, () => {

  console.log("Server launched on port 8080");
})

</code>```

WT32-ETH01 code (Arduino ide)

```<code>#if !defined(ESP32)
  #error This code is intended to run only on the ESP32 boards ! Please check your Tools->Board setting.
#endif

#define _WEBSOCKETS_LOGLEVEL_     2

#include <WebServer_WT32_ETH01.h>     // https://github.com/khoih-prog/WebServer_WT32_ETH01

#include <ArduinoJson.h>

#include <WebSocketsClient_Generic.h>
#include <SocketIOclient_Generic.h>

SocketIOclient socketIO;

/////////////////////////////////////////////

// Select the Server's IP address according to your local network
IPAddress serverIP(192, 168, 100, 59);
uint16_t  serverPort = 8080;

/////////////////////////////////////////////

// Select the IP address according to your local network
IPAddress myIP(192, 168, 100, 99);
IPAddress myGW(192, 168, 100, 1);
IPAddress mySN(255, 255, 255, 0);

// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);

/////////////////////////////////////////////

void hexdump(const void *mem, const uint32_t& len, const uint8_t& cols = 16)
{
  const uint8_t* src = (const uint8_t*) mem;

  Serial.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);

  for (uint32_t i = 0; i < len; i++)
  {
    if (i % cols == 0)
    {
      Serial.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);
    }

    Serial.printf("%02X ", *src);
    src++;
  }

  Serial.printf("\n");
}

void socketIOEvent(const socketIOmessageType_t& type, uint8_t * payload, const size_t& length)
{
  switch (type)
  {
    case sIOtype_DISCONNECT:
      Serial.println("[IOc] Disconnected");

      break;

    case sIOtype_CONNECT:
      Serial.print("[IOc] Connected to url: ");
      Serial.println((char*) payload);

      // join default namespace (no auto join in Socket.IO V3)
      socketIO.send(sIOtype_CONNECT, "/");

      break;

    case sIOtype_EVENT:
      Serial.print("[IOc] Get event: ");
      Serial.println((char*) payload);

      break;

    case sIOtype_ACK:
      Serial.print("[IOc] Get ack: ");
      Serial.println(length);

      hexdump(payload, length);

      break;

    case sIOtype_ERROR:
      Serial.print("[IOc] Get error: ");
      Serial.println(length);

      hexdump(payload, length);

      break;

    case sIOtype_BINARY_EVENT:
      Serial.print("[IOc] Get binary: ");
      Serial.println(length);

      hexdump(payload, length);

      break;

    case sIOtype_BINARY_ACK:
      Serial.print("[IOc] Get binary ack: ");
      Serial.println(length);

      hexdump(payload, length);

      break;

    case sIOtype_PING:
      Serial.println("[IOc] Get PING");

      break;

    case sIOtype_PONG:
      Serial.println("[IOc] Get PONG");

      break;

    default:
      break;
  }
}

void setup()
{
  // Serial.begin(921600);
  Serial.begin(115200);

  while (!Serial);

  Serial.print("\nStart WT32_ETH01_WebSocketClientSocketIO on ");
  Serial.print(ARDUINO_BOARD);
  Serial.print(" with ");
  Serial.println(SHIELD_TYPE);
  Serial.println(WEBSERVER_WT32_ETH01_VERSION);
  Serial.println(WEBSOCKETS_GENERIC_VERSION);

  Serial.setDebugOutput(true);

  // To be called before ETH.begin()
  WT32_ETH01_onEvent();

  //bool begin(uint8_t phy_addr=ETH_PHY_ADDR, int power=ETH_PHY_POWER, int mdc=ETH_PHY_MDC, int mdio=ETH_PHY_MDIO,
  //           eth_phy_type_t type=ETH_PHY_TYPE, eth_clock_mode_t clk_mode=ETH_CLK_MODE);
  //ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_PHY_TYPE, ETH_CLK_MODE);
  ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER);

  // Static IP, leave without this line to get IP via DHCP
  //bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
  ETH.config(myIP, myGW, mySN, myDNS);

  WT32_ETH01_waitForConnect();

  // Client address
  Serial.print("WebSockets Client started @ IP address: ");
  Serial.println(ETH.localIP());

  // server address, port and URL
  Serial.print("Connecting to WebSockets Server @ IP address: ");
  Serial.print(serverIP);
  Serial.print(", port: ");
  Serial.println(serverPort);

  // setReconnectInterval to 10s, new from v2.5.1 to avoid flooding server. Default is 0.5s
  socketIO.setReconnectInterval(10000);

  socketIO.setExtraHeaders("Authorization: 1234567890");

  // server address, port and URL
  // void begin(IPAddress host, uint16_t port, String url = "/socket.io/?EIO=4", String protocol = "arduino");
  // To use default EIO=4 fron v2.5.1
  socketIO.begin(serverIP, serverPort);

  // event handler
  socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;

void loop()
{
  socketIO.loop();

  uint64_t now = millis();

  if (now - messageTimestamp > 30000)
  {
    messageTimestamp = now;

    // creat JSON message for Socket.IO (event)
    DynamicJsonDocument doc(1024);
    JsonArray array = doc.to<JsonArray>();

    // add evnet name
    // Hint: socket.on('event_name', ....
    array.add("event_name");

    // add payload (parameters) for the event
    JsonObject param1 = array.createNestedObject();
    param1["now"]     = (uint32_t) now;

    // JSON to String (serializion)
    String output;
    serializeJson(doc, output);

    // Send event
    socketIO.sendEVENT(output);

    // Print JSON for debugging
    Serial.println(output);
  }
}
</code>```

I am lost, ive used different socket.io verisions such as v1, v2, v3 and v4.

What I expect to happen is for it to have a stable connection, it connects but it disconnects after a short while.

Body:
I am absolutely bewildered right now, I have been using this library WebSocket_generic (https://github.com/khoih-prog/WebSockets_Generic) for my WT32-ETH01 and it even has examples just for the board. Ive used both the server and client examples, it connects just fine, but after three messages, or roughly 90 secs give or take it suddenly and abruptly disconnects. Give it 5 minutes it reconnects, sends some more pings and it disconnects, and does so in a cycle. Here is the serverside code:

const app = require('express');
const http = require('http').createServer(app);
const io = require('socket.io')(http);

io.on('connection', (socket) => {

  console.log('Connected');
  console.log(socket.id);
  console.log("JWT token test: ",socket.handshake.headers)

  socket.on('event_name', (data) => {

    console.log("Message from Client : ", data);

    socket.broadcast.emit("Send Message socket.broadcast.emit : ", data);
    io.emit("Send Message io.emit Broadcasted : ", data);
    socket.emit("Send Message : ", data);

  })

  socket.on('disconnect', (reason) => {

    console.log('Disconnected');
    console.log(reason);

  })

})

http.listen(8080, () => {

  console.log("Server launched on port 8080");
})

WT32-ETH01 code (Arduino ide)

#if !defined(ESP32)
  #error This code is intended to run only on the ESP32 boards ! Please check your Tools->Board setting.
#endif

#define _WEBSOCKETS_LOGLEVEL_     2

#include <WebServer_WT32_ETH01.h>     // https://github.com/khoih-prog/WebServer_WT32_ETH01

#include <ArduinoJson.h>

#include <WebSocketsClient_Generic.h>
#include <SocketIOclient_Generic.h>

SocketIOclient socketIO;

/////////////////////////////////////////////

// Select the Server's IP address according to your local network
IPAddress serverIP(192, 168, 100, 59);
uint16_t  serverPort = 8080;

/////////////////////////////////////////////

// Select the IP address according to your local network
IPAddress myIP(192, 168, 100, 99);
IPAddress myGW(192, 168, 100, 1);
IPAddress mySN(255, 255, 255, 0);

// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);

/////////////////////////////////////////////

void hexdump(const void *mem, const uint32_t& len, const uint8_t& cols = 16)
{
  const uint8_t* src = (const uint8_t*) mem;

  Serial.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);

  for (uint32_t i = 0; i < len; i++)
  {
    if (i % cols == 0)
    {
      Serial.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);
    }

    Serial.printf("%02X ", *src);
    src++;
  }

  Serial.printf("\n");
}

void socketIOEvent(const socketIOmessageType_t& type, uint8_t * payload, const size_t& length)
{
  switch (type)
  {
    case sIOtype_DISCONNECT:
      Serial.println("[IOc] Disconnected");

      break;

    case sIOtype_CONNECT:
      Serial.print("[IOc] Connected to url: ");
      Serial.println((char*) payload);

      // join default namespace (no auto join in Socket.IO V3)
      socketIO.send(sIOtype_CONNECT, "/");

      break;

    case sIOtype_EVENT:
      Serial.print("[IOc] Get event: ");
      Serial.println((char*) payload);

      break;

    case sIOtype_ACK:
      Serial.print("[IOc] Get ack: ");
      Serial.println(length);

      hexdump(payload, length);

      break;

    case sIOtype_ERROR:
      Serial.print("[IOc] Get error: ");
      Serial.println(length);

      hexdump(payload, length);

      break;

    case sIOtype_BINARY_EVENT:
      Serial.print("[IOc] Get binary: ");
      Serial.println(length);

      hexdump(payload, length);

      break;

    case sIOtype_BINARY_ACK:
      Serial.print("[IOc] Get binary ack: ");
      Serial.println(length);

      hexdump(payload, length);

      break;

    case sIOtype_PING:
      Serial.println("[IOc] Get PING");

      break;

    case sIOtype_PONG:
      Serial.println("[IOc] Get PONG");

      break;

    default:
      break;
  }
}

void setup()
{
  // Serial.begin(921600);
  Serial.begin(115200);

  while (!Serial);

  Serial.print("\nStart WT32_ETH01_WebSocketClientSocketIO on ");
  Serial.print(ARDUINO_BOARD);
  Serial.print(" with ");
  Serial.println(SHIELD_TYPE);
  Serial.println(WEBSERVER_WT32_ETH01_VERSION);
  Serial.println(WEBSOCKETS_GENERIC_VERSION);

  Serial.setDebugOutput(true);

  // To be called before ETH.begin()
  WT32_ETH01_onEvent();

  //bool begin(uint8_t phy_addr=ETH_PHY_ADDR, int power=ETH_PHY_POWER, int mdc=ETH_PHY_MDC, int mdio=ETH_PHY_MDIO,
  //           eth_phy_type_t type=ETH_PHY_TYPE, eth_clock_mode_t clk_mode=ETH_CLK_MODE);
  //ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_PHY_TYPE, ETH_CLK_MODE);
  ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER);

  // Static IP, leave without this line to get IP via DHCP
  //bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
  ETH.config(myIP, myGW, mySN, myDNS);

  WT32_ETH01_waitForConnect();

  // Client address
  Serial.print("WebSockets Client started @ IP address: ");
  Serial.println(ETH.localIP());

  // server address, port and URL
  Serial.print("Connecting to WebSockets Server @ IP address: ");
  Serial.print(serverIP);
  Serial.print(", port: ");
  Serial.println(serverPort);

  // setReconnectInterval to 10s, new from v2.5.1 to avoid flooding server. Default is 0.5s
  socketIO.setReconnectInterval(10000);

  socketIO.setExtraHeaders("Authorization: 1234567890");

  // server address, port and URL
  // void begin(IPAddress host, uint16_t port, String url = "/socket.io/?EIO=4", String protocol = "arduino");
  // To use default EIO=4 fron v2.5.1
  socketIO.begin(serverIP, serverPort);

  // event handler
  socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;

void loop()
{
  socketIO.loop();

  uint64_t now = millis();

  if (now - messageTimestamp > 30000)
  {
    messageTimestamp = now;

    // creat JSON message for Socket.IO (event)
    DynamicJsonDocument doc(1024);
    JsonArray array = doc.to<JsonArray>();

    // add evnet name
    // Hint: socket.on('event_name', ....
    array.add("event_name");

    // add payload (parameters) for the event
    JsonObject param1 = array.createNestedObject();
    param1["now"]     = (uint32_t) now;

    // JSON to String (serializion)
    String output;
    serializeJson(doc, output);

    // Send event
    socketIO.sendEVENT(output);

    // Print JSON for debugging
    Serial.println(output);
  }
}

I am lost, ive used different socket.io verisions such as v1, v2, v3 and v4.

What I expect to happen is for it to have a stable connection, it connects but it disconnects after a short while.


问:
Why is React Native's Text.onTextLayout not being called?
I have a custom component which contains a <Text> component, and there is a handler on the onTextLayout callback of the <Text>:

```<code>  <Text style={style}
    onTextLayout={(e) => {
      ...
    }}
  >...</Text>
</code>```

This component is used at several locations in the app. At some of them, the onTextLayout callback is called correctly. At other locations, it is not called at all. No matter what I put in the callback (console.warns, throws, etc.), the component renders but my onTextLayout callback is not called.

What could be the reason for this? Is there a (documented) scenario in which a Text is rendered on the screen without onTextLayout being called?

Body:
I have a custom component which contains a <Text> component, and there is a handler on the onTextLayout callback of the <Text>:

  <Text style={style}
    onTextLayout={(e) => {
      ...
    }}
  >...</Text>

This component is used at several locations in the app. At some of them, the onTextLayout callback is called correctly. At other locations, it is not called at all. No matter what I put in the callback (console.warns, throws, etc.), the component renders but my onTextLayout callback is not called.

What could be the reason for this? Is there a (documented) scenario in which a Text is rendered on the screen without onTextLayout being called?


问:
jenkins expression is evaluating to false when checking for file existance to run second stage
team,

I have my pipeline that runs two stages.

stage 1 creates a file under /coverage-data/myfile and this is emptydir shared volume mounted from pod spec.

stage 2 starts if this file exists.

result: always expression is evaluating to FALSE any hint? I want to start the stage when file is created and present on the node on which this pipeline is runing such that all container in stages has access to this file.

pipeline

```<code>pipeline {
    agent {
        label 'label-coverage-cli'
    }

    environment {
        COVERAGE_FILE = fileExists '/coverage-data/myfile'
    }

    stages {
        stage('Code Coverage Tests') {
            steps {
                container('main') {
                        sh '''
                        ls -ltr /coverage-data/
                        unit-tests.sh
                        ls -ltr /coverage-data/myfile
                        '''.stripIndent()
                }
            }
        }
        stage('Code Coverage Scan') {
            when { expression { COVERAGE_FILE == 'true' } }
            steps {
                container('sonar-scan') {
                        sh '''
                        scan.sh
                        '''.stripIndent()
                }
            }
        }
    }
}
</code>```

pod spec that is mounting shared volume for all containers in all stages to write on and read from as shared-data

```<code>apiVersion: v1
kind: Pod
spec:
  imagePullSecrets:
    - name: sec
  volumes:
    - name: shared-data
      emptyDir: {}
  containers:
    - name: main
      image: registry/tci-sonar-scanner:latest
      volumeMounts:
      - name: shared-data
        mountPath: /coverage-data
      command:
        - /sbin/tini
      args:
        - --
        - sleep
        - infinity
    - name: sonar-scanner
      image: registry/sonarqube-scanner:4.7.0.2747
      volumeMounts:
      - name: shared-data
        mountPath: /coverage-data
      securityContext:
        privileged: true
      command:
        - tail
      args:
      - "-f"
      - "/dev/null"
</code>```

output also shows file was created as I can with ls -ltr

```<code>Stage "Code Coverage Tests"
    +ls -ltr /coverage-data/
    total 0
    + script...
    +ls -ltr /coverage-data/myfile

-rw-r--r--  1 jenkins  staff  0 Dec 17 09:25 /coverage-data/myfile

.
.
.
Stage "Code Coverage Scan" skipped due to when conditional
</code>```

Body:
team,

I have my pipeline that runs two stages.

stage 1 creates a file under /coverage-data/myfile and this is emptydir shared volume mounted from pod spec.

stage 2 starts if this file exists.

result: always expression is evaluating to FALSE any hint? I want to start the stage when file is created and present on the node on which this pipeline is runing such that all container in stages has access to this file.

pipeline

pipeline {
    agent {
        label 'label-coverage-cli'
    }

    environment {
        COVERAGE_FILE = fileExists '/coverage-data/myfile'
    }

    stages {
        stage('Code Coverage Tests') {
            steps {
                container('main') {
                        sh '''
                        ls -ltr /coverage-data/
                        unit-tests.sh
                        ls -ltr /coverage-data/myfile
                        '''.stripIndent()
                }
            }
        }
        stage('Code Coverage Scan') {
            when { expression { COVERAGE_FILE == 'true' } }
            steps {
                container('sonar-scan') {
                        sh '''
                        scan.sh
                        '''.stripIndent()
                }
            }
        }
    }
}

pod spec that is mounting shared volume for all containers in all stages to write on and read from as shared-data

apiVersion: v1
kind: Pod
spec:
  imagePullSecrets:
    - name: sec
  volumes:
    - name: shared-data
      emptyDir: {}
  containers:
    - name: main
      image: registry/tci-sonar-scanner:latest
      volumeMounts:
      - name: shared-data
        mountPath: /coverage-data
      command:
        - /sbin/tini
      args:
        - --
        - sleep
        - infinity
    - name: sonar-scanner
      image: registry/sonarqube-scanner:4.7.0.2747
      volumeMounts:
      - name: shared-data
        mountPath: /coverage-data
      securityContext:
        privileged: true
      command:
        - tail
      args:
      - "-f"
      - "/dev/null"

output also shows file was created as I can with ls -ltr

Stage "Code Coverage Tests"
    +ls -ltr /coverage-data/
    total 0
    + script...
    +ls -ltr /coverage-data/myfile

-rw-r--r--  1 jenkins  staff  0 Dec 17 09:25 /coverage-data/myfile

.
.
.
Stage "Code Coverage Scan" skipped due to when conditional


问:
amazon_product_review_scraper returns certificate verify failed
I'm running the following code:

```<code>from amazon_product_review_scraper import amazon_product_review_scraper
review_scraper = amazon_product_review_scraper(amazon_site="amazon.in", product_asin="B098RKWHHZ")
reviews_df = review_scraper.scrape()
reviews_df.head(5)
</code>```

and I get the following:

```<code>SSLError: HTTPSConnectionPool(host='sslproxies.org', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)')))
</code>```

I have installed certifi  but did not help.

Body:
I'm running the following code:

from amazon_product_review_scraper import amazon_product_review_scraper
review_scraper = amazon_product_review_scraper(amazon_site="amazon.in", product_asin="B098RKWHHZ")
reviews_df = review_scraper.scrape()
reviews_df.head(5)

and I get the following:

SSLError: HTTPSConnectionPool(host='sslproxies.org', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)')))

I have installed certifi  but did not help.


问:
NodeJS Puppeteer use active browser
How can i create a new tab at the active browser?

I tried

```<code>  const browser = await puppeteer.launch({
    headless: false,
    executablePath:
      "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
    userDataDir:
      "C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\User Data",
  });
</code>```

giving the userDataDir but it gives an error:

```<code>C:\Users\Administrator\Desktop\api\node_modules\puppeteer-core\lib\cjs\puppeteer\node\BrowserRunner.js:299
            reject(new Error([
                   ^

Error: Failed to launch the browser process!
</code>```

Title: NodeJS Puppeteer use active browser

Body:
How can i create a new tab at the active browser?

I tried

  const browser = await puppeteer.launch({
    headless: false,
    executablePath:
      "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
    userDataDir:
      "C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\User Data",
  });

giving the userDataDir but it gives an error:

C:\Users\Administrator\Desktop\api\node_modules\puppeteer-core\lib\cjs\puppeteer\node\BrowserRunner.js:299
            reject(new Error([
                   ^

Error: Failed to launch the browser process!


问:
zsh: killed mkdir -m 700 -p "$SHELL_SESSION_DIR"
I have upgraded my macOS from Monterey to Ventura and now I am constantly, when opening terminal, getting an error:

```<code>zsh: killed  mkdir -m 700 -p "$SHELL_SESSION_DIR"
</code>```

Then when I run npm script in VSCode, for example with Nodemon package, I get an error:

```<code>$ npm run start

zsh: killed     npm run start
</code>```

or if I run Nodemon:

```<code>$ nodemon server.js

zsh: command not found: nodemon
</code>```

I have tried running:

```<code>brew uninstall git
brew update
brew reinstall pcre2 gettext
brew install git
brew reinstall node
</code>```

but yet problem is still here.

Body:
I have upgraded my macOS from Monterey to Ventura and now I am constantly, when opening terminal, getting an error:

zsh: killed  mkdir -m 700 -p "$SHELL_SESSION_DIR"

Then when I run npm script in VSCode, for example with Nodemon package, I get an error:

$ npm run start

zsh: killed     npm run start

or if I run Nodemon:

$ nodemon server.js

zsh: command not found: nodemon

I have tried running:

brew uninstall git
brew update
brew reinstall pcre2 gettext
brew install git
brew reinstall node

but yet problem is still here.


问:
pyttsx3 makes pauses evere 82 words
I am learning to use pyttsx3 module.

I want to make a continuous speech without any pauses so I deleted all '.' and ',', but pauses are created in what I thought were random places. So dug deeper and figured that it makes a pause every 82 (+/-1 words).

Any idea how to fix it?

Here is my code:

```<code>import pyttsx3

with open('D:\D-Chilldom\QuickMovieRecap\Movie.txt', 'r') as f:
    text = f.read()

text = text.replace('.', '')
text = text.replace(',', '')

# Initialize the TTS engine
engine = pyttsx3.init()

# Set the rate of speech (words per minute)
rate = 250
engine.setProperty('rate', rate)

# Set the volume of the voice
volume = 1
engine.setProperty('volume', volume)

# Set the voice to use
voice_id = "com.apple.speech.synthesis.voice.samantha"
engine.setProperty('voice', voice_id)

engine.save_to_file(text, 'D:/D-Chilldom/QuickMovieRecap/rec/zzzz.mp3')
engine.runAndWait()
</code>```

Title: pyttsx3 makes pauses evere 82 words

Body:
I am learning to use pyttsx3 module.

I want to make a continuous speech without any pauses so I deleted all '.' and ',', but pauses are created in what I thought were random places. So dug deeper and figured that it makes a pause every 82 (+/-1 words).

Any idea how to fix it?

Here is my code:

import pyttsx3

with open('D:\D-Chilldom\QuickMovieRecap\Movie.txt', 'r') as f:
    text = f.read()

text = text.replace('.', '')
text = text.replace(',', '')

# Initialize the TTS engine
engine = pyttsx3.init()

# Set the rate of speech (words per minute)
rate = 250
engine.setProperty('rate', rate)

# Set the volume of the voice
volume = 1
engine.setProperty('volume', volume)

# Set the voice to use
voice_id = "com.apple.speech.synthesis.voice.samantha"
engine.setProperty('voice', voice_id)

engine.save_to_file(text, 'D:/D-Chilldom/QuickMovieRecap/rec/zzzz.mp3')
engine.runAndWait()


问:
Matplotlib Chart border/colouring on x Axis values
Is there a way to add lines/boxes on a matplotlib chart on the x Axis values?

See the image below, this is what I'm trying to do.

If that isn't possible, then is it possible to shade color the box between a specific range? example: Jan - Dec 2020 would be grey, 2021 black, 2022 green.

This would hopefully make it much easier to distinguish the years. Thankyou

```<code>df_orders.set_index('Date').plot.bar()

plt.title('Customer Orders: Discounted Vs Full Price', pad = 10, Fontsize =16)
plt.ylabel("Order Count", labelpad = 10, fontsize=14)
plt.xlabel("Year-Month", labelpad = 20, fontsize=14)

plt.tight_layout()

plt.legend(facecolor='white', fontsize =13,  framealpha=1)

plt.show()
</code>```

Body:
Is there a way to add lines/boxes on a matplotlib chart on the x Axis values?

See the image below, this is what I'm trying to do.

If that isn't possible, then is it possible to shade color the box between a specific range? example: Jan - Dec 2020 would be grey, 2021 black, 2022 green.

This would hopefully make it much easier to distinguish the years. Thankyou

df_orders.set_index('Date').plot.bar()

plt.title('Customer Orders: Discounted Vs Full Price', pad = 10, Fontsize =16)
plt.ylabel("Order Count", labelpad = 10, fontsize=14)
plt.xlabel("Year-Month", labelpad = 20, fontsize=14)

plt.tight_layout()

plt.legend(facecolor='white', fontsize =13,  framealpha=1)

plt.show()


问:
psql password not typing in terminal windows 11
i want to install psql in my terminal for the first time on windows 11 pc,
when i run psql i will get this Password for user Cullkid: .
And when i tried to enter a password, it wouldn't allow me to tyepe anything there.
i am using progreSQL 15

i watched some videos via youtube and saw that progresql request password when installing but mine doesn't give me the option

first i run

```<code>psql --version
</code>```

and it shows me the result.

secondly i run

```<code>psql
</code>```

and it gives me

```<code>Password for user Cullkid:

</code>```

thirdly if i try typing password, it wouldn't typeout anything

if i hit return without introducing a password, then i get this :

```<code>psql: error: connection to server at "localhost" (::1), port 5432 failed: FATAL:password authentication failed for user "Cullkid"
</code>```

Body:
i want to install psql in my terminal for the first time on windows 11 pc,
when i run psql i will get this Password for user Cullkid: .
And when i tried to enter a password, it wouldn't allow me to tyepe anything there.
i am using progreSQL 15

i watched some videos via youtube and saw that progresql request password when installing but mine doesn't give me the option

first i run

psql --version

and it shows me the result.

secondly i run

psql

and it gives me

Password for user Cullkid:

thirdly if i try typing password, it wouldn't typeout anything

if i hit return without introducing a password, then i get this :

psql: error: connection to server at "localhost" (::1), port 5432 failed: FATAL:password authentication failed for user "Cullkid"


问:
Spotipy - Can't add tracks to playlist
I've been trying to create a simple tool that converts apple music playlists to Spotify playlists using web scraping and Spotipy.

I broke each part of this tool into various functions. My function to scrape the apple website and create a playlist works fine but adding the tracks doesn't. It just shows an empty playlist on my Spotify account

This is the function that is supposed to search and add the tracks.

I commented out previous search/query methods.

```<code>def get_spotify_tracks(songs, artists, sp, user_id):
'''
Step 4: Transfer fetched song data
Step 5: Search for song on Spotify
Step 6: Add the songs to the Spotify playlist
'''
list_of_tracks = []
prePlaylist = sp.user_playlists(user=user_id)
playlist = prePlaylist["items"][0]["id"]
for playlist_song, song_artist in zip(songs, artists):
    track_id = sp.search(q='artist:' + song_artist + ' track:' + playlist_song, type='track')

    #track_data = list(f'{playlist_song} by {song_artist}')
    #result = sp.search(q=track_data, )
    #query = f"https://api.spotify.com/v1/serch?query=track%3A{playlist_song}" \
    #        f"+artist%3A{song_artist}&type=track&offset=0&limit=5"

    list_of_tracks.append(track_id["tracks"]["items"][0]["uri"])
    print(list_of_tracks)
query = f"https://api.spotify.com/v1/playlists/{playlist}/tracks"
response = requests.post(
    query,
    data=list_of_tracks,
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
)
return list_of_tracks
</code>```

This is the complete code. Executing main() creates a playlist with the right name and description but no tracks.

```<code>'''
Making a program that converts an Apple music playlist to a Spotify Playlist

Step1: Fetch the Apple music playlist data
Step2: Get Authorization to spotify account
Step3: Create new spotify playlist
Step4: Transfer fetched song data
Step5: Search for song on Spotify
Step6: Add the songs to Spotify playlist
'''

clientid = os.environ['CLIENT_ID']
client_secret = os.environ['CLIENT_SECRET']
token = os.environ['ACCESS_TOKEN']
username = os.environ['USERNAME']
track_list = []
artist_list = []

def get_apple_playlist(URL):
    '''
    Step1: Fetch the Apple music playlist data
    '''
    headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
    "Accept-Language": "en-US,en;q=0.9"
    }
    # pass in apple playlist link
    apple_link = requests.get(URL, headers=headers)
    # Use Beautiful soup to retrieve page html
    playlist_soup = BeautifulSoup(apple_link.content, "lxml")

    # Find various playlist info with Beautiful soup
    playlist_name = playlist_soup.find('h1', attrs={'data-testid': 'non-editable-product-title'}).get_text(strip=True)

    playlist_description = playlist_soup.find('p', attrs={'data-testid': 'truncate-text'}).get_text(strip=True)

    songs_raw = playlist_soup.find_all("div", class_="songs-list-row__song-name")

    artists_raw = playlist_soup.find_all("div", class_="songs-list__col songs-list__col--artist typography-body")
    #song_art = [playlist_soup.find_all("div picture source", type="image/jpeg").get_]

    #Refining data
    for song in songs_raw:
        track_list.append(song.get_text(strip=True))

    for artist in artists_raw:
        artist_list.append(artist.get_text(strip=True))

    return playlist_name, playlist_description, track_list, artist_list

def spotify_playlist(playlist_name, playlist_description):
    '''
    Step 2: Get Authorization to spotify account
    Step 3: Create new spotify playlist
    '''
    token = SpotifyOAuth(client_id=clientid,
                         client_secret=client_secret,
                         redirect_uri="http://127.0.0.1:8080/",
                         scope="playlist-modify-public")

    sp = spotipy.Spotify(auth_manager=token)
    user_id = sp.current_user()['id']

    new_playlist = sp.user_playlist_create(user=user_id, name=playlist_name, description=playlist_description, public=True)
    playlist_id = new_playlist['id']

    return playlist_id, user_id, sp

def get_spotify_tracks(songs, artists, sp, user_id):
    '''
    Step 4: Transfer fetched song data
    Step 5: Search for song on Spotify
    Step 6: Add the songs to the Spotify playlist
    '''
    list_of_tracks = []
    prePlaylist = sp.user_playlists(user=user_id)
    playlist = prePlaylist["items"][0]["id"]
    for playlist_song, song_artist in zip(songs, artists):
        track_id = sp.search(q='artist:' + song_artist + ' track:' + playlist_song, type='track')

        #track_data = list(f'{playlist_song} by {song_artist}')
        #result = sp.search(q=track_data, )
        #query = f"https://api.spotify.com/v1/serch?query=track%3A{playlist_song}" \
        #        f"+artist%3A{song_artist}&type=track&offset=0&limit=5"

        list_of_tracks.append(track_id["tracks"]["items"][0]["uri"])
        print(list_of_tracks)
    query = f"https://api.spotify.com/v1/playlists/{playlist}/tracks"
    response = requests.post(
        query,
        data=list_of_tracks,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {token}"
        }
    )
    return list_of_tracks

def main(url):
    '''
    Execution
    '''
    playlist_data = get_apple_playlist(url)
    playlist = spotify_playlist(playlist_data[0], playlist_data[1])
    tracks = get_spotify_tracks(playlist_data[2], playlist_data[3], playlist[2], playlist[1])

main("https://music.apple.com/ng/playlist/angry/pl.u-PDbYmE4Ie084DqR")
</code>```

Title: Spotipy - Can't add tracks to playlist

Body:
I've been trying to create a simple tool that converts apple music playlists to Spotify playlists using web scraping and Spotipy.

I broke each part of this tool into various functions. My function to scrape the apple website and create a playlist works fine but adding the tracks doesn't. It just shows an empty playlist on my Spotify account

This is the function that is supposed to search and add the tracks.

I commented out previous search/query methods.

def get_spotify_tracks(songs, artists, sp, user_id):
'''
Step 4: Transfer fetched song data
Step 5: Search for song on Spotify
Step 6: Add the songs to the Spotify playlist
'''
list_of_tracks = []
prePlaylist = sp.user_playlists(user=user_id)
playlist = prePlaylist["items"][0]["id"]
for playlist_song, song_artist in zip(songs, artists):
    track_id = sp.search(q='artist:' + song_artist + ' track:' + playlist_song, type='track')

    #track_data = list(f'{playlist_song} by {song_artist}')
    #result = sp.search(q=track_data, )
    #query = f"https://api.spotify.com/v1/serch?query=track%3A{playlist_song}" \
    #        f"+artist%3A{song_artist}&type=track&offset=0&limit=5"

    list_of_tracks.append(track_id["tracks"]["items"][0]["uri"])
    print(list_of_tracks)
query = f"https://api.spotify.com/v1/playlists/{playlist}/tracks"
response = requests.post(
    query,
    data=list_of_tracks,
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
)
return list_of_tracks

This is the complete code. Executing main() creates a playlist with the right name and description but no tracks.

'''
Making a program that converts an Apple music playlist to a Spotify Playlist

Step1: Fetch the Apple music playlist data
Step2: Get Authorization to spotify account
Step3: Create new spotify playlist
Step4: Transfer fetched song data
Step5: Search for song on Spotify
Step6: Add the songs to Spotify playlist
'''

clientid = os.environ['CLIENT_ID']
client_secret = os.environ['CLIENT_SECRET']
token = os.environ['ACCESS_TOKEN']
username = os.environ['USERNAME']
track_list = []
artist_list = []

def get_apple_playlist(URL):
    '''
    Step1: Fetch the Apple music playlist data
    '''
    headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
    "Accept-Language": "en-US,en;q=0.9"
    }
    # pass in apple playlist link
    apple_link = requests.get(URL, headers=headers)
    # Use Beautiful soup to retrieve page html
    playlist_soup = BeautifulSoup(apple_link.content, "lxml")

    # Find various playlist info with Beautiful soup
    playlist_name = playlist_soup.find('h1', attrs={'data-testid': 'non-editable-product-title'}).get_text(strip=True)

    playlist_description = playlist_soup.find('p', attrs={'data-testid': 'truncate-text'}).get_text(strip=True)

    songs_raw = playlist_soup.find_all("div", class_="songs-list-row__song-name")

    artists_raw = playlist_soup.find_all("div", class_="songs-list__col songs-list__col--artist typography-body")
    #song_art = [playlist_soup.find_all("div picture source", type="image/jpeg").get_]

    #Refining data
    for song in songs_raw:
        track_list.append(song.get_text(strip=True))

    for artist in artists_raw:
        artist_list.append(artist.get_text(strip=True))

    return playlist_name, playlist_description, track_list, artist_list

def spotify_playlist(playlist_name, playlist_description):
    '''
    Step 2: Get Authorization to spotify account
    Step 3: Create new spotify playlist
    '''
    token = SpotifyOAuth(client_id=clientid,
                         client_secret=client_secret,
                         redirect_uri="http://127.0.0.1:8080/",
                         scope="playlist-modify-public")

    sp = spotipy.Spotify(auth_manager=token)
    user_id = sp.current_user()['id']

    new_playlist = sp.user_playlist_create(user=user_id, name=playlist_name, description=playlist_description, public=True)
    playlist_id = new_playlist['id']

    return playlist_id, user_id, sp

def get_spotify_tracks(songs, artists, sp, user_id):
    '''
    Step 4: Transfer fetched song data
    Step 5: Search for song on Spotify
    Step 6: Add the songs to the Spotify playlist
    '''
    list_of_tracks = []
    prePlaylist = sp.user_playlists(user=user_id)
    playlist = prePlaylist["items"][0]["id"]
    for playlist_song, song_artist in zip(songs, artists):
        track_id = sp.search(q='artist:' + song_artist + ' track:' + playlist_song, type='track')

        #track_data = list(f'{playlist_song} by {song_artist}')
        #result = sp.search(q=track_data, )
        #query = f"https://api.spotify.com/v1/serch?query=track%3A{playlist_song}" \
        #        f"+artist%3A{song_artist}&type=track&offset=0&limit=5"

        list_of_tracks.append(track_id["tracks"]["items"][0]["uri"])
        print(list_of_tracks)
    query = f"https://api.spotify.com/v1/playlists/{playlist}/tracks"
    response = requests.post(
        query,
        data=list_of_tracks,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {token}"
        }
    )
    return list_of_tracks

def main(url):
    '''
    Execution
    '''
    playlist_data = get_apple_playlist(url)
    playlist = spotify_playlist(playlist_data[0], playlist_data[1])
    tracks = get_spotify_tracks(playlist_data[2], playlist_data[3], playlist[2], playlist[1])

main("https://music.apple.com/ng/playlist/angry/pl.u-PDbYmE4Ie084DqR")