问:
Issue connecting to databases using jaydebeapi
Using Jupyter notebook through Anaconda in order to connect python to databases.

Tried running this code in the notebook. I am also in the correct environment in anaconda as well

Any idea on how to solve this issue?

Tried to run this code in Jupyter Notebook:

```<code>import jaydebeapi

connect = jaydebeapi.connect(
                     'com.ibm.db2.jcc.DB2Driver',
                     'jdbc:db2://he3qlxvtdbs351.fhlmc.com:50001/DB2QLTY',
                     ['f408195', pw],
                    'C:/JDBC/db2jcc.jar')
</code>```

This was the result :
JVMNotFoundException: No JVM shared library file (jvm.dll) found. Try setting up the JAVA_HOME environment variable properly

Any advice on how to get past this issue? Thanks.

Body:
Using Jupyter notebook through Anaconda in order to connect python to databases.

Tried running this code in the notebook. I am also in the correct environment in anaconda as well

Any idea on how to solve this issue?

Tried to run this code in Jupyter Notebook:

import jaydebeapi

connect = jaydebeapi.connect(
                     'com.ibm.db2.jcc.DB2Driver',
                     'jdbc:db2://he3qlxvtdbs351.fhlmc.com:50001/DB2QLTY',
                     ['f408195', pw],
                    'C:/JDBC/db2jcc.jar')

This was the result :
JVMNotFoundException: No JVM shared library file (jvm.dll) found. Try setting up the JAVA_HOME environment variable properly

Any advice on how to get past this issue? Thanks.


来源: stackexchange

问:
Angular auth problem, auth.service is not working
I am new to the angular, I am following a course and there is aerror sshowing follows
Module not found: Error: Package path ./compat is not exported from package D:\EcommeceWeb\App1\oshop\node_modules\firebase (see exports field in D:\EcommeceWeb\App1\oshop\node_modules\firebase\package.json)
and
auth.service.ts:16:49 - error TS2339: Property 'auth' does not exist on type 'typeof import("D:/EcommeceWeb/App1/oshop/node_modules/firebase/compat/index")'.

16 this.afAuth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());

I need to slove this hear is my auth.service.ts

```<code>import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import * as firebase from 'firebase/compat';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import '@firebase/auth';
import { initializeApp } from 'firebase/app';
import { Observable } from 'rxjs/internal/Observable';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  user$: Observable<firebase.User>
  constructor(private afAuth : AngularFireAuth) {
    this.user$=afAuth.authState;

  }

  login(){
    this.afAuth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());

  }
  logout(){
    this.afAuth.signOut();

  }

}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to the angular, I am following a course and there is aerror sshowing follows
Module not found: Error: Package path ./compat is not exported from package D:\EcommeceWeb\App1\oshop\node_modules\firebase (see exports field in D:\EcommeceWeb\App1\oshop\node_modules\firebase\package.json)
and
auth.service.ts:16:49 - error TS2339: Property 'auth' does not exist on type 'typeof import("D:/EcommeceWeb/App1/oshop/node_modules/firebase/compat/index")'.

16 this.afAuth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());

I need to slove this hear is my auth.service.ts

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import * as firebase from 'firebase/compat';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import '@firebase/auth';
import { initializeApp } from 'firebase/app';
import { Observable } from 'rxjs/internal/Observable';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  user$: Observable<firebase.User>
  constructor(private afAuth : AngularFireAuth) {
    this.user$=afAuth.authState;

  }

  login(){
    this.afAuth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());

  }
  logout(){
    this.afAuth.signOut();

  }

}


问:
How to Add Time Input to Sheets Depending on User Dropdown Selection
I'm wondering how can I achieve the following by modifying my existing code.

Add the time input into Time Activated Column (Column B) when Activate dropdown is selected

Add the time input when user selected Deactivate, it should be added under column C

An error message when column C is Blank and user added new activate entry

Add time duration in the HTML form when active

HTML Dropdown is Activate and Deactivate.

Here's my Sheet and form looks like.

GS

```<code>function saveData(obj) {

    let sheet = ss.getSheetByName('Feedback');
    let dateString = Utilities.formatDate(new Date(), "GMT-5", "MM/dd/yyyy HH:mm:ss");
    //Saving records to Google Sheet
    sheet.appendRow([
      obj.data1,
      obj.data2,
      dateString,
      Session.getActiveUser().getUsername()
      ]);

return true;
}
</code>```

JS

```<code><script>
  document.getElementById('submit').addEventListener('click',submitForm);

function submitForm(){
  let input1 = document.getElementById('input1');
  let input2 = document.getElementById('input2');

  let obj = {
    data1 : input1.value,
    data2 : input2.value

  };
  if(input1.value  == "" || input2.value ==""){
  Swal.fire({
  icon: 'info',
  title: 'Oops. Please fill out the blank fields!'

})
}
 else{

Swal.fire({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  icon: 'warning',
  showCancelButton: true,
  showDenyButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, enact this!',
  denyButtonText: 'No, revert this!'
}).then((result) => {
  if (result.isConfirmed) {
     google.script.run
      .withSuccessHandler( () => {
      input1.value = "";
      input2.value = "";
       } )
       .saveData(obj);
        $("#input2").val('');
        $("#input1").prop("selectedIndex", 0);

    Swal.fire({
  icon: 'success',
//  width: 600,
  title: 'Message!',
  text: 'Draft communication has been sent to your personal email!',
  confirmButtonText:
    '<i class="fa fa-thumbs-up"></i> Awesome!',
  confirmButtonAriaLabel: 'Thumbs up, great!',
})
  }
  else if (result.isDenied) {
    Swal.fire('Changes are not saved', '', 'info')
    input1.value = "";
    input2.value = "";
  }
})

};

  };
</script>
</code>```

HTML

```<code>   <div class="header">
  <h1>Activation tool</h1>
  <p>.</p>
</div>

        <div class="frame">
          <h3 class-="mb-4">Enactment Tool</h3>

          <label for="need" class="form-label">Enactment Request: *</label>
          <div class="mb-4">
            <select id="input1" class="form-control">
                          <option value="" selected disabled>--Select Your Request--</option>
                          <option>Activate</option>
                          <option>Deactivate</option>
                    </select>
          </div>
          <label for="time" class="form-label">Time: *</label>
          <div class="mb-4">
            <input id="input2" class="form-control" type="datetime-local" name="time">
          </div>
          <div>
            <button id="submit" class="btn btn-primary"> Send Email </button>
          </div>
        </div>
</code>```

Body:
I'm wondering how can I achieve the following by modifying my existing code.

Add the time input into Time Activated Column (Column B) when Activate dropdown is selected

Add the time input when user selected Deactivate, it should be added under column C

An error message when column C is Blank and user added new activate entry

Add time duration in the HTML form when active

HTML Dropdown is Activate and Deactivate.

Here's my Sheet and form looks like.

GS

function saveData(obj) {

    let sheet = ss.getSheetByName('Feedback');
    let dateString = Utilities.formatDate(new Date(), "GMT-5", "MM/dd/yyyy HH:mm:ss");
    //Saving records to Google Sheet
    sheet.appendRow([
      obj.data1,
      obj.data2,
      dateString,
      Session.getActiveUser().getUsername()
      ]);

return true;
}

JS

HTML

Activation tool

.

Enactment Tool

          Enactment Request: *

            <select id="input1" class="form-control">
                          <option value="" selected disabled>--Select Your Request--</option>
                          <option>Activate</option>
                          <option>Deactivate</option>
                    </select>

          Time: *

            <input id="input2" class="form-control" type="datetime-local" name="time">

            <button id="submit" class="btn btn-primary"> Send Email </button>


问:
Problems with the tkinter library in ubuntu with the transparent option
Some time ago I made a project in python which executed the dancing bowser gif at the bottom of my computer. This is done in windows. My problem is that when I switch to linux, for which I read the transparent property for tkinter for linux it does not work, so I would like to know some idea to carry out this project but for linux

```<code>root.wm_attributes('-transparentcolor', '#F0F0F0')
</code>```

That is the line that does not let me run in Ubuntu
Here is the link of the project on github: https://github.com/Programacion315/Virtual_assistant_Browser

Body:
Some time ago I made a project in python which executed the dancing bowser gif at the bottom of my computer. This is done in windows. My problem is that when I switch to linux, for which I read the transparent property for tkinter for linux it does not work, so I would like to know some idea to carry out this project but for linux

root.wm_attributes('-transparentcolor', '#F0F0F0')

That is the line that does not let me run in Ubuntu
Here is the link of the project on github: https://github.com/Programacion315/Virtual_assistant_Browser


问:
Best practice for storing token/credential using cli tools
I want to make cli tools just like firebase or github using yargs. so firebase does have this command "firebase login". I wonder how and where do they store the token/credential. If it's web browser I could store it in the cookie or local storage but using cli I don't have any clue.

```<code>yargs(Deno.args)
  .command('login', 'make a post request to my oauth server', (yargs: any) => {
     OauthClient.post({ username: yargs.username, password: yargs.password })
                .then(r => {
                   // what to do with this token????
                   const token = extractToken(r.headers.authorization)
                })
  })
  .strictCommands()
  .demandCommand(1)
  .parse()
</code>```

Body:
I want to make cli tools just like firebase or github using yargs. so firebase does have this command "firebase login". I wonder how and where do they store the token/credential. If it's web browser I could store it in the cookie or local storage but using cli I don't have any clue.

yargs(Deno.args)
  .command('login', 'make a post request to my oauth server', (yargs: any) => {
     OauthClient.post({ username: yargs.username, password: yargs.password })
                .then(r => {
                   // what to do with this token????
                   const token = extractToken(r.headers.authorization)
                })
  })
  .strictCommands()
  .demandCommand(1)
  .parse()


问:
Johansen’s Cointegration Test in r
I don't know how to find the number of lags from the VARselect when applying the Johansen's conintegration test in r. Does anyone help me to solve it?

Here is my code:

```<code>library(vars)
library(tsDyn)

# Simulate the data
data <- runif(100)

# i. Select the number of lags in the VAR model with 'VARselect' from vars
lag_num <- VARselect(data, lag.max = 12, type = "const")

# ii. Estimate a VECM with 'VECOM' from tsDyn
vecm <- VECM(gbp, estim = "ML", lag = length(lag_num)-1)
</code>```

Also, I have two more questions.

Why does the Johansen’s test rely on the maximum likelihood estimator?

Can I choose a specification for the deterministic component other than an unrestricted constant?

Thanks a lot.

Title: Johansen’s Cointegration Test in r

Body:
I don't know how to find the number of lags from the VARselect when applying the Johansen's conintegration test in r. Does anyone help me to solve it?

Here is my code:

library(vars)
library(tsDyn)

# Simulate the data
data <- runif(100)

# i. Select the number of lags in the VAR model with 'VARselect' from vars
lag_num <- VARselect(data, lag.max = 12, type = "const")

# ii. Estimate a VECM with 'VECOM' from tsDyn
vecm <- VECM(gbp, estim = "ML", lag = length(lag_num)-1)

Also, I have two more questions.

Why does the Johansen’s test rely on the maximum likelihood estimator?

Can I choose a specification for the deterministic component other than an unrestricted constant?

Thanks a lot.


问:
ERR_CONNECTION_REFUSED Laravel 9 deployed in the AWS Elastic Beanstalk
I have deployed Laravel 9 application in AWS Elastic Beanstalk. However, when I access the login page, I get the following error.

I have taken the following steps to solve the problem without any success.

I did run the npm run build to build the assets.

Then I installed composer require fruitcake/laravel-cors and included \Fruitcake\Cors\HandleCors::class in the Kernal.php file.

And here is the cors.php in the config folder.

```<code><?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];
</code>```

Load balancer configurations

Is there anything I'm doing wrong? Any help is highly appreciated.

Body:
I have deployed Laravel 9 application in AWS Elastic Beanstalk. However, when I access the login page, I get the following error.

I have taken the following steps to solve the problem without any success.

I did run the npm run build to build the assets.

Then I installed composer require fruitcake/laravel-cors and included \Fruitcake\Cors\HandleCors::class in the Kernal.php file.

And here is the cors.php in the config folder.

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];

Load balancer configurations

Is there anything I'm doing wrong? Any help is highly appreciated.


问:
Unexpected result when convert Dataframe to Pivot_table in pandas
I have a dataframe read from a csv file. I wanna convert it to a pivot_table and it causing some unexpected list in value like this:
Code convert dataframe to pivot_table

The original data:
Original data

Unexpected array in result:
Unexpected result

I am trying to convert a csv stocks price in time range as above image to the format with column are stock symbols and row are days.

Someone please help me to fix this problem or any or any other approach to reach my expect.

Thank you!


问:
Refresh cache after hitting first request to the application (spring boot)
We have one requirement,where we have cache it needs to get updated from db every day when the application receives first request
This problem is similar to this
Reload/Refresh cache in spring boot

I have tried similar to this,but it needs to get updated on the first request in a day

Reload/Refresh cache in spring boot


问:
Why can't i activate my virtual env in cmd?
I created a venv using "python -m venv env" and I'm trying to activate it but it kept showing "The system cannot find the path specified"

I tried activating using env\Scripts\activate
please any idea on  how i can solve this?

i use python 3.11, window 11


问:
Error : increase sysctl fs.aio-max-nr while configuring SQL Server in Ubuntu
I have successfully installed SQL Server in Ubuntu 20.04.5. But while configuring SQL Server running the command /opt/mssql/bin/mssql-conf setup and answering to all questions, I got the following error

```<code>    The following diagnostic information is available:

         Reason: 0x00000003
         Status: 0x0000000b
        Message: Unable to create a new asynchronous I/O context. Please increase sysctl fs.aio-max-nr
          Stack:
                 IP               Function
                 ---------------- --------------------------------------
                 0000555a422995b2 <unknown>
                 0000555a42298fd0 <unknown>
                 0000555a422032af <unknown>
                 0000555a422b1d11 <unknown>
                 0000555a422b1af8 <unknown>
                 0000555a42253096 <unknown>
                 0000555a4225386e <unknown>
                 0000555a422bf0ca <unknown>
                 0000555a421fa8ad <unknown>
                 00007f7ed3521083 __libc_start_main+0xf3
                 0000555a421fa77e <unknown>
        Process: 13543 - sqlservr
         Thread: 13543
    Instance Id: e13b426f-6907-4503-b340-4d6575d62a76
       Crash Id: 48813d78-4d11-482e-8318-bbd3b504e5ab
    Build stamp: d81e9b6de06534e649bd57dd609aa3050f5e380f361b7f8a80a80eeb71e7422c
Distribution: Ubuntu 20.04.5 LTS
     Processors: 2
   Total Memory: 270359584768 bytes
      Timestamp: Tue Dec  6 03:58:53 2022
     Last errno: 11
Last errno text: Resource temporarily unavailable
Capturing a dump of 13543
sqlservr: utils.cpp:561: uintptr_t GetEndOfLibOSVmRange(): Assertion `GetGlobals()->GetStatics()->IsLibOSVmmRangeEndValid()' failed.
</code>```

Any help will be greatly appreciated

Body:
I have successfully installed SQL Server in Ubuntu 20.04.5. But while configuring SQL Server running the command /opt/mssql/bin/mssql-conf setup and answering to all questions, I got the following error

    The following diagnostic information is available:

         Reason: 0x00000003
         Status: 0x0000000b
        Message: Unable to create a new asynchronous I/O context. Please increase sysctl fs.aio-max-nr
          Stack:
                 IP               Function
                 ---------------- --------------------------------------
                 0000555a422995b2 <unknown>
                 0000555a42298fd0 <unknown>
                 0000555a422032af <unknown>
                 0000555a422b1d11 <unknown>
                 0000555a422b1af8 <unknown>
                 0000555a42253096 <unknown>
                 0000555a4225386e <unknown>
                 0000555a422bf0ca <unknown>
                 0000555a421fa8ad <unknown>
                 00007f7ed3521083 __libc_start_main+0xf3
                 0000555a421fa77e <unknown>
        Process: 13543 - sqlservr
         Thread: 13543
    Instance Id: e13b426f-6907-4503-b340-4d6575d62a76
       Crash Id: 48813d78-4d11-482e-8318-bbd3b504e5ab
    Build stamp: d81e9b6de06534e649bd57dd609aa3050f5e380f361b7f8a80a80eeb71e7422c
Distribution: Ubuntu 20.04.5 LTS
     Processors: 2
   Total Memory: 270359584768 bytes
      Timestamp: Tue Dec  6 03:58:53 2022
     Last errno: 11
Last errno text: Resource temporarily unavailable
Capturing a dump of 13543
sqlservr: utils.cpp:561: uintptr_t GetEndOfLibOSVmRange(): Assertion `GetGlobals()->GetStatics()->IsLibOSVmmRangeEndValid()' failed.

Any help will be greatly appreciated


问:
Android Studio no Console output with Dual debug type?
Recently started using C++ in a Java Android app with CMake and Gradle on Windows (based on https://developer.android.com/studio/projects/gradle-external-native-builds).
It works great, but now Java logs are not showing up in the Console when debugging the app. When it starts, it shows both an app and app-java process and neither of them show anything expected (such as touch events). Any way to fix this?

app:

```<code>12/05 20:12:12: Launching 'app' on samsung.
Install successfully finished in 6 s 531 ms.
$ adb shell am start -n "com.agragps.agragps/com.agragps.agragps.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.agragps.agragps
Connecting to com.agragps.agragps
Now Launching Native Debug Session
$ adb shell cat /data/local/tmp/lldb-server | run-as com.agragps.agragps sh -c 'cat > /data/data/com.agragps.agragps/lldb/bin/lldb-server && chmod 700 /data/data/com.agragps.agragps/lldb/bin/lldb-server'
$ adb shell cat /data/local/tmp/start_lldb_server.sh | run-as com.agragps.agragps sh -c 'cat > /data/data/com.agragps.agragps/lldb/bin/start_lldb_server.sh && chmod 700 /data/data/com.agragps.agragps/lldb/bin/start_lldb_server.sh'
Starting LLDB server: /data/data/com.agragps.agragps/lldb/bin/start_lldb_server.sh /data/data/com.agragps.agragps/lldb unix-abstract /com.agragps.agragps-0 platform-1670296340839.sock "lldb process:gdb-remote packets"
Debugger attached to process 18174
</code>```

app-java:

```<code>Connected to the target VM, address: 'localhost:53082', transport: 'socket'
</code>```

Body:
Recently started using C++ in a Java Android app with CMake and Gradle on Windows (based on https://developer.android.com/studio/projects/gradle-external-native-builds).
It works great, but now Java logs are not showing up in the Console when debugging the app. When it starts, it shows both an app and app-java process and neither of them show anything expected (such as touch events). Any way to fix this?

app:

12/05 20:12:12: Launching 'app' on samsung.
Install successfully finished in 6 s 531 ms.
$ adb shell am start -n "com.agragps.agragps/com.agragps.agragps.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.agragps.agragps
Connecting to com.agragps.agragps
Now Launching Native Debug Session
$ adb shell cat /data/local/tmp/lldb-server | run-as com.agragps.agragps sh -c 'cat > /data/data/com.agragps.agragps/lldb/bin/lldb-server && chmod 700 /data/data/com.agragps.agragps/lldb/bin/lldb-server'
$ adb shell cat /data/local/tmp/start_lldb_server.sh | run-as com.agragps.agragps sh -c 'cat > /data/data/com.agragps.agragps/lldb/bin/start_lldb_server.sh && chmod 700 /data/data/com.agragps.agragps/lldb/bin/start_lldb_server.sh'
Starting LLDB server: /data/data/com.agragps.agragps/lldb/bin/start_lldb_server.sh /data/data/com.agragps.agragps/lldb unix-abstract /com.agragps.agragps-0 platform-1670296340839.sock "lldb process:gdb-remote packets"
Debugger attached to process 18174

app-java:

Connected to the target VM, address: 'localhost:53082', transport: 'socket'


问:
"<class 'PermissionError'> [Errno 13] Permission denied: 'party.csv' Terminating program." error as a result of trying to modify the file
Error was caused by the command del

This is the cvs file

Code (python 3)

```<code>#!/usr/bin/env python3

import csv
import sys

FILENAME = "party.csv"

def exit_program():
    print("Terminating program.")
    sys.exit()

def read_party():
    try:
        party = []
        with open(FILENAME, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                party.append(row)
        return party
    except FileNotFoundError as e:
        return party
    except Exception as e:
        print(type(e), e)
        exit_program()

def write_party(party):
    try:
        with open(FILENAME, "w", newline="") as file:
            writer = csv.writer(file)
            writer.writerows(party)
    except OSError as e:
        print(type(e), e)
        exit_program()
    except Exception as e:
        print(type(e), e)
        exit_program()

def list_party(party):
    for i, party in enumerate(party, start=1):
        print(f"{i}. {party[0]} --{party[1]}-- ({party[2]}) {party[3]}")
    print()

def add_party(party):
    #name = get_name
    #member_guest = get_member_guest
    name = input("Name: ")
    member_guest = input("Member or Guest: ")
    food = input(" Chicken entre  Beef entre  Vegetarian meal: ")

    while True:
        try:
            fees = int(input("Fees: "))
        except ValueError:
            print("Invalid integer. Please try again.")
            continue
        if fees <= 0:
            print("Fees must be greater than zero. Please try again.")
            continue
        else:
            break
    party_list = [name, member_guest, food, fees]
    party.append(party_list)
    write_party(party)
    print(f"{name} was added.\n")

def delete_party(party):
    while True:
        try:
            number = int(input("Number: "))
        except ValueError:
            print("Invalid integer. Please try again.")
            continue
        if number < 1 or number > len(party):
            print("There is no member with that number. Please try again.")
        else:
            break
    party_pop = party.pop(number - 1)
    write_party(party_pop)
    print(f"{party[0]} was deleted.\n")

def display_menu():
    print("The Party List Program")
    print()
    print("COMMAND MENU")
    print("list - List all members and guests")
    print("add -  Add a member to the list")
    print("del -  Remove a member from the list")
    print("exit - Exit program")
    print()

def main():
    display_menu()
    party = read_party()

    while True:
        command = input("Command: ")
        if command.lower() == "list":
            list_party(party)
        elif command.lower() == "add":
            add_party(party)
        elif command.lower() == "del":
            delete_party(party)
        elif command.lower() == "exit":
            break
        else:
            print("Not a valid command. Please try again.\n")
    print("Bye!")

if __name__ == "__main__":
    main()

</code>```

I was testing the code's functionality, everything but the del had been tested, so when I went to test del to delete line 3 I got an error that shut down the program, I'm not really sure why, it might be something small that stands out that I simply haven't noticed, either way I'd appreciate your help.

Body:
Error was caused by the command del

This is the cvs file

Code (python 3)

#!/usr/bin/env python3

import csv
import sys

FILENAME = "party.csv"

def exit_program():
    print("Terminating program.")
    sys.exit()

def read_party():
    try:
        party = []
        with open(FILENAME, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                party.append(row)
        return party
    except FileNotFoundError as e:
        return party
    except Exception as e:
        print(type(e), e)
        exit_program()

def write_party(party):
    try:
        with open(FILENAME, "w", newline="") as file:
            writer = csv.writer(file)
            writer.writerows(party)
    except OSError as e:
        print(type(e), e)
        exit_program()
    except Exception as e:
        print(type(e), e)
        exit_program()

def list_party(party):
    for i, party in enumerate(party, start=1):
        print(f"{i}. {party[0]} --{party[1]}-- ({party[2]}) {party[3]}")
    print()

def add_party(party):
    #name = get_name
    #member_guest = get_member_guest
    name = input("Name: ")
    member_guest = input("Member or Guest: ")
    food = input(" Chicken entre  Beef entre  Vegetarian meal: ")

    while True:
        try:
            fees = int(input("Fees: "))
        except ValueError:
            print("Invalid integer. Please try again.")
            continue
        if fees <= 0:
            print("Fees must be greater than zero. Please try again.")
            continue
        else:
            break
    party_list = [name, member_guest, food, fees]
    party.append(party_list)
    write_party(party)
    print(f"{name} was added.\n")

def delete_party(party):
    while True:
        try:
            number = int(input("Number: "))
        except ValueError:
            print("Invalid integer. Please try again.")
            continue
        if number < 1 or number > len(party):
            print("There is no member with that number. Please try again.")
        else:
            break
    party_pop = party.pop(number - 1)
    write_party(party_pop)
    print(f"{party[0]} was deleted.\n")

def display_menu():
    print("The Party List Program")
    print()
    print("COMMAND MENU")
    print("list - List all members and guests")
    print("add -  Add a member to the list")
    print("del -  Remove a member from the list")
    print("exit - Exit program")
    print()

def main():
    display_menu()
    party = read_party()

    while True:
        command = input("Command: ")
        if command.lower() == "list":
            list_party(party)
        elif command.lower() == "add":
            add_party(party)
        elif command.lower() == "del":
            delete_party(party)
        elif command.lower() == "exit":
            break
        else:
            print("Not a valid command. Please try again.\n")
    print("Bye!")

if __name__ == "__main__":
    main()

I was testing the code's functionality, everything but the del had been tested, so when I went to test del to delete line 3 I got an error that shut down the program, I'm not really sure why, it might be something small that stands out that I simply haven't noticed, either way I'd appreciate your help.


问:
SIGABRT when calling mono_runtime_object_init
I am relatively new to C++, and have copied some code from a live stream to get started with embedding C# mono into my game engine.

I have created a C# script:

```<code>using System;

namespace Neutron {
    public class Main {
        public float FloatVar { get; set; }

        public Main() {
            Console.WriteLine("Main constructor");
        }

        public void PrintMessage() {
            Console.WriteLine("Hello World from C#!");
        }

        public void PrintCustomMessage(string message) {
            Console.WriteLine($"C# says: {message}");
        }
    }
}
</code>```

and built it to
../Sandbox/Sandbox/bin/Debug/Sandbox.dll (which i have verified within the c++ program that I am embedding it into)

when i call mono_runtime_object_init passing the MonoObject* created from calling mono_object_new (I have verified that it doesnt return a nullptr)

The following error occurs:
* Assertion at object.c:116, condition `is_ok (error)' not met, function:mono_runtime_object_init, (null) assembly:/usr/lib/mono/4.5/mscorlib.dll type:TypeInitializationException member:(null)
Followed by a long stack trace.

Here are my relavent files:

ScriptingEngine.cpp (See the InitMono function towards the bottom)

```<code>//
// Created by aw1lt on 05/12/22.
//

#include "ScriptingEngine.h"
#include "Logger.h"

#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
#include <fstream>

namespace Neutron {

    struct ScriptEngineData {
        MonoDomain* RootDomain = nullptr;
        MonoDomain* AppDomain = nullptr;
        MonoAssembly* CoreAssembly = nullptr;
    };

    char* ReadBytes(const std::string& filepath, uint32_t* outSize) {
        std::ifstream stream(filepath, std::ios::binary | std::ios::ate);

        if (!stream) {
            // Failed to open the file
            return nullptr;
        }

        std::streampos end = stream.tellg();
        stream.seekg(0, std::ios::beg);
        uint32_t size = end - stream.tellg();

        if (size == 0) {
            // File is empty
            return nullptr;
        }

        char* buffer = new char[size];
        stream.read((char*)buffer, size);
        stream.close();

        *outSize = size;
        return buffer;
    }

    MonoAssembly* LoadCSharpAssembly(const std::string& assemblyPath) {
        uint32_t fileSize = 0;
        char* fileData = ReadBytes(assemblyPath, &fileSize);

        // NOTE: We can't use this image for anything other than loading the assembly because this image doesn't have a reference to the assembly
        MonoImageOpenStatus status;
        MonoImage* image = mono_image_open_from_data_full(fileData, fileSize, 1, &status, 0);

        if (status != MONO_IMAGE_OK) {
            const char* errorMessage = mono_image_strerror(status);
            Logger::Crit(errorMessage);
            return nullptr;
        }

        MonoAssembly* assembly = mono_assembly_load_from_full(image, assemblyPath.c_str(), &status, 0);
        mono_image_close(image);

        // Don't forget to free the file data
        delete[] fileData;

        return assembly;
    }

    void PrintAssemblyTypes(MonoAssembly* assembly) {
        MonoImage* image = mono_assembly_get_image(assembly);
        const MonoTableInfo* typeDefinitionsTable = mono_image_get_table_info(image, MONO_TABLE_TYPEDEF);
        int32_t numTypes = mono_table_info_get_rows(typeDefinitionsTable);

        for (int32_t i = 0; i < numTypes; i++) {
            uint32_t cols[MONO_TYPEDEF_SIZE];
            mono_metadata_decode_row(typeDefinitionsTable, i, cols, MONO_TYPEDEF_SIZE);

            const char* nameSpace = mono_metadata_string_heap(image, cols[MONO_TYPEDEF_NAMESPACE]);
            const char* name = mono_metadata_string_heap(image, cols[MONO_TYPEDEF_NAME]);

            Logger::Log(std::string(nameSpace) + "." + name);
        }
    }

    static ScriptEngineData* s_Data;

    void ScriptingEngine::Init() {
        s_Data = new ScriptEngineData();

        InitMono();
    }

    void ScriptingEngine::Shutdown() {
        delete s_Data;
    }

    void ScriptingEngine::InitMono(std::string path) {
        MonoDomain* rootDomain = mono_jit_init("NeutronJITRuntime");
        Logger::Assert(rootDomain != nullptr);

        //system(("cat " + path).c_str());

        // Store the root domain pointer
        s_Data->RootDomain = rootDomain;

        // Create an App Domain
        s_Data->AppDomain = mono_domain_create_appdomain("NeutronScriptRuntime", nullptr);
        mono_domain_set(s_Data->AppDomain, true);

        s_Data->CoreAssembly = LoadCSharpAssembly(path);

        Logger::Assert(s_Data->CoreAssembly != nullptr);

        MonoImage* assemblyImage = mono_assembly_get_image(s_Data->CoreAssembly);
        MonoClass* monoClass = mono_class_from_name(assemblyImage, "Neutron", "Main");

        Logger::Assert(monoClass != nullptr);

        PrintAssemblyTypes(s_Data->CoreAssembly);

        MonoObject* instance = mono_object_new(s_Data->AppDomain, monoClass);
        Logger::Assert(instance != nullptr);

        mono_runtime_object_init(instance); //  << ERROR HAPPENS HERE

    }

    void ScriptingEngine::ShutdownMono() {

    }
} // Neutron
</code>```

my header file, ScriptingEngine.h

```<code>//
// Created by aw1lt on 05/12/22.
//

#ifndef NEUTRONENGINE_SCRIPTINGENGINE_H
#define NEUTRONENGINE_SCRIPTINGENGINE_H

#include <string>

namespace Neutron {

    class ScriptingEngine {
    public:
        static void Init();
        static void Shutdown();
    private:
        static void InitMono(std::string path = "../Sandbox/Sandbox/bin/Debug/Sandbox.dll");
        static void ShutdownMono();
    };

} // Neutron

#endif //NEUTRONENGINE_SCRIPTINGENGINE_H
</code>```

I also tried the answers on this page.

Thank you, and sorry if this answer is a mess.

Body:
I am relatively new to C++, and have copied some code from a live stream to get started with embedding C# mono into my game engine.

I have created a C# script:

using System;

namespace Neutron {
    public class Main {
        public float FloatVar { get; set; }

        public Main() {
            Console.WriteLine("Main constructor");
        }

        public void PrintMessage() {
            Console.WriteLine("Hello World from C#!");
        }

        public void PrintCustomMessage(string message) {
            Console.WriteLine($"C# says: {message}");
        }
    }
}

and built it to
../Sandbox/Sandbox/bin/Debug/Sandbox.dll (which i have verified within the c++ program that I am embedding it into)

when i call mono_runtime_object_init passing the MonoObject* created from calling mono_object_new (I have verified that it doesnt return a nullptr)

The following error occurs:
* Assertion at object.c:116, condition `is_ok (error)' not met, function:mono_runtime_object_init, (null) assembly:/usr/lib/mono/4.5/mscorlib.dll type:TypeInitializationException member:(null)
Followed by a long stack trace.

Here are my relavent files:

ScriptingEngine.cpp (See the InitMono function towards the bottom)

//
// Created by aw1lt on 05/12/22.
//

#include "ScriptingEngine.h"
#include "Logger.h"

#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
#include <fstream>

namespace Neutron {

    struct ScriptEngineData {
        MonoDomain* RootDomain = nullptr;
        MonoDomain* AppDomain = nullptr;
        MonoAssembly* CoreAssembly = nullptr;
    };

    char* ReadBytes(const std::string& filepath, uint32_t* outSize) {
        std::ifstream stream(filepath, std::ios::binary | std::ios::ate);

        if (!stream) {
            // Failed to open the file
            return nullptr;
        }

        std::streampos end = stream.tellg();
        stream.seekg(0, std::ios::beg);
        uint32_t size = end - stream.tellg();

        if (size == 0) {
            // File is empty
            return nullptr;
        }

        char* buffer = new char[size];
        stream.read((char*)buffer, size);
        stream.close();

        *outSize = size;
        return buffer;
    }

    MonoAssembly* LoadCSharpAssembly(const std::string& assemblyPath) {
        uint32_t fileSize = 0;
        char* fileData = ReadBytes(assemblyPath, &fileSize);

        // NOTE: We can't use this image for anything other than loading the assembly because this image doesn't have a reference to the assembly
        MonoImageOpenStatus status;
        MonoImage* image = mono_image_open_from_data_full(fileData, fileSize, 1, &status, 0);

        if (status != MONO_IMAGE_OK) {
            const char* errorMessage = mono_image_strerror(status);
            Logger::Crit(errorMessage);
            return nullptr;
        }

        MonoAssembly* assembly = mono_assembly_load_from_full(image, assemblyPath.c_str(), &status, 0);
        mono_image_close(image);

        // Don't forget to free the file data
        delete[] fileData;

        return assembly;
    }

    void PrintAssemblyTypes(MonoAssembly* assembly) {
        MonoImage* image = mono_assembly_get_image(assembly);
        const MonoTableInfo* typeDefinitionsTable = mono_image_get_table_info(image, MONO_TABLE_TYPEDEF);
        int32_t numTypes = mono_table_info_get_rows(typeDefinitionsTable);

        for (int32_t i = 0; i < numTypes; i++) {
            uint32_t cols[MONO_TYPEDEF_SIZE];
            mono_metadata_decode_row(typeDefinitionsTable, i, cols, MONO_TYPEDEF_SIZE);

            const char* nameSpace = mono_metadata_string_heap(image, cols[MONO_TYPEDEF_NAMESPACE]);
            const char* name = mono_metadata_string_heap(image, cols[MONO_TYPEDEF_NAME]);

            Logger::Log(std::string(nameSpace) + "." + name);
        }
    }

    static ScriptEngineData* s_Data;

    void ScriptingEngine::Init() {
        s_Data = new ScriptEngineData();

        InitMono();
    }

    void ScriptingEngine::Shutdown() {
        delete s_Data;
    }

    void ScriptingEngine::InitMono(std::string path) {
        MonoDomain* rootDomain = mono_jit_init("NeutronJITRuntime");
        Logger::Assert(rootDomain != nullptr);

        //system(("cat " + path).c_str());

        // Store the root domain pointer
        s_Data->RootDomain = rootDomain;

        // Create an App Domain
        s_Data->AppDomain = mono_domain_create_appdomain("NeutronScriptRuntime", nullptr);
        mono_domain_set(s_Data->AppDomain, true);

        s_Data->CoreAssembly = LoadCSharpAssembly(path);

        Logger::Assert(s_Data->CoreAssembly != nullptr);

        MonoImage* assemblyImage = mono_assembly_get_image(s_Data->CoreAssembly);
        MonoClass* monoClass = mono_class_from_name(assemblyImage, "Neutron", "Main");

        Logger::Assert(monoClass != nullptr);

        PrintAssemblyTypes(s_Data->CoreAssembly);

        MonoObject* instance = mono_object_new(s_Data->AppDomain, monoClass);
        Logger::Assert(instance != nullptr);

        mono_runtime_object_init(instance); //  << ERROR HAPPENS HERE

    }

    void ScriptingEngine::ShutdownMono() {

    }
} // Neutron

my header file, ScriptingEngine.h

//
// Created by aw1lt on 05/12/22.
//

#ifndef NEUTRONENGINE_SCRIPTINGENGINE_H
#define NEUTRONENGINE_SCRIPTINGENGINE_H

#include <string>

namespace Neutron {

    class ScriptingEngine {
    public:
        static void Init();
        static void Shutdown();
    private:
        static void InitMono(std::string path = "../Sandbox/Sandbox/bin/Debug/Sandbox.dll");
        static void ShutdownMono();
    };

} // Neutron

#endif //NEUTRONENGINE_SCRIPTINGENGINE_H

I also tried the answers on this page.

Thank you, and sorry if this answer is a mess.


问:
How to reference a value in AsyncStorage object?
I'm trying to pass data between two pages, as an object. So far, I can print the details of the object, but I haven't had much luck getting specific values out of it. E.g., name, id, price. I figured it would be fairly simple, but I'm struggling to find options online. I think I need to map through it, but every attempt I've made it has made it worse.

Storing the data:

```<code>const [cart, setCart] = useState([]);

  const addCart = async() => {
    setButtonText('ADDED TO CART!')
    cart.push({name, id, quantity, price})
    try {
      const toyDetails = JSON.stringify(cart)
      await AsyncStorage.setItem('object', toyDetails)
    }catch(error){
      console.log('setitem didnt work')
    }
  }
</code>```

Retrieving the data:

```<code>const CartCard = ({name, id, price}) => {

  const [details, setDetails] = useState('')

  const [itemName, setItemName] = useState({name})

  useEffect(()=>{
      getData()
    }, [])

  const getData = async() => {
    try {
      const getValues = await AsyncStorage.getItem('object')
      if(getValues !== null){
        console.log(JSON.parse(getValues))
        setDetails(getValues)
      }
    }catch(error){
      console.log('getitem didnt work')
    }
  }

  return (
    <View>
      <View>
// gives me error about '.map is not a function', online says its because the value is not an array
        {/* <Text>{details.map(detail=>{detail.name})}</Text> */}
        <Text>{details}</Text>
      </View>
    </View>
  )
}

export default CartCard
</code>```

I'm not sure if it has anything to do with it, but I can also only put in 1 object in the cart, as opposed to more than one. It just replaces it. Not sure why.

Body:
I'm trying to pass data between two pages, as an object. So far, I can print the details of the object, but I haven't had much luck getting specific values out of it. E.g., name, id, price. I figured it would be fairly simple, but I'm struggling to find options online. I think I need to map through it, but every attempt I've made it has made it worse.

Storing the data:

const [cart, setCart] = useState([]);

  const addCart = async() => {
    setButtonText('ADDED TO CART!')
    cart.push({name, id, quantity, price})
    try {
      const toyDetails = JSON.stringify(cart)
      await AsyncStorage.setItem('object', toyDetails)
    }catch(error){
      console.log('setitem didnt work')
    }
  }

Retrieving the data:

const CartCard = ({name, id, price}) => {

  const [details, setDetails] = useState('')

  const [itemName, setItemName] = useState({name})

  useEffect(()=>{
      getData()
    }, [])

  const getData = async() => {
    try {
      const getValues = await AsyncStorage.getItem('object')
      if(getValues !== null){
        console.log(JSON.parse(getValues))
        setDetails(getValues)
      }
    }catch(error){
      console.log('getitem didnt work')
    }
  }

  return (
    <View>
      <View>
// gives me error about '.map is not a function', online says its because the value is not an array
        {/* <Text>{details.map(detail=>{detail.name})}</Text> */}
        <Text>{details}</Text>
      </View>
    </View>
  )
}

export default CartCard

I'm not sure if it has anything to do with it, but I can also only put in 1 object in the cart, as opposed to more than one. It just replaces it. Not sure why.


问:
AdMob Requests and impressions drop to 0
I have a problem and I hope you can help!

I have an application added to Admob. The first 4 days (like the chart below), the figures are completely normal. From the fifth day onward, everything was almost wiped to 0: request, impression...I did not receive any error message or email.

I look forward to your help on this matter. Thank you!

This is admob report

I have checked my app's activities on google analytics, all is normal, my app is still working, nothing has changed (number of installs/day, crashes, DAU...). The thing is that other apps linked to my admob account are still working fine, only this app has lost its stats.


问:
Error when return a variable in typescript
Goal: I want to eliminate code repetition

here is the code ::

```<code>export class GoogleService {
  keyFile:string = './src/google/credentials.json';
  scopes:string = 'https://www.googleapis.com/auth/spreadsheets';
  spreadsheetId:string = 'ABC';

  constructor(private http: HttpService) {}

  async writeToGSheets() {
    const auth = new google.auth.GoogleAuth({
      keyFile: this.keyFile,
      scopes: this.scopes,
    });

    const client = await auth.getClient();
    const googleSheet = google.sheets({ version: 'v4', auth: client });

    const metaData = await googleSheet.spreadsheets.get({
      auth,
      spreadsheetId:this.spreadsheetId
    });

    const getRows = await googleSheet.spreadsheets.values.get({
      auth,
      spreadsheetId:this.spreadsheetId,
      range: 'Sheet1',
    });

    await googleSheet.spreadsheets.values.append({
      auth,
      spreadsheetId:this.spreadsheetId,
      range: 'Sheet1!A:B',
      valueInputOption: 'RAW',
      requestBody: {
        values: [['1', '2']],
      },
    });
  }

  async readGSheets() {
    const auth = new google.auth.GoogleAuth({
      keyFile: this.keyFile,
      scopes: this.scopes,
    });

    const client = await auth.getClient();
    const googleSheet = google.sheets({ version: 'v4', auth: client });

    const metaData = await googleSheet.spreadsheets.get({
      auth,
      spreadsheetId:this.spreadsheetId,
      // range: 'Sheet1!A:B'
    });

    // read rows from spreadsheets

    const getRows = await googleSheet.spreadsheets.values.get({
      auth,
      spreadsheetId:this.spreadsheetId,
      range: 'Sheet1',
    });
    return getRows.data.values;
  }
}

</code>```

As you can see, I have a bunch of repetition and I hate it!

I am trying to write out a function for the authentication variable as so::

```<code>  getAuth(){
    const auth = new google.auth.GoogleAuth({
      keyFile: this.keyFile,
      scopes: this.scopes,
    });
    return auth;
  }
</code>```

However, I get the following error:

```<code>The inferred type of 'getAuth' cannot be named without a reference to '.pnpm/google-auth-library@8.7.0/node_modules/google-auth-library/build/src/auth/googleauth'. This is likely not portable. A type annotation is necessary.ts(2742)
</code>```

I don't need to slim down the code, but I really want to further my dev skills and I think this is a good challenge.
I don't understand what the issue is here though lol

Body:
Goal: I want to eliminate code repetition

here is the code ::

export class GoogleService {
  keyFile:string = './src/google/credentials.json';
  scopes:string = 'https://www.googleapis.com/auth/spreadsheets';
  spreadsheetId:string = 'ABC';

  constructor(private http: HttpService) {}

  async writeToGSheets() {
    const auth = new google.auth.GoogleAuth({
      keyFile: this.keyFile,
      scopes: this.scopes,
    });

    const client = await auth.getClient();
    const googleSheet = google.sheets({ version: 'v4', auth: client });

    const metaData = await googleSheet.spreadsheets.get({
      auth,
      spreadsheetId:this.spreadsheetId
    });

    const getRows = await googleSheet.spreadsheets.values.get({
      auth,
      spreadsheetId:this.spreadsheetId,
      range: 'Sheet1',
    });

    await googleSheet.spreadsheets.values.append({
      auth,
      spreadsheetId:this.spreadsheetId,
      range: 'Sheet1!A:B',
      valueInputOption: 'RAW',
      requestBody: {
        values: [['1', '2']],
      },
    });
  }

  async readGSheets() {
    const auth = new google.auth.GoogleAuth({
      keyFile: this.keyFile,
      scopes: this.scopes,
    });

    const client = await auth.getClient();
    const googleSheet = google.sheets({ version: 'v4', auth: client });

    const metaData = await googleSheet.spreadsheets.get({
      auth,
      spreadsheetId:this.spreadsheetId,
      // range: 'Sheet1!A:B'
    });

    // read rows from spreadsheets

    const getRows = await googleSheet.spreadsheets.values.get({
      auth,
      spreadsheetId:this.spreadsheetId,
      range: 'Sheet1',
    });
    return getRows.data.values;
  }
}

As you can see, I have a bunch of repetition and I hate it!

I am trying to write out a function for the authentication variable as so::

  getAuth(){
    const auth = new google.auth.GoogleAuth({
      keyFile: this.keyFile,
      scopes: this.scopes,
    });
    return auth;
  }

However, I get the following error:

The inferred type of 'getAuth' cannot be named without a reference to '.pnpm/google-auth-library@8.7.0/node_modules/google-auth-library/build/src/auth/googleauth'. This is likely not portable. A type annotation is necessary.ts(2742)

I don't need to slim down the code, but I really want to further my dev skills and I think this is a good challenge.
I don't understand what the issue is here though lol


问:
Subprocess only opening .app files & how to save data
I make a tkinter gui to allow the user to create buttons to name and launch .app programs on mac. I have 2 problems:

If I try to open anything other than a .app I get this error:
"The application /Users/.../Desktop/IMG_3802.jpg cannot be opened, error=Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted""

Can someone help me with a way to store the buttons so they will apear once the app is relaunched?

I am newish to python and am working on a project that is ahead of where we are at in school (We have been on Turtle for weeks) and would like some advice please


问:
Is this flutter example bugged?
I am trying to learn about actions but this example on the flutter.dev site doesn't seem to fully work? If you use the keyboard shortcuts ctrl+a and ctrl+c, it will select all and copy. But the buttons, which call the same actions and intents, do not work. Is this code sample incorrect?

https://docs.flutter.dev/development/ui/advanced/actions_and_shortcuts#putting-it-together

Title: Is this flutter example bugged?


问:
How to implement websocket by embed-tomcat？
I want to implement websocket by embed-tomcat, but when I run my program, the tomcat can't handle websocket request, it just can handle servlet request, this is my github demo program: https://github.com/ZTW1995/tomcat-websocket-demo. What should I do? I don't want to use any framework.

I use browser open the chat.html to connect my tomcat server by websocket, but tips WebSocket connection to 'ws://localhost:8888/web/bear' failed.
The browser console image


问:
How to decode url in Grafana?
There are some variables in my data sources that have been encoded to url in the format like this :

%E5%AE%A1%E6%A0%B8%E5%8F%B0%E7%9A%84%E6%8E%A5%E5%8F%A3%E7%9B%AE%E5%89%8D%E8%B0%83%E7%94%A8%E4%BC%9A%E6%9C%89%E9%97%AE%E9%A2%98%E5%90%97%EF%BC%8C%E5%AE%A1%E6%A0%B8%E5%8F%B0%E7%9A%84%E6%A8%A1%E5%9D%97%E5%86%85%E5%AE%B9%E4%BC%9A%E6%AF%94%E6%9F%94%E6%80%A7%E5%B0%91%EF%BC%8C%E6%88%91%E6%95%B4%E7%90%86%E4%B8%80%E4%B8%8B%E5%AE%A1%E6%A0%B8%E5%8F%B0%E6%B6%89%E5%8F%8A%E7%9A%84%E6%A8%A1%E5%9D%97%EF%BC%9F

How to decode it in Grafana so that I can see the understandable content ?

googled the question didnt find any answer about it.

Title: How to decode url in Grafana?


问:
erorr while iam delete site on cloud panel
why thhis happend when iam delete a site on my cloudpanel ?

"An error has occurred, error message: Command " : /usr/bin/sudo /bin/bash -c "/bin/rm -f '/etc/php/8.0/fpm/pool.d/allnetwork.online.conf'"" failed, error message: /bin/bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8) /bin/bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)"

help me, iam stack
first


问:
HTML & Javascript Spinner
I am creating a html spinner but having trouble with my code not playing the gif/timer once I've pressed stop and go. I have my html file in the folder with the gifs/png pictures buts its only showing one picture if the spinner and not actually going through the motion and spinning around once start is pressed.

Here is my code

```<code><!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Spinner</title>
        <style>
            body {text-align:center}
            </style>
            <script>
                var frame = 0;
                var timerID;
                var pics = new Array(12);
                function animate () {
                    document.images[0].src = pics[frame].src;
                    frame = (frame + 1)%12;
                    timerID = setTimeout ("animate()",100);
                }
                for (i=0; i<pics.length; i++) {
                    pics[i] = new Image();
                }
                for (var i=0; i<pics.length; i++) {
                    pics[i].src = "frame" + i + ".png";
                }
            </script>
        </head>
        <body>
            <img src="frame-1.png" alt="spinner"/>

            <form>
                <input type="button" value="Start" onclick='setTimeout("animate()",100);'/>
                <input type="button" value="Stop" onclick='clearTimeout(timerID);'/>
            </form>
        </body>
    </html>
</code>```

and this is what I keep getting in the screenshot but I need it to actually go around Results im getting

I've tried playing around with the code more, but I'm not getting anything the full outcome im wanting which is having the spinner fully spin when I press stop.

Title: HTML & Javascript Spinner

Body:
I am creating a html spinner but having trouble with my code not playing the gif/timer once I've pressed stop and go. I have my html file in the folder with the gifs/png pictures buts its only showing one picture if the spinner and not actually going through the motion and spinning around once start is pressed.

Here is my code

<!doctype html>

        <meta charset="utf-8">
        <title>Spinner</title>

            <form>
                <input type="button" value="Start" onclick='setTimeout("animate()",100);'/>
                <input type="button" value="Stop" onclick='clearTimeout(timerID);'/>
            </form>

and this is what I keep getting in the screenshot but I need it to actually go around Results im getting

I've tried playing around with the code more, but I'm not getting anything the full outcome im wanting which is having the spinner fully spin when I press stop.


问:
opencv mat to QbyteArray Unsupported image format
Hi I am trying to draw a contour to a base64 encoded qbytearray by converting it to cv mat and revert it back to qbyte array to display on qml.
While the first part is working correclty, I can't seem to convert the cv mat to qbytearray back properly

the code that I am using now is

```<code>cv::Mat final_img;
        cv::Mat dst;
        cv::resize(final_img, final_img, final_img.size());
        cv::cvtColor(final_img, dst, cv::COLOR_BGR2BGRA);
        QByteArray data = QByteArray::fromRawData(reinterpret_cast<char*>(dst.data), 592355);
        decoded_image = "data:image/jpeg;base64,";
        decoded_image.append(QString::fromLatin1(data.toBase64().data()));
</code>```

I get a correct format of base64encoded bytearray but gets the following error

```<code>Unsupported image format

</code>```

Any help will be appreciated! Thanks

Body:
Hi I am trying to draw a contour to a base64 encoded qbytearray by converting it to cv mat and revert it back to qbyte array to display on qml.
While the first part is working correclty, I can't seem to convert the cv mat to qbytearray back properly

the code that I am using now is

cv::Mat final_img;
        cv::Mat dst;
        cv::resize(final_img, final_img, final_img.size());
        cv::cvtColor(final_img, dst, cv::COLOR_BGR2BGRA);
        QByteArray data = QByteArray::fromRawData(reinterpret_cast<char*>(dst.data), 592355);
        decoded_image = "data:image/jpeg;base64,";
        decoded_image.append(QString::fromLatin1(data.toBase64().data()));

I get a correct format of base64encoded bytearray but gets the following error

Unsupported image format

Any help will be appreciated! Thanks


问:
I get NA when using as.Date in r
When I use the "as.Date" command in r it returns Na as a result, I have tried different things like transforming it to POSIXt format, changing the date format with % and even using the "paste" command, but it doesn't work.

```<code>
    #The format I want to have:
    format(Sys.Date(), "%B de %Y")
    [1] "December de 2022"

    #Example
    date="noviembre de 2022"

    #Attempt 1:
    date2 <- strptime(date, format = "%B de %Y")
    date3 <- as.Date(date2,format="%B de %Y")
    date3
    [1] NA

    #Attempt 2:
    date2 <- as.Date(paste(1, gsub("de ", "", date)), format = "%d %B %Y")
    date2
    [1] NA

    #Attempt 3:
    date2 <- as.Date(date,format="%B de %Y")
    date2
    [1] NA

    #Attempt 4:
    a <- as.character("noviembre de 2022")
    pos_dt <- strptime(a, format = "%B de %Y")
    b <- as.Date(pos_dt, format = "%B de %Y")
    print(a)
    [1] NA
    print(b)
    [1] NA
</code>```

I don't know what other option I could try or how I could solve the problem. I just need r to read me the date format like I have in the example.

Thanks for the help

Title: I get NA when using as.Date in r

Body:
When I use the "as.Date" command in r it returns Na as a result, I have tried different things like transforming it to POSIXt format, changing the date format with % and even using the "paste" command, but it doesn't work.

    #The format I want to have:
    format(Sys.Date(), "%B de %Y")
    [1] "December de 2022"

    #Example
    date="noviembre de 2022"

    #Attempt 1:
    date2 <- strptime(date, format = "%B de %Y")
    date3 <- as.Date(date2,format="%B de %Y")
    date3
    [1] NA

    #Attempt 2:
    date2 <- as.Date(paste(1, gsub("de ", "", date)), format = "%d %B %Y")
    date2
    [1] NA

    #Attempt 3:
    date2 <- as.Date(date,format="%B de %Y")
    date2
    [1] NA

    #Attempt 4:
    a <- as.character("noviembre de 2022")
    pos_dt <- strptime(a, format = "%B de %Y")
    b <- as.Date(pos_dt, format = "%B de %Y")
    print(a)
    [1] NA
    print(b)
    [1] NA

I don't know what other option I could try or how I could solve the problem. I just need r to read me the date format like I have in the example.

Thanks for the help


问:
Ordering with Pivot Table in Laravel 5.7
I am new on stack overflow (as well as to Laravel), please forgive mw if some details are not clear on my question and I am happy to provide more details as needed.

I have a query builder below:

```<code>$users = User::whereHas('activeService', function($query) use($servicesName){
            $query->where('service_id', $servicesName);
          })
          ->with(['services' => function($query){
              $query->where('start_at', '<', Carbon::now())
            ->where('end_at', '>=', Carbon::now())
            ->where('users_services.is_active', 1)
            ->withPivot(['start_at', 'end_at', 'is_active'])
            ->orderby('end_at', 'asc');
          }])

          ->paginate(50);
</code>```

Collections returned(the relation section):

```<code>#relations: array:1 [▼
"services" => Illuminate\Database\Eloquent\Collection {#3087 ▼
  #items: array:1 [▼
    0 => App\Models\Service {#2933 ▼
      #table: "services"
      #fillable: array:8 [▶]
      #attributes: array:13 [▼
        "id" => 98
        "name" => "Silver"
        "code" => "silver"
        "is_active" => 1
        "created_at" => "2019-02-04 12:54:03"
        "updated_at" => "2022-10-01 12:48:55"
        "deleted_at" => null
      ]
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #original: array:18 [▼
        "id" => 98
        "name" => "Silver"
        "code" => "silver"
        "is_active" => 1
        "created_at" => "2019-02-04 12:54:03"
        "updated_at" => "2022-10-01 12:48:55"
        "deleted_at" => null
        "pivot_user_id" => 50964
        "pivot_service_id" => 98
        "pivot_start_at" => "2022-07-21 09:00:27"
        "pivot_end_at" => "2023-07-21 23:59:59"
        "pivot_is_active" => 1
      ]
</code>```

How can I order the list with pivot_start_at before paginate the collection? I have tried with ->orderBy('pivot_start_at') or ->orderBy('services.pivot_start_at') etc. but I still can't access the attribute.

Body:
I am new on stack overflow (as well as to Laravel), please forgive mw if some details are not clear on my question and I am happy to provide more details as needed.

I have a query builder below:

$users = User::whereHas('activeService', function($query) use($servicesName){
            $query->where('service_id', $servicesName);
          })
          ->with(['services' => function($query){
              $query->where('start_at', '<', Carbon::now())
            ->where('end_at', '>=', Carbon::now())
            ->where('users_services.is_active', 1)
            ->withPivot(['start_at', 'end_at', 'is_active'])
            ->orderby('end_at', 'asc');
          }])

          ->paginate(50);

Collections returned(the relation section):

#relations: array:1 [▼
"services" => Illuminate\Database\Eloquent\Collection {#3087 ▼
  #items: array:1 [▼
    0 => App\Models\Service {#2933 ▼
      #table: "services"
      #fillable: array:8 [▶]
      #attributes: array:13 [▼
        "id" => 98
        "name" => "Silver"
        "code" => "silver"
        "is_active" => 1
        "created_at" => "2019-02-04 12:54:03"
        "updated_at" => "2022-10-01 12:48:55"
        "deleted_at" => null
      ]
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #original: array:18 [▼
        "id" => 98
        "name" => "Silver"
        "code" => "silver"
        "is_active" => 1
        "created_at" => "2019-02-04 12:54:03"
        "updated_at" => "2022-10-01 12:48:55"
        "deleted_at" => null
        "pivot_user_id" => 50964
        "pivot_service_id" => 98
        "pivot_start_at" => "2022-07-21 09:00:27"
        "pivot_end_at" => "2023-07-21 23:59:59"
        "pivot_is_active" => 1
      ]

How can I order the list with pivot_start_at before paginate the collection? I have tried with ->orderBy('pivot_start_at') or ->orderBy('services.pivot_start_at') etc. but I still can't access the attribute.


问:
How to test both inView and outView cases separately using jest React, when I am using useInView() hook of react-intersection-observer
I am using useInView() hook to monitor a component, and whenever the component is InView , I perform some operation. I am writing UT's for this component and I want to test both the cases i.e. when the component is inView or not. Can anyone suggest how can we mock useInView() to test both the cases.</p>


问:
MySQL - Way to simplify repetitive calculation sub-queries
I've been tasked with making output that fetches number of days passed between an order and its shipment, like this:

order_date
orders
Days0
Days1
Days7Plus

2022-11-01
12
9
3
1

2022-11-15
22
20
0
2

2022-12-02
77
65
5
7

I'm sure you can imagine example underlying data, where there's an orders table with a unique ID per record, an order date that can share multiple IDs, and each order has its own ship date.

The hard part is counting only business days, which required subtracting weekends and holidays from the date range days. I got that all figured out but it required copy-pasting these ugly sub-queries 7 more times :/ While this can be dynamically generated in other code, I figured there must be a cleaner way, since other people (some non-devs) may be testing or reviewing this, and I'll probably get grief about it.

Here's the query essentially:

```<code># get orders shipped count
SELECT
    ...
  # orders that were shipped x number of days from receipt
    SUM(COALESCE(DATEDIFF(shipped, ordered), 0)
        - ( # subtract weekend days
            5 * (DATEDIFF('2022-12-05', '2022-11-01') DIV 7)
            + MID('0123444401233334012222340111123400012345001234550',
                    7 * WEEKDAY('2022-11-01') + WEEKDAY('2022-12-05') + 1, 1
            )
        )
        - ( # subtract holidays
            SELECT COUNT(`date`) FROM holiday WHERE active = 1
            AND `date` BETWEEN '2022-11-01' AND '2022-12-05'
            AND DAYOFWEEK(`date`) < 6
        )
        = 0) AS 0Days, # subsequently 1Days, 2Days, 3Days, etc
  ...
    SUM(COALESCE(DATEDIFF(shipped, ordered), 0)
            - ( # subtract weekend days
                5 * (DATEDIFF('2022-12-05', '2022-11-01') DIV 7)
                + MID('0123444401233334012222340111123400012345001234550',
                    7 * WEEKDAY('2022-11-01') + WEEKDAY('2022-12-05') + 1, 1
            )
        )
        - ( # subtract holidays
            SELECT COUNT(`date`) FROM holiday WHERE active = 1
            AND `date` BETWEEN '2022-11-01' AND '2022-12-05'
            AND DAYOFWEEK(`date`) < 6
        )
        >= 7) AS Days7Plus
FROM orders
WHERE
    AND ordered BETWEEN :startDate AND :endDate
GROUP BY CAST(ordered AS DATE)
ORDER BY ordered
</code>```

I got the MID calculation from https://stackoverflow.com/a/6762805/14744970

I feel pretty proud of getting it all together, but I feel like I'm a small step away from collapsing the redundancy down somehow that I'm not quite understanding.

Note that I don't know if the GROUP BY actually matters with any sort of simplifying of the redundant statements.

Body:
I've been tasked with making output that fetches number of days passed between an order and its shipment, like this:

order_date
orders
Days0
Days1
Days7Plus

2022-11-01
12
9
3
1

2022-11-15
22
20
0
2

2022-12-02
77
65
5
7

I'm sure you can imagine example underlying data, where there's an orders table with a unique ID per record, an order date that can share multiple IDs, and each order has its own ship date.

The hard part is counting only business days, which required subtracting weekends and holidays from the date range days. I got that all figured out but it required copy-pasting these ugly sub-queries 7 more times :/ While this can be dynamically generated in other code, I figured there must be a cleaner way, since other people (some non-devs) may be testing or reviewing this, and I'll probably get grief about it.

Here's the query essentially:

# get orders shipped count
SELECT
    ...
  # orders that were shipped x number of days from receipt
    SUM(COALESCE(DATEDIFF(shipped, ordered), 0)
        - ( # subtract weekend days
            5 * (DATEDIFF('2022-12-05', '2022-11-01') DIV 7)
            + MID('0123444401233334012222340111123400012345001234550',
                    7 * WEEKDAY('2022-11-01') + WEEKDAY('2022-12-05') + 1, 1
            )
        )
        - ( # subtract holidays
            SELECT COUNT(`date`) FROM holiday WHERE active = 1
            AND `date` BETWEEN '2022-11-01' AND '2022-12-05'
            AND DAYOFWEEK(`date`) < 6
        )
        = 0) AS 0Days, # subsequently 1Days, 2Days, 3Days, etc
  ...
    SUM(COALESCE(DATEDIFF(shipped, ordered), 0)
            - ( # subtract weekend days
                5 * (DATEDIFF('2022-12-05', '2022-11-01') DIV 7)
                + MID('0123444401233334012222340111123400012345001234550',
                    7 * WEEKDAY('2022-11-01') + WEEKDAY('2022-12-05') + 1, 1
            )
        )
        - ( # subtract holidays
            SELECT COUNT(`date`) FROM holiday WHERE active = 1
            AND `date` BETWEEN '2022-11-01' AND '2022-12-05'
            AND DAYOFWEEK(`date`) < 6
        )
        >= 7) AS Days7Plus
FROM orders
WHERE
    AND ordered BETWEEN :startDate AND :endDate
GROUP BY CAST(ordered AS DATE)
ORDER BY ordered

I got the MID calculation from https://stackoverflow.com/a/6762805/14744970

I feel pretty proud of getting it all together, but I feel like I'm a small step away from collapsing the redundancy down somehow that I'm not quite understanding.

Note that I don't know if the GROUP BY actually matters with any sort of simplifying of the redundant statements.


问:
How to distinguish Categorical Variables by Color using leaflet in R
I'm making an interactive map of squirrels chasing behavior in New York central Park and I'm using "leaflet" in R.I want to use different colors to distinguish the different times (PM,AM) so that we can see how chasing behavour varies across.

```<code>pal <- colorNumeric(palette = "RdYlBu",domain = d$chasingInt)

d %>%
  filter(!is.na(chasingInt)) %>%
  leaflet() %>%
  addTiles() %>%
  addCircleMarkers(lng = ~x,
                   lat = ~y, radius = 3, stroke = FALSE, fillOpacity = 0.5) %>%
  addLegend(position ="bottomright", pal = pal, values = ~ chasingInt)%>%
  addCircleMarkers(~x,
                   ~y,
                   radius = ~chasingInt/10,
                   color ="red",
                   stroke = FALSE,
                   fillOpacity = 0.4,
                   group = "shift",
                   popup = ~as.character(shift))
</code>```

All PM and AM are colored as red so there is no difference on the plot

Body:
I'm making an interactive map of squirrels chasing behavior in New York central Park and I'm using "leaflet" in R.I want to use different colors to distinguish the different times (PM,AM) so that we can see how chasing behavour varies across.

pal <- colorNumeric(palette = "RdYlBu",domain = d$chasingInt)

d %>%
  filter(!is.na(chasingInt)) %>%
  leaflet() %>%
  addTiles() %>%
  addCircleMarkers(lng = ~x,
                   lat = ~y, radius = 3, stroke = FALSE, fillOpacity = 0.5) %>%
  addLegend(position ="bottomright", pal = pal, values = ~ chasingInt)%>%
  addCircleMarkers(~x,
                   ~y,
                   radius = ~chasingInt/10,
                   color ="red",
                   stroke = FALSE,
                   fillOpacity = 0.4,
                   group = "shift",
                   popup = ~as.character(shift))

All PM and AM are colored as red so there is no difference on the plot


问:
parse the json data receive through firebase messaging in flutter app
enter image description here here is the json response I get through notification while decoding the json i get an error

the method I tried

```<code>var data = message.data;
Map<String, dynamic> data1 = json.decode(data);

the error I got on json.decode(data);

The argument type 'Map<String, dynamic>' can't be assigned to the parameter type 'String'
</code>```

Body:
enter image description here here is the json response I get through notification while decoding the json i get an error

the method I tried

var data = message.data;
Map<String, dynamic> data1 = json.decode(data);

the error I got on json.decode(data);

The argument type 'Map<String, dynamic>' can't be assigned to the parameter type 'String'


问:
How does one install a specific ocaml compiler when it doesn't appear on the opam switch list?
I've installed this compiler before in a docker container, but I don't understand why it's missing right now. Command and error:

```<code>(iit_synthesis) brando9~ $ opam switch create ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1 ocaml-variants.4.07.1+flambda
[ERROR] No compiler matching `ocaml-variants.4.07.1+flambda' found, use `opam switch list-available' to see what is available, or use `--packages' to
        select packages explicitly.
</code>```

but it's not in the list:

```<code>(iit_synthesis) brando9~ $ opam switch list-available
# Listing available compilers from repositories: default
# Name                  # Version # Synopsis
ocaml-option-32bit      1         Set OCaml to be compiled in 32-bit mode for 64-bit Linux and OS X hosts
ocaml-option-flambda    1         Set OCaml to be compiled with flambda activated
ocaml-option-nnpchecker 1         Set OCaml to be compiled with --enable-naked-pointers-checker
ocaml-option-spacetime  1         Set OCaml to be compiled with spacetime activated
ocaml-options-vanilla   1         Ensure that OCaml is compiled with no special options enabled
</code>```

Opam update fails

Output:

```<code>$ opam update --all

<><> Updating package repositories ><><><><><><><><><><><><><><><><><><><><><><>
Processing  1/1: [default: http]

Processing  1/1: [default: http]

[default] synchronised from https://opam.ocaml.org
[ERROR] Could not update repository "default": "~/anaconda/bin/patch -p1 -i /dfs/scratch0/brando9/.opam/log/patch-99014-0624b6" exited with code 2
</code>```

I probably should have started with this but I installed opam with "manually" with deb because I don't have sudo. In particular I did this:

```<code># - opam (snap, no sudo)
# ref: https://askubuntu.com/questions/339/how-can-i-install-a-package-without-root-access
apt-get download opam
#apt-get download opam_1.2.2-4_amd64
# manually checked the opam name
#ls | less
mkdir -p ~/.local
dpkg -x opam_1.2.2-4_amd64.deb ~/.local/bin
export PATH="$HOME/.local/bin:$PATH"
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc.user
source ~/.bashrc.user

tr ':' '\n' <<< "$PATH"

opam --version
</code>```

before that I did try installing opam with conda (which has worked in the past) but it failed. I wonder if that screwed things up :/. Will try to reproduce to post the conda error. But I ran conda install -c conda-forge opam.

related:

How to install a specific version of ocaml compiler with opam

https://discuss.ocaml.org/t/why-doesnt-my-server-show-the-ocaml-compiler-that-i-need/10917

https://www.reddit.com/r/ocaml/comments/zed88p/how_does_one_install_a_specific_ocaml_compiler/

How does one install opam without sudo priveledges on linux/ubuntu?

Body:
I've installed this compiler before in a docker container, but I don't understand why it's missing right now. Command and error:

(iit_synthesis) brando9~ $ opam switch create ocaml-variants.4.07.1+flambda_coq-serapi.8.11.0+0.11.1 ocaml-variants.4.07.1+flambda
[ERROR] No compiler matching `ocaml-variants.4.07.1+flambda' found, use `opam switch list-available' to see what is available, or use `--packages' to
        select packages explicitly.

but it's not in the list:

(iit_synthesis) brando9~ $ opam switch list-available
# Listing available compilers from repositories: default
# Name                  # Version # Synopsis
ocaml-option-32bit      1         Set OCaml to be compiled in 32-bit mode for 64-bit Linux and OS X hosts
ocaml-option-flambda    1         Set OCaml to be compiled with flambda activated
ocaml-option-nnpchecker 1         Set OCaml to be compiled with --enable-naked-pointers-checker
ocaml-option-spacetime  1         Set OCaml to be compiled with spacetime activated
ocaml-options-vanilla   1         Ensure that OCaml is compiled with no special options enabled

Opam update fails

Output:

$ opam update --all

<><> Updating package repositories ><><><><><><><><><><><><><><><><><><><><><><>
Processing  1/1: [default: http]

Processing  1/1: [default: http]

[default] synchronised from https://opam.ocaml.org
[ERROR] Could not update repository "default": "~/anaconda/bin/patch -p1 -i /dfs/scratch0/brando9/.opam/log/patch-99014-0624b6" exited with code 2

I probably should have started with this but I installed opam with "manually" with deb because I don't have sudo. In particular I did this:

# - opam (snap, no sudo)
# ref: https://askubuntu.com/questions/339/how-can-i-install-a-package-without-root-access
apt-get download opam
#apt-get download opam_1.2.2-4_amd64
# manually checked the opam name
#ls | less
mkdir -p ~/.local
dpkg -x opam_1.2.2-4_amd64.deb ~/.local/bin
export PATH="$HOME/.local/bin:$PATH"
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc.user
source ~/.bashrc.user

tr ':' '\n' <<< "$PATH"

opam --version

before that I did try installing opam with conda (which has worked in the past) but it failed. I wonder if that screwed things up :/. Will try to reproduce to post the conda error. But I ran conda install -c conda-forge opam.

related:

How to install a specific version of ocaml compiler with opam

https://discuss.ocaml.org/t/why-doesnt-my-server-show-the-ocaml-compiler-that-i-need/10917

https://www.reddit.com/r/ocaml/comments/zed88p/how_does_one_install_a_specific_ocaml_compiler/

How does one install opam without sudo priveledges on linux/ubuntu?


问:
Email not sent via nodemailer
I am developing authentication Api with Express and json-server. I am trying to send a verification email when the user signed up. After a new user is created in a database then an email should be sent but is not.

```<code>// Create new user
  const newUser: User = {
    id: uuidv4(),
    email: user.email,
    name: String(user.name),
    passwordHash: await bcrypt.hash(String(user.password), 10),
  };

  await Api.post(USERS_URL, newUser); << if i delete this line then an email is sent

  // Sent verification link
  const emailToken = Auth.generateToken(user.email);
  const message = `Click the link below to verify your email\nhttp://localhost:4000/verifyEmail/${newUser.id}/${emailToken}`;
  try {
    await Email.send(user.email, 'Verify your email', message);
  } catch (error) {
    return res.status(INTERNAL_SERVER_ERROR).send('Email not sent');
  }

  return res.status(OK).send('Email sent');
</code>```

Api module

```<code>export class Api {
  private static baseUrl = 'http://localhost:3001';

  private static getUrl(url: string, id?: string | number) {
    return id ? this.baseUrl + url + `/${id}` : this.baseUrl + url;
  }

  private static responseHandler(response: AxiosResponse) {
    return response.data;
  }

  static async post(url: string, data: any) {
    const response = await Axios.post(this.getUrl(url), data);
    return this.responseHandler(response);
  }
}
</code>```

and Email module

```<code>import nodemailer from 'nodemailer';

export const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'fake@gmail.com',
    pass: 'fake',
  },
});

export class Email {
  static async send(to: string, subject: string, text: string) {
    return transporter.sendMail({
      from: 'fake',
      to,
      subject,
      text,
    });
  }
}

</code>```

If I put the line with posting the user to a database after sending the email it also works but I want to do it after the user is created

I tried everything and now I'm stuck

Title: Email not sent via nodemailer

Body:
I am developing authentication Api with Express and json-server. I am trying to send a verification email when the user signed up. After a new user is created in a database then an email should be sent but is not.

// Create new user
  const newUser: User = {
    id: uuidv4(),
    email: user.email,
    name: String(user.name),
    passwordHash: await bcrypt.hash(String(user.password), 10),
  };

  await Api.post(USERS_URL, newUser); << if i delete this line then an email is sent

  // Sent verification link
  const emailToken = Auth.generateToken(user.email);
  const message = `Click the link below to verify your email\nhttp://localhost:4000/verifyEmail/${newUser.id}/${emailToken}`;
  try {
    await Email.send(user.email, 'Verify your email', message);
  } catch (error) {
    return res.status(INTERNAL_SERVER_ERROR).send('Email not sent');
  }

  return res.status(OK).send('Email sent');

Api module

export class Api {
  private static baseUrl = 'http://localhost:3001';

  private static getUrl(url: string, id?: string | number) {
    return id ? this.baseUrl + url + `/${id}` : this.baseUrl + url;
  }

  private static responseHandler(response: AxiosResponse) {
    return response.data;
  }

  static async post(url: string, data: any) {
    const response = await Axios.post(this.getUrl(url), data);
    return this.responseHandler(response);
  }
}

and Email module

import nodemailer from 'nodemailer';

export const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'fake@gmail.com',
    pass: 'fake',
  },
});

export class Email {
  static async send(to: string, subject: string, text: string) {
    return transporter.sendMail({
      from: 'fake',
      to,
      subject,
      text,
    });
  }
}

If I put the line with posting the user to a database after sending the email it also works but I want to do it after the user is created

I tried everything and now I'm stuck


问:
Best practices for callback functions
```<code>import { useState } from "react";
import textfield from "../components/textfield";
const cycle = () => {
  const [txt, setTxt] = useState("");
  const changeText = (val) => {
    setTxt(val);
  };
  return <textfield value={txt} changeval={changeText} />;
};

export default cycle;
</code>```
```<code>const textfield = ({ val, changeval }) => {
  return (
    <input
      value={val}
      onChange={(e) => {
        changeval(e.target.value);
      }}
    />
  );
};

export default textfield;
</code>```

This is a crude example of how I was taught to use a callback with child components. Is the method I use inefficient/poor practice?

Title: Best practices for callback functions

Body:
import { useState } from "react";
import textfield from "../components/textfield";
const cycle = () => {
  const [txt, setTxt] = useState("");
  const changeText = (val) => {
    setTxt(val);
  };
  return <textfield value={txt} changeval={changeText} />;
};

export default cycle;

const textfield = ({ val, changeval }) => {
  return (
    <input
      value={val}
      onChange={(e) => {
        changeval(e.target.value);
      }}
    />
  );
};

export default textfield;

This is a crude example of how I was taught to use a callback with child components. Is the method I use inefficient/poor practice?


问:
How to load all pages on JSON from a python request session?
I currently have a method that loads the first page from a request session

```<code>json.loads(self.session.get( ... params: "page": 0 ...))
</code>```

I would like to change this to load every page available on the session...

Is there some sort of "totalPages" variable on a session?

Body:
I currently have a method that loads the first page from a request session

json.loads(self.session.get( ... params: "page": 0 ...))

I would like to change this to load every page available on the session...

Is there some sort of "totalPages" variable on a session?


问:
Tensor flow and tflearn Chatbot keeps on getting high probability even when user input is wrong
I coded a simple AI chatbot with TensorFlow and tflearn and it runs just fine but the issue is when the user inputs the wrong thing, the bot is supposed to say it doesnt understand if the prediction accuracy is less than 70%, but the bot always scores above that even if the user gives jibberish like "rjrigrejfr". The bot assumes theyre greeting them. The patterns its supposed to study in the json are "patterns": ["Hi", "How are you", "Wassup", "Hello", "Good day", "Waddup", "Yo"]. I can share the json file if needed its short. Anyway, this is the python code:</p>
```<code>import numpy as np
import nltk
import tensorflow
import tflearn
import random
import json
import pickle
# Some extra configuration:
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
nltk.download('punkt')

# Load the data from the json file into a variable.
with open("intents.json") as file:
    data = json.load(file)

# If we already have saved data, we do not need to retrain the model and waste time (could develop into an issue in more complex programs. Save in pickle. )
try:
    with open("data.pickle", "rb") as f: # rb stands for bytes.
        words, labels, training, output = pickle.load(f)

# --- Pre-training data preparation ---
except:
    words = []
    docsx = [] # Stores patterns
    docsy = [] # Stores intents
    labels = [] # All the specific tag values such as greeting, contact, etc.
    for intent in data["intents"]:
        for pattern in intent["patterns"]:

            w = nltk.word_tokenize(pattern)  # nltk function that splits the sentences inside intent into words list.
            words.extend(w) # Add the tokenized list to words list.
            docsx.append(w)
            docsy.append(intent["tag"])  # append the classification of the sentence

            if intent["tag"] not in labels:
                labels.append(intent["tag"])

    words = [stemmer.stem(w.lower()) for w in words if w not in ".?!"]  # Stemming the words to remove unnecessary elements leaving their root. Convert all to lowercase.
    words = sorted(list(set(words))) # Set ensures no duplicate elements then we convert back to list and sort it.
    labels = sorted(labels)

    training = []
    output = []

    out_empty = [0 for i in range(len(labels))] # Gives a list of 0 ints based on # of tags. This is useful later in the program when binerizing.

    # One hot encoding the intent categories. Need to one-hot code the data which improves the efficiency of the ML to "binerize" the data.
    # In this case, we have a list of 0s and 1s if the word appears it is assigned a 1 else a 0.
    for x, doc in enumerate(docsx):
        bag = [] # Bag of words or the one-hot coded data for the ML.

        docx_word_stemmed = [stemmer.stem(word) for word in doc] # Stemming the data in docx.

        # Now adding and transforming data into the one-hot coded list/bag of words data.
        for i in words:
            if i in docx_word_stemmed: # Checking against stemmed words:
                # Word exists
                bag.append(1)
            else:
                bag.append(0)

        output_row = out_empty[:] # Copying out_empty
        # Going through the labels list using .index() and for the occurance of docx value in docy, assign binary 1.
        output_row[labels.index(docsy[x])] = 1

        training.append(bag)
        output.append(output_row)
    # Required to use numpy arrays for use in tflearn. It is also faster.
    training = np.array(training)
    output = np.array(output)

    # Saving the data so we do not need to do the data configuration every time.
    with open("data.pickle", "wb") as f:
        pickle.dump((words, labels, training, output), f)

try:

    model.load('model.tflearn')
except:
    tensorflow.compat.v1.reset_default_graph()

    net = tflearn.input_data(shape=[None, len(training[0])])
    net = tflearn.fully_connected(net, 8)
    net = tflearn.fully_connected(net, 8)
    net = tflearn.fully_connected(net, len(output[0]), activation='softmax')
    net = tflearn.regression(net)

    model = tflearn.DNN(net)

    model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)
    model.save("model.tflearn")

def bagofwords(sentence, words):
    bag = [0 for _ in range(len(words))] # blank bag of words.

    # Tokenize s and then stem it.
    sentence_words = nltk.word_tokenize(sentence)
    sentence_words = [stemmer.stem(word.lower()) for word in sentence_words]

    for string in sentence_words:
        for i, word in enumerate(words):
            if word == string:
                bag[i] = 1
    return np.array(bag)

def chat():
    print("Hello there! I'm the SRO AI Virtual Assistant. How am I help you?")
    # Figure out the error slime!
    while True:
        user_input = input("Type here:")
        if user_input == "quit":
            break
        result = model.predict([bagofwords(user_input, words)])[0] #bagofwords func and predict function to give predictions on what the user is saying.

        best_result = np.argmax(result) # We want to only use the best result.
        tag = labels[best_result]
        print(result[best_result])

        # Open JSON file and pick a response.
        if result[best_result] > 0.7:
            for tg in data["intents"]:
                if tg['tag'] == tag:
                    responses = tg['responses']
            print(random.choice(responses))
        else:
            print("I don't quite understand")

chat()
</code>```

Body:
I coded a simple AI chatbot with TensorFlow and tflearn and it runs just fine but the issue is when the user inputs the wrong thing, the bot is supposed to say it doesnt understand if the prediction accuracy is less than 70%, but the bot always scores above that even if the user gives jibberish like "rjrigrejfr". The bot assumes theyre greeting them. The patterns its supposed to study in the json are "patterns": ["Hi", "How are you", "Wassup", "Hello", "Good day", "Waddup", "Yo"]. I can share the json file if needed its short. Anyway, this is the python code:

import numpy as np
import nltk
import tensorflow
import tflearn
import random
import json
import pickle
# Some extra configuration:
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
nltk.download('punkt')

# Load the data from the json file into a variable.
with open("intents.json") as file:
    data = json.load(file)

# If we already have saved data, we do not need to retrain the model and waste time (could develop into an issue in more complex programs. Save in pickle. )
try:
    with open("data.pickle", "rb") as f: # rb stands for bytes.
        words, labels, training, output = pickle.load(f)

# --- Pre-training data preparation ---
except:
    words = []
    docsx = [] # Stores patterns
    docsy = [] # Stores intents
    labels = [] # All the specific tag values such as greeting, contact, etc.
    for intent in data["intents"]:
        for pattern in intent["patterns"]:

            w = nltk.word_tokenize(pattern)  # nltk function that splits the sentences inside intent into words list.
            words.extend(w) # Add the tokenized list to words list.
            docsx.append(w)
            docsy.append(intent["tag"])  # append the classification of the sentence

            if intent["tag"] not in labels:
                labels.append(intent["tag"])

    words = [stemmer.stem(w.lower()) for w in words if w not in ".?!"]  # Stemming the words to remove unnecessary elements leaving their root. Convert all to lowercase.
    words = sorted(list(set(words))) # Set ensures no duplicate elements then we convert back to list and sort it.
    labels = sorted(labels)

    training = []
    output = []

    out_empty = [0 for i in range(len(labels))] # Gives a list of 0 ints based on # of tags. This is useful later in the program when binerizing.

    # One hot encoding the intent categories. Need to one-hot code the data which improves the efficiency of the ML to "binerize" the data.
    # In this case, we have a list of 0s and 1s if the word appears it is assigned a 1 else a 0.
    for x, doc in enumerate(docsx):
        bag = [] # Bag of words or the one-hot coded data for the ML.

        docx_word_stemmed = [stemmer.stem(word) for word in doc] # Stemming the data in docx.

        # Now adding and transforming data into the one-hot coded list/bag of words data.
        for i in words:
            if i in docx_word_stemmed: # Checking against stemmed words:
                # Word exists
                bag.append(1)
            else:
                bag.append(0)

        output_row = out_empty[:] # Copying out_empty
        # Going through the labels list using .index() and for the occurance of docx value in docy, assign binary 1.
        output_row[labels.index(docsy[x])] = 1

        training.append(bag)
        output.append(output_row)
    # Required to use numpy arrays for use in tflearn. It is also faster.
    training = np.array(training)
    output = np.array(output)

    # Saving the data so we do not need to do the data configuration every time.
    with open("data.pickle", "wb") as f:
        pickle.dump((words, labels, training, output), f)

try:

    model.load('model.tflearn')
except:
    tensorflow.compat.v1.reset_default_graph()

    net = tflearn.input_data(shape=[None, len(training[0])])
    net = tflearn.fully_connected(net, 8)
    net = tflearn.fully_connected(net, 8)
    net = tflearn.fully_connected(net, len(output[0]), activation='softmax')
    net = tflearn.regression(net)

    model = tflearn.DNN(net)

    model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)
    model.save("model.tflearn")

def bagofwords(sentence, words):
    bag = [0 for _ in range(len(words))] # blank bag of words.

    # Tokenize s and then stem it.
    sentence_words = nltk.word_tokenize(sentence)
    sentence_words = [stemmer.stem(word.lower()) for word in sentence_words]

    for string in sentence_words:
        for i, word in enumerate(words):
            if word == string:
                bag[i] = 1
    return np.array(bag)

def chat():
    print("Hello there! I'm the SRO AI Virtual Assistant. How am I help you?")
    # Figure out the error slime!
    while True:
        user_input = input("Type here:")
        if user_input == "quit":
            break
        result = model.predict([bagofwords(user_input, words)])[0] #bagofwords func and predict function to give predictions on what the user is saying.

        best_result = np.argmax(result) # We want to only use the best result.
        tag = labels[best_result]
        print(result[best_result])

        # Open JSON file and pick a response.
        if result[best_result] > 0.7:
            for tg in data["intents"]:
                if tg['tag'] == tag:
                    responses = tg['responses']
            print(random.choice(responses))
        else:
            print("I don't quite understand")

chat()


问:
Magento 2 , how to get the data from page_image_form and change the frontend imagelink?
adminhtml/ui_component/page_image_form.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="advanced">
        <field name="custeom-one" sortOrder="70" formElement="input">
            <settings>
                <dataType>text</dataType>
                <label translate="true">Custom One</label>
            </settings>
        </field>
         <field name="custom-two" sortOrder="70" formElement="input">
            <settings>
                <dataType>text</dataType>
                <label translate="true">Custom Two</label>
            </settings>
        </field>

    </fieldset>
</form>

</code>```

how to get the data from page_image_form and change the frontend imagelink?

i expect the html result as below:

```<code><a href="https://example.com/1.html" target="" data-custom-two="XXXXXdata" data-custom-one="XXXXXdata" data-link-type="default" title="" data-element="link"><img class="pagebuilder-mobile-hidden" src="https://u001.ugg.com.hk/media/wysiwyg/1.jpg" alt="" title="" data-element="desktop_image" data-pb-style="A123456"><img class="pagebuilder-mobile-only" src="https://example.com/media/wysiwyg/1.jpg" alt="" title="" data-element="mobile_image" data-pb-style="A123456"></a>
</code>```

Body:
adminhtml/ui_component/page_image_form.xml :

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="advanced">
        <field name="custeom-one" sortOrder="70" formElement="input">
            <settings>
                <dataType>text</dataType>
                Custom One
            </settings>
        </field>
         <field name="custom-two" sortOrder="70" formElement="input">
            <settings>
                <dataType>text</dataType>
                Custom Two
            </settings>
        </field>

    </fieldset>
</form>

how to get the data from page_image_form and change the frontend imagelink?

i expect the html result as below: