问:
Google Scholar API of SerpApi fetches only first 100 articles from GoogleScholar profile
What am I trying to do ?
I am trying to use SerpApi's Google Scholar API for fetching articles of the publishers and was expecting all article titles to store in the array $title but it limits only to the first 100 articles.

Any Help Would be really appreciated, code :

title.py

```<code>from serpapi import GoogleSearch
import sys

id = sys.argv[1]
key = sys.argv[2]
params = {
  "engine": "google_scholar_author",
  "author_id": id,
  "api_key": key,
  "sort":"pubdate",
  "num":10000
}

search = GoogleSearch(params)
results = search.get_dict()
articles = results["articles"]

res = [ sub['title'] for sub in articles ]

print(res)

</code>```

Controller

```<code>$title = shell_exec("python publicationScripts/title.py $gscID $key");
dd($title);
</code>```

Output

```<code>The output shows only 100 articles but there are more than 200 articles
</code>```

Body:
What am I trying to do ?
I am trying to use SerpApi's Google Scholar API for fetching articles of the publishers and was expecting all article titles to store in the array $title but it limits only to the first 100 articles.

Any Help Would be really appreciated, code :

title.py

from serpapi import GoogleSearch
import sys

id = sys.argv[1]
key = sys.argv[2]
params = {
  "engine": "google_scholar_author",
  "author_id": id,
  "api_key": key,
  "sort":"pubdate",
  "num":10000
}

search = GoogleSearch(params)
results = search.get_dict()
articles = results["articles"]

res = [ sub['title'] for sub in articles ]

print(res)

Controller

$title = shell_exec("python publicationScripts/title.py $gscID $key");
dd($title);

Output

The output shows only 100 articles but there are more than 200 articles


来源: stackexchange

问:
What is the correct executable path to bundle puppeteer sharp C# along with the project in Visual Studio?
I have a Visual Studio C# winform project using puppeteer sharp, it runs fine inside Visual Studio enviroment, but when I publish the project it seems it isn't finding the chrome.exe, I need to bundle the executable along with the project, what should I do to make it work?

What is the right relative executable path to put in bellow's code to work when bundled/published:

```<code>        browser = await Puppeteer.LaunchAsync(new LaunchOptions
        {
            Headless = true,
            DefaultViewport = null,
            ExecutablePath = ?? //what Do I put here?
        });
</code>```

Are there any other measures beyond defining the ExecutablePath parameter above?

My executable is located in:

```<code>    ...\bin\Debug\.local-chromium\Win64-970485\chrome-win\chrome.exe
</code>```

Running from inside Visual Studio, works that way:

```<code>        browser = await Puppeteer.LaunchAsync(new LaunchOptions
        {
            Headless = true,
            DefaultViewport = null,
            ExecutablePath = AppDomain.CurrentDomain.BaseDirectory + @"\.local-chromium\Win64-970485\chrome-win\chrome.exe"
        });
</code>```

But it doesn't work for the published project when bundled.

Thanks in advance.

ContentLicense: CC BY-SA 4.0

Body:
I have a Visual Studio C# winform project using puppeteer sharp, it runs fine inside Visual Studio enviroment, but when I publish the project it seems it isn't finding the chrome.exe, I need to bundle the executable along with the project, what should I do to make it work?

What is the right relative executable path to put in bellow's code to work when bundled/published:

        browser = await Puppeteer.LaunchAsync(new LaunchOptions
        {
            Headless = true,
            DefaultViewport = null,
            ExecutablePath = ?? //what Do I put here?
        });

Are there any other measures beyond defining the ExecutablePath parameter above?

My executable is located in:

    ...\bin\Debug\.local-chromium\Win64-970485\chrome-win\chrome.exe

Running from inside Visual Studio, works that way:

        browser = await Puppeteer.LaunchAsync(new LaunchOptions
        {
            Headless = true,
            DefaultViewport = null,
            ExecutablePath = AppDomain.CurrentDomain.BaseDirectory + @"\.local-chromium\Win64-970485\chrome-win\chrome.exe"
        });

But it doesn't work for the published project when bundled.

Thanks in advance.


问:
Why data is not getting pushed in the array?
This is the Cart.jsx,

```<code>import { createContext, useEffect } from "react"
import "./Cart.css"
import Cake from "../About Section/Cake";
const PdtList = createContext();
let list = [];
export default function Cart() {
    return (
        <>
            <main className="align" >
                <h1>Thanks for shopping with us</h1>
                <PdtList.Provider value={list}>
                    <Cake />
                </PdtList.Provider>

            </main>
        </>
    )
}
export { PdtList };
</code>```

And this is the Cake.jsx

```<code>import "./Product.css"
import { PdtList } from "../Cart/Cart";
import { useContext  , useState , useEffect} from "react";
export default function Cake(props) {
  const { name, images, bold, cut } = props;
  const newList = useContext(PdtList);
  console.log("this is something " , newList);
  const [value, setvalue] = useState(newList);
  const Add_Products = (index) => {
    // console.log('Add_Products called');
    let tobeAdded = { name, images, bold };
    setvalue((e) => [...e, tobeAdded]);
  }
  useEffect(() => {
    console.log(value);
  }, [value])
    return (
        <>
            <main className="align unique">
                <img src={images} alt="" />
                <h1>{name}</h1>
                <div className="align2">
                    <small>Rs {bold}</small>
                    <small style={{ "margin": "0px 10px" }} ></small>
                    <small style={{ "font-size": "15px", "textDecoration": "line-through" }} >Rs {cut}</small>
                </div>
                <button onClick={Add_Products} style={{ "margin": "10px 0px" }}>Add to Cart</button>
            </main>
        </>
    )
}
</code>```

I was trying to use useContext but I am not able to push data in the array in Cake.jsx using useState.

The error is Uncaught TypeError: e is not iterable.

Body:
This is the Cart.jsx,

import { createContext, useEffect } from "react"
import "./Cart.css"
import Cake from "../About Section/Cake";
const PdtList = createContext();
let list = [];
export default function Cart() {
    return (
        <>

Thanks for shopping with us

                <PdtList.Provider value={list}>
                    <Cake />
                </PdtList.Provider>

        </>
    )
}
export { PdtList };

And this is the Cake.jsx

import "./Product.css"
import { PdtList } from "../Cart/Cart";
import { useContext  , useState , useEffect} from "react";
export default function Cake(props) {
  const { name, images, bold, cut } = props;
  const newList = useContext(PdtList);
  console.log("this is something " , newList);
  const [value, setvalue] = useState(newList);
  const Add_Products = (index) => {
    // console.log('Add_Products called');
    let tobeAdded = { name, images, bold };
    setvalue((e) => [...e, tobeAdded]);
  }
  useEffect(() => {
    console.log(value);
  }, [value])
    return (
        <>

{name}

                    Rs {bold}

                    Rs {cut}

                <button onClick={Add_Products} style={{ "margin": "10px 0px" }}>Add to Cart</button>

        </>
    )
}

I was trying to use useContext but I am not able to push data in the array in Cake.jsx using useState.

The error is Uncaught TypeError: e is not iterable.


问:
Any text is accepted in the text field, instead of a certain string
The user must enter his username in the text field of the form. The accepted username is retrieved from the server and is 'Bret'. But everything the user enters in the field is accepted. How can I solve this problem?

app.component.html

```<code><div id="details">
  <form [formGroup]="form" (ngSubmit)="addDetails()">

    <div class="form-group">

      <label for="s_url">URL:</label>
      <br>
      <input style="width:80%" type="text" id="s_url" formControlName="s_url" />
      <div style="color:red" *ngIf="s_url.value && s_url.invalid">
        not a valid URL
      </div>

    </div>
    <br>
    <button type="submit" [disabled]="form.invalid">Submit</button>
    <br>

    <hr>

    Form status:
    <span [style.color]="form.status === 'VALID' ? 'green' : 'red'">
      {{ form.status }}
    </span>

    <hr>
    ```Form values: {{ form.value | json }}```
    <hr>

  </form>
</div>
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { RouterModule } from '@angular/router';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((json) => {
        console.log(json[0].username);
        this.reg = json[0].username;
      });

    const reg = this.reg;
    this.form = this.fb.group({
      s_url: ['', [Validators.required, Validators.pattern(reg)]],
    });
  }

  // Getter for easy access
  get s_url() {
    return this.form.get('s_url');
  }

  // On submit
  addDetails() {}
}
</code>```

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, ReactiveFormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code>```

Here is the live example: https://stackblitz.com/edit/angular-1kyxry

Body:
The user must enter his username in the text field of the form. The accepted username is retrieved from the server and is 'Bret'. But everything the user enters in the field is accepted. How can I solve this problem?

app.component.html

  <form [formGroup]="form" (ngSubmit)="addDetails()">

      URL:

      <input style="width:80%" type="text" id="s_url" formControlName="s_url" />

        not a valid URL

    <button type="submit" [disabled]="form.invalid">Submit</button>

    Form status:

      {{ form.status }}

Form values: {{ form.value | json }}

  </form>

app.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { RouterModule } from '@angular/router';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((json) => {
        console.log(json[0].username);
        this.reg = json[0].username;
      });

    const reg = this.reg;
    this.form = this.fb.group({
      s_url: ['', [Validators.required, Validators.pattern(reg)]],
    });
  }

  // Getter for easy access
  get s_url() {
    return this.form.get('s_url');
  }

  // On submit
  addDetails() {}
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, ReactiveFormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Here is the live example: https://stackblitz.com/edit/angular-1kyxry


问:
Python-docx: no style with name "Heading 1"
I have been generating .docx files with python-docx for a while now and it worked well. Since the documents I have to produce need to stick with a certain size limit which it exceeded lately I tried to edit the "default.docx" file directly, which serves as a basis for the library, to decrease spacing before and after headings.

Ever since I did that, I receive the error message "Key Error: "no style with name Heading 1"

I have tried to follow advice issued here by creating and deleting paragraphs with the applicable updated styles in the document but to no avail.

I am using python-docx version 0.8.11 and Linux / LibreOffice Writer.

Example code triggering the error:

```<code>from docx import Document
doc = Document()
doc.add_heading("hello", 1)
</code>```

Body:
I have been generating .docx files with python-docx for a while now and it worked well. Since the documents I have to produce need to stick with a certain size limit which it exceeded lately I tried to edit the "default.docx" file directly, which serves as a basis for the library, to decrease spacing before and after headings.

Ever since I did that, I receive the error message "Key Error: "no style with name Heading 1"

I have tried to follow advice issued here by creating and deleting paragraphs with the applicable updated styles in the document but to no avail.

I am using python-docx version 0.8.11 and Linux / LibreOffice Writer.

Example code triggering the error:

from docx import Document
doc = Document()
doc.add_heading("hello", 1)


问:
How can I evaluate unsupervised learning if I have labels? How do I know which label is corresponding to which cluster class?
I have small dataset, I did clustering with  features of dataset,not label is included,  so I have now predicted class and labels. I need to evaluate it with sklearn.metrics. But how do I know which label is corresponding to which prediction value? I had 7 labels and got 7 predictions for them.

Here b5 is 1 maybe or b2 is 2, so I can not match them. Please guide me.

```<code>def kmeans(df):
  from sklearn.cluster import KMeans #importing the libery
  km=KMeans(n_clusters=len(df['class'].unique()))
  global y_predicted # I making it global so i can use it outside of the function
  y_predicted=km.fit_predict(df[['x','y']])
  df['prediction']=y_predicted
  return df
df=kmeans(df)

</code>```

I tried to give label encoder for class column, but it also gave different labels, it did not match. Thanks in advance.

Body:
I have small dataset, I did clustering with  features of dataset,not label is included,  so I have now predicted class and labels. I need to evaluate it with sklearn.metrics. But how do I know which label is corresponding to which prediction value? I had 7 labels and got 7 predictions for them.

Here b5 is 1 maybe or b2 is 2, so I can not match them. Please guide me.

def kmeans(df):
  from sklearn.cluster import KMeans #importing the libery
  km=KMeans(n_clusters=len(df['class'].unique()))
  global y_predicted # I making it global so i can use it outside of the function
  y_predicted=km.fit_predict(df[['x','y']])
  df['prediction']=y_predicted
  return df
df=kmeans(df)

I tried to give label encoder for class column, but it also gave different labels, it did not match. Thanks in advance.


问:
Is there a way to get a callback in Python, whenever something gets printed to stdout in a thread?
I want to monitor the stdout of a program and whenever it prints something into stdout, I want to get a callback in python to process the gathered data.

The program I want to monitor is not written in python, but behaves similar to this dummy_script.py:

```<code>import datetime
import random
import time

i = 0
while True:
    line = f"{datetime.datetime.now()} {i}"
    print(line)
    i += 1
    time.sleep(random.uniform(0, 1))
</code>```

For the main python script I tried something like this:

```<code>from threading import Thread
import os

def do_stuff():
    command = f"python3 dummy_script.py"
    os.system(command)

thread = Thread(target=do_stuff)
thread.daemon = True
thread.start()
</code>```

So is there a way to create a callback when a new line is printed to stdout?

Body:
I want to monitor the stdout of a program and whenever it prints something into stdout, I want to get a callback in python to process the gathered data.

The program I want to monitor is not written in python, but behaves similar to this dummy_script.py:

import datetime
import random
import time

i = 0
while True:
    line = f"{datetime.datetime.now()} {i}"
    print(line)
    i += 1
    time.sleep(random.uniform(0, 1))

For the main python script I tried something like this:

from threading import Thread
import os

def do_stuff():
    command = f"python3 dummy_script.py"
    os.system(command)

thread = Thread(target=do_stuff)
thread.daemon = True
thread.start()

So is there a way to create a callback when a new line is printed to stdout?


问:
How to dispatch gesture from AccessibilityService onGesture
I'm trying to build an app that can detect different gestures and then perform some action. I'm able to detect gestures using AccessibilityService onGesture method.

But I want to dispatch the gesture so that user actions are not blocked. How can I dispatchGesture from AccessibilityService onGesture method

```<code>public class MyAccessibilityService extends AccessibilityService {

    private static final String TAG = "MyAccessibilityService";

    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
        Log.d(TAG, "onAccessibilityEvent: " + accessibilityEvent.getEventType());
    }

    @Override
    public void onInterrupt() {
        Log.e(TAG, "onInterrupt: something went wrong");
    }

    @Override
    public boolean onGesture(@NonNull AccessibilityGestureEvent gestureEvent) {
        super.onGesture(gestureEvent);
        int gestureId = gestureEvent.getGestureId();

        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();

        Log.d(TAG, "onGesture: Gesture Detected " + gestureId);
        switch (gestureId){
            case 17:
                Log.d(TAG, "onGesture: Double Tap Happened");
        }

        GestureDescription gestureDescription = new GestureDescription.Builder().build();
        dispatchGesture(gestureDescription, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
            }
        }, null);

        return true;
    }

}
</code>```

Body:
I'm trying to build an app that can detect different gestures and then perform some action. I'm able to detect gestures using AccessibilityService onGesture method.

But I want to dispatch the gesture so that user actions are not blocked. How can I dispatchGesture from AccessibilityService onGesture method

public class MyAccessibilityService extends AccessibilityService {

    private static final String TAG = "MyAccessibilityService";

    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
        Log.d(TAG, "onAccessibilityEvent: " + accessibilityEvent.getEventType());
    }

    @Override
    public void onInterrupt() {
        Log.e(TAG, "onInterrupt: something went wrong");
    }

    @Override
    public boolean onGesture(@NonNull AccessibilityGestureEvent gestureEvent) {
        super.onGesture(gestureEvent);
        int gestureId = gestureEvent.getGestureId();

        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();

        Log.d(TAG, "onGesture: Gesture Detected " + gestureId);
        switch (gestureId){
            case 17:
                Log.d(TAG, "onGesture: Double Tap Happened");
        }

        GestureDescription gestureDescription = new GestureDescription.Builder().build();
        dispatchGesture(gestureDescription, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
            }
        }, null);

        return true;
    }

}


问:
Why? NotAllowedError: The request is not allowed by the user agent or the platform in the current context
Full error: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

Why I got first time, but not second when sharing file?

const shareData = {
  files: [
    new File([buffer], `${imgId}.mp4`, {
      type: "video/mp4",
    }),
  ],
  title: "Megosztom",
  text: "Mentsd le a képekbe, és oszd meg storyban.",
};
```
<pre class="lang-js prettyprint-override"><code>navigator
  .share(shareData)
  .then(() => {
    log(
      {
        text: `'The share was successful 1 ` + getTempUserShortId(),
      },
      env
    );
  })
  .catch((error) => {
    log(
      {
        text: `There was an error sharing 1 ${error} ` + getTempUserShortId(),
      },
      env
    );
  });
</code>```

Body:
Full error: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

Why I got first time, but not second when sharing file?

const shareData = {
  files: [
    new File([buffer], `${imgId}.mp4`, {
      type: "video/mp4",
    }),
  ],
  title: "Megosztom",
  text: "Mentsd le a képekbe, és oszd meg storyban.",
};

navigator
  .share(shareData)
  .then(() => {
    log(
      {
        text: `'The share was successful 1 ` + getTempUserShortId(),
      },
      env
    );
  })
  .catch((error) => {
    log(
      {
        text: `There was an error sharing 1 ${error} ` + getTempUserShortId(),
      },
      env
    );
  });


问:
Stacking classifier in mlxtend have not attribute for transfer learning to get pretrained weights of own model. How to implement transfer learning?
I have developed stacking classifier with DL models in mlxtend library and have trained it, now i want its weights for transfer learning but mlxtend stacking classifier have not attribute to got weights for transfer how can i implement transfer learning?

link of stacking classifier

http://rasbt.github.io/mlxtend/user_guide/classifier/StackingClassifier/


问:
how to do audioPlayer`s notification in flutter?
im making audio player with flutter and i wanna make undraggable notification in which i ll have next, prev, play/pause, add to favorite, change looping mod and dispose the notification actions (last not important). how i can do it?

i use assets_audio_player package but there i can not add all my action and i looked for in flutter_local_notifications package but also found nothing yet


问:
Read USB port on Raspberry Pi Pico with alternative to pyserial
I'm trying to read out a USB-connected device hooked onto my Raspberry Pi Pico using Micropython. In CPython it's quite easily done using the pyserial lib:

import serial # <-- the problem: not available in micropython?

ser = serial.Serial()
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.xonxoff = 0
ser.rtscts = 0
ser.timeout = 12

# configure usb port
ser.port = "/dev/ttyUSB0"
ser.close()

try:
    ser.open()

    raw_msg = ser.readline()
    decoded = raw_msg.decode('ascii').strip()
except:
    sys.exit(f'Error on {ser.name}')
finally:
    ser.close
```

However, considering pyserial isn't available in micropython, how can I achieve the same without pyserial? I.e. how to read data from a USB connected device using Micropython.

Please note that I'm new to specifically micropython and I haven't found a good example for reading out USB data yet.

Body:
I'm trying to read out a USB-connected device hooked onto my Raspberry Pi Pico using Micropython. In CPython it's quite easily done using the pyserial lib:

import serial # <-- the problem: not available in micropython?

ser = serial.Serial()
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.xonxoff = 0
ser.rtscts = 0
ser.timeout = 12

# configure usb port
ser.port = "/dev/ttyUSB0"
ser.close()

try:
    ser.open()

    raw_msg = ser.readline()
    decoded = raw_msg.decode('ascii').strip()
except:
    sys.exit(f'Error on {ser.name}')
finally:
    ser.close

However, considering pyserial isn't available in micropython, how can I achieve the same without pyserial? I.e. how to read data from a USB connected device using Micropython.

Please note that I'm new to specifically micropython and I haven't found a good example for reading out USB data yet.


问:
How to pause and resume jobs in 'APScheduler' using tags similar in 'schedule' library?
I want to pause a scheduled job for specific days and resume later. In 'Schedule' library there is something called tag (can use same name for multiple jobs). But in 'APScheduler', it has something called 'id' and it must be unique per job.

Eg in schedule: schedule.every().day.at(rec_time).do(curr_job, pass_audio=audiofile).tag('regular-days', 'mon-fri')

Eg in APScheduler: sched.add_job(regularjob, 'cron', day_of_week='sat', hour='20', minute='01', args=[audiofile], id = 'regular1')

Pausing and resuming jobs are difficult in this library, is there a better way to do this?

I want to pause/resume/cancel all jobs in 1 single go, like this

schedule.clear('regular-days') #Cancel Jobs by tag


问:
Serving favicon.ico for Googlebot in Flask
I have a favicon.ico in my Flask app's html. The google bot wants to index it and of course it gets an error since I have it in my static folder and it has the /static/favicon.ico code in my html as well. I didn't link it at all like /favicon.ico.

```<code>66.249.64.15 - - [07/Jan/2023:11:50:58 +0000] "GET /favicon.ico HTTP/1.1" 301 289 "-" "Googlebot-Image/1.0" "66.249.64.15" response-time=0.001
66.249.64.11 - - [07/Jan/2023:11:50:58 +0000] "GET /favicon.ico/ HTTP/1.1" 500 291 "-" "Googlebot-Image/1.0" "66.249.64.11" response-time=0.025
66.249.64.13 - - [07/Jan/2023:11:50:59 +0000] "GET /favicon.ico/ HTTP/1.1" 500 291 "-" "Googlebot-Image/1.0" "66.249.64.13" response-time=0.011
</code>```

My question is how should I handle this situation? I want to fix the above 500 error codes. My first idea would be something like this:

```<code>@app.route('/favicon.ico')
def static_from():
    return send_from_directory(app.static_folder, request.path[1:])
</code>```

Is this the correct solution? Or is there a better one?

Body:
I have a favicon.ico in my Flask app's html. The google bot wants to index it and of course it gets an error since I have it in my static folder and it has the /static/favicon.ico code in my html as well. I didn't link it at all like /favicon.ico.

66.249.64.15 - - [07/Jan/2023:11:50:58 +0000] "GET /favicon.ico HTTP/1.1" 301 289 "-" "Googlebot-Image/1.0" "66.249.64.15" response-time=0.001
66.249.64.11 - - [07/Jan/2023:11:50:58 +0000] "GET /favicon.ico/ HTTP/1.1" 500 291 "-" "Googlebot-Image/1.0" "66.249.64.11" response-time=0.025
66.249.64.13 - - [07/Jan/2023:11:50:59 +0000] "GET /favicon.ico/ HTTP/1.1" 500 291 "-" "Googlebot-Image/1.0" "66.249.64.13" response-time=0.011

My question is how should I handle this situation? I want to fix the above 500 error codes. My first idea would be something like this:

@app.route('/favicon.ico')
def static_from():
    return send_from_directory(app.static_folder, request.path[1:])

Is this the correct solution? Or is there a better one?


问:
Sharp put images side by side with a linear gradient transition between images
I'm trying to use the sharp library to put images side by side but can't get a linear transition between the images to work, what's the correct way to do that?

This is a sample output without the linear gradient:

I tried multiple blend modes but they all don't yield the result I'd like to have, perhaps do I need an SVG linear gradient between the images?

    const overlayPixels = 50;

    const buffer = await sharp({
      create: {
        width: 2048,
        height: 512,
        channels: 4,
        background: { r: 255, g: 255, b: 255, alpha: 0 },
      },
    })
      .composite([
        { input: "./images/1.png", left: 0, top: 0 },
        {
          input: Buffer.from([0, 0, 0, 255]),
          raw: {
            width: 1,
            height: 1,
            channels: 4,
          },
          blend: "multiply",
        },
        {
          input: "./images/2.png",
          left: 512 - overlayPixels,
          top: 0,
        },
        {
          input: "./images/3.png",
          left: 1024 - overlayPixels,
          top: 0,
        },
        {
          input: "./images/4.png",
          left: 1536 - overlayPixels,
          top: 0,
        },
      ])
      .toFormat("jpeg")
      .toBuffer();

    fs.writeFileSync(`./output.jpg`, buffer);
```


问:
JS-echart-histpgram-X axis
blue is the standard, the red is current mine
compared with these two diagrams, I do not no how to design the x-axis in the blue diagram, which is a range to describe the data.

Now, I using an array to store all value displayed, and on the y-axis, another array stores the times of each number displays. But I do not know make the X-axis to be a range.

```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style>
    .box {
        width: 1000px;
        height: 400px;
        background-color: pink;
    }
</style></code>```

    <input type="file" onchange="readExcel(this)" />

 ```

Title: JS-echart-histpgram-X axis

Body:
blue is the standard, the red is current mine
compared with these two diagrams, I do not no how to design the x-axis in the blue diagram, which is a range to describe the data.

Now, I using an array to store all value displayed, and on the y-axis, another array stores the times of each number displays. But I do not know make the X-axis to be a range.

    <input type="file" onchange="readExcel(this)" />


问:
Change color of ASCII code from live input according to sound frequency
I am new to coding and I'm trying to make an ascii code from a live input (my video camera) that changes color depending on sound frequency (using FFT, still not gotten into that part). I am using a pixel array in order to get the brightness of my image and convert it into ascii using a density. I have not been able to change the color inside my sketch code, but I could change it writing some code in my html file (which is not what I want since I need to get some sound frequencies in order to change the color of the pixel array I have created for my density).

Could someone please help me out on this?

let capture; //to manipulate the video I'm getting
const density = "Ñ@#W$9876543210?!abc;:+=-,._                            "; //string to use as     image for video
let asciiDiv;

function setup() {
  createCanvas();
  background(0);
  capture = createCapture(VIDEO); //input webcam video
  capture.size(192,96);
  asciiDiv = createDiv();
  //capture.hide(); //hide the video outside the canvas
}

function draw() {
  capture.loadPixels();
  let asciiImage = '';
  //let co = color(202, 102, 232);
for (let j = 0; j < capture.height; j++) {
  for (let i = 0; i < capture.width; i++) {
  const pixelIndex = (i + j * capture.width) * 4;
  const r = capture.pixels[pixelIndex + 0];
  const g = capture.pixels[pixelIndex + 1];
  const b = capture.pixels[pixelIndex + 2];
  const avg = (r + g + b) / 3;
  const len = density.length;
  //noStroke();

  fill(202, 102, 232);
  const charIndex = floor(map(avg, 0, 255, len, 0));

  const c = density.charAt(charIndex);
  if (c == ' ') asciiImage += ' '
  else asciiImage += c;

}
asciiImage += '
';
}
asciiDiv.html(asciiImage);

  }
```
<pre class="lang-css prettyprint-override"><code>html, body {
  margin: 0;
  padding: 0;
  background-color: #000;
  color: #d9b3ff; //the color I want to put inside the pixel array and change with sound frequency
  font-family: 'Courier';
  font-size: 24pt;
  line-height: 20pt;
}
canvas {
  display: block;
}
</code>```

I have tried to declare fill(); before my pixel array, I have tried to declare fill(); before the constant I created and nothing seems to work! This only to change the color inside my sketch and not do it on the html file.

Body:
I am new to coding and I'm trying to make an ascii code from a live input (my video camera) that changes color depending on sound frequency (using FFT, still not gotten into that part). I am using a pixel array in order to get the brightness of my image and convert it into ascii using a density. I have not been able to change the color inside my sketch code, but I could change it writing some code in my html file (which is not what I want since I need to get some sound frequencies in order to change the color of the pixel array I have created for my density).

Could someone please help me out on this?

let capture; //to manipulate the video I'm getting
const density = "Ñ@#W$9876543210?!abc;:+=-,._                            "; //string to use as     image for video
let asciiDiv;

function setup() {
  createCanvas();
  background(0);
  capture = createCapture(VIDEO); //input webcam video
  capture.size(192,96);
  asciiDiv = createDiv();
  //capture.hide(); //hide the video outside the canvas
}

function draw() {
  capture.loadPixels();
  let asciiImage = '';
  //let co = color(202, 102, 232);
for (let j = 0; j < capture.height; j++) {
  for (let i = 0; i < capture.width; i++) {
  const pixelIndex = (i + j * capture.width) * 4;
  const r = capture.pixels[pixelIndex + 0];
  const g = capture.pixels[pixelIndex + 1];
  const b = capture.pixels[pixelIndex + 2];
  const avg = (r + g + b) / 3;
  const len = density.length;
  //noStroke();

  fill(202, 102, 232);
  const charIndex = floor(map(avg, 0, 255, len, 0));

  const c = density.charAt(charIndex);
  if (c == ' ') asciiImage += ' '
  else asciiImage += c;

}
asciiImage += '
';
}
asciiDiv.html(asciiImage);

  }

html, body {
  margin: 0;
  padding: 0;
  background-color: #000;
  color: #d9b3ff; //the color I want to put inside the pixel array and change with sound frequency
  font-family: 'Courier';
  font-size: 24pt;
  line-height: 20pt;
}
canvas {
  display: block;
}

I have tried to declare fill(); before my pixel array, I have tried to declare fill(); before the constant I created and nothing seems to work! This only to change the color inside my sketch and not do it on the html file.


问:
How to filter out signal repetition when you are using IIF(BUY,,) condition on a 5 min chart since Buy is true for each tick in 5 min candle
I've created an AFL script that sends Buy, Stoploss, and Target values directly to my telegram with the help of a telegram bot. I've made it call the telegram sender function when the buy is true. But the problem is that since buy will be true for a whole candle so when I switch to for example 5 minute candle it sends me that buy signal 5 times (since I'm backtesting with a 1minute bar replay)

I tried using additional variables to set the telegram parameters value to zero when buy is not true and then process telegram sender only when the set parameter has non zero value, but still since buy will be true for the whole candle so the parameter is getting non-zero value for each tick for if the tick belonging to the same candle. For your reference here is the complete code. (With Bot API's removed)

```<code>_SECTION_BEGIN("5min EMA Longing");

 FirstTradeTime = 094500;
 LastTradeTime = 151500;

function writecsv( pricetowrite, wrtitethis )
{
if (StrFind(pricetowrite,"0.000"))
{
}
else
{
   fh = fopen( "C:\\Users\\<username>\\Desktop\\newfile.csv", "a");
    if(fh)
{
    fputs(wrtitethis+"\n", fh );
    fclose(fh);
    ih = InternetOpenURL("https://api.telegram.org/bot<ChatID>:<API>/sendMessage?chat_id=1487299238&text="+wrtitethis);
    InternetClose(ih);
    }
    else
    {
       printf("Error opening file");
    }
}
}

 //Current candle data
 CandleOpen = TimeFrameGetPrice("O",in5Minute); //as it is fixed
 CandleHigh = TimeFrameGetPrice("H",in5Minute); //as it is fixed
 CandleLow = TimeFrameGetPrice("L",in5Minute); //as it is fixed
 CandleClose = TimeFrameGetPrice("C",in5Minute); //as it is fixed

 //Prev candle's data
 PrevCanOpen = TimeFrameGetPrice("H",in5Minute,-1);
 PrevCanHigh = TimeFrameGetPrice("H",in5Minute,-1);
 PrevCanLow = TimeFrameGetPrice("L",in5Minute,-1);
 PrevCanClose = TimeFrameGetPrice("C",in5Minute,-1);

Ema5 = ref(EMA(Close,5),-1); //5 period EMA
HighNotLow = PrevCanHigh-PrevCanLow;
Ema20 = EMA(close,20);
Rsi15 = RSI(14);
EMA20_Slope = Ema20 - ref(EMA(Close,20),-6);
//EMA20_Slope = 0;
indicator1 = PrevCanOpen<Ema5 AND PrevCanHigh<Ema5 AND PrevCanLow<Ema5 AND PrevCanClose<Ema5 AND CandleHigh>=PrevCanHigh; //main 5EMA strategy
indicator2 = EMA20_Slope>=0; //20 EMA slope or RSI indicating buy zone
BUY = indicator1 AND indicator2 AND HighNotLow>0 AND (TimeNum() >=FirstTradeTime AND TimeNum()<= LastTradeTime);

BuyPrice = HighestSince(Buy,Ref(H,-1));

stopLevelLong = ValueWhen(Buy, Ref(Low,-1));
PriceBuy = ValueWhen(Buy, BuyPrice); //entry price
stopAmountLong = PriceBuy-stopLevelLong;
targetAmountLong = 2*stopAmountLong;

Stoploss = stopAmountLong;
Target = targetAmountLong;
Plot(PriceBuy ,"Bought Price",colorGreen);  //drawing entry price
Plot(PriceBuy-Stoploss ,"Stoploss",colorAqua);  //drawing entry price
Plot(PriceBuy+Target ,"Target",colorYellow);    //drawing entry price

ApplyStop(Type=0,Mode=2,Amount=Stoploss);
ApplyStop(Type=1,Mode=2,Amount=Target);

Sell = (((HighestSince(Buy,H)>PriceBuy+Target) OR (LOWESTSince(Buy,L)<PriceBuy-Stoploss)) AND (TimeNum() >=FirstTradeTime AND TimeNum()<= LastTradeTime)) OR TimeNum()>= LastTradeTime;
BUY = ExRem(BUY,Sell);
timenow = ValueWhen(Buy, TimeNum());
priceto = IIf(Buy,PriceBuy,null);
timenow = NumToStr(timenow,1);
timenow = StrReplace(timenow,",",".");
//logging

wrtitethis =Name()+" "+timenow +", BUY: "+NumToStr(PriceBuy)+", SL: "+NumToStr(PriceBuy-Stoploss)+", TG: "+NumToStr(PriceBuy+Target);

writecsv( NumToStr(LastValue(priceto)),wrtitethis);
//logging

Sell = ExRem(Sell,buy);

PlotShapes(IIf(Buy,shapeUpArrow,shapeNone),colorYellow,0,L,offset=-50);
PlotShapes(IIf(Sell AND (HighestSince(Buy,H)>PriceBuy+Target),shapedownArrow,shapeNone),colorGreen,0,H,offset=-50);
PlotShapes(IIf(Sell AND (LOWESTSince(Buy,L)<PriceBuy-Stoploss),shapedownArrow,shapeNone),colorRed,0,H,offset=-50);
PlotShapes(IIf(Sell AND TimeNum()>= LastTradeTime,shapedownArrow,shapeNone),colorAqua,0,H,offset=-50);

//Show bar index on selection
bi = BarIndex();
sar1 = SAR(0.01);
sarsigs = C < sar1 AND Ref(C,-1) > Ref(sar1,-1);
// Here I changed SelectedValue() to LastValue()
lastSarSiggBarNum = LastValue(ValueWhen(sarsigs, bi));
_TRACE("Last Bar Num for sarsigs: " + lastSarSiggBarNum);
PlotText(StrFormat("%1.0f", lastSarSiggBarNum), lastSarSiggBarNum, sar1[lastSarSiggBarNum], colorWhite, colorRed);
currentlySelectedBarNum = SelectedValue(bi);
_TRACE("Currently selected BarNum " + currentlySelectedBarNum);
// plot the current bar text at the close price level
PlotText(StrFormat("%1.0f", currentlySelectedBarNum), currentlySelectedBarNum, C[currentlySelectedBarNum], colorBlack, colorAqua, 10);
//Show bar index on selection

_SECTION_END();
</code>```

Body:
I've created an AFL script that sends Buy, Stoploss, and Target values directly to my telegram with the help of a telegram bot. I've made it call the telegram sender function when the buy is true. But the problem is that since buy will be true for a whole candle so when I switch to for example 5 minute candle it sends me that buy signal 5 times (since I'm backtesting with a 1minute bar replay)

I tried using additional variables to set the telegram parameters value to zero when buy is not true and then process telegram sender only when the set parameter has non zero value, but still since buy will be true for the whole candle so the parameter is getting non-zero value for each tick for if the tick belonging to the same candle. For your reference here is the complete code. (With Bot API's removed)

_SECTION_BEGIN("5min EMA Longing");

 FirstTradeTime = 094500;
 LastTradeTime = 151500;

function writecsv( pricetowrite, wrtitethis )
{
if (StrFind(pricetowrite,"0.000"))
{
}
else
{
   fh = fopen( "C:\\Users\\<username>\\Desktop\\newfile.csv", "a");
    if(fh)
{
    fputs(wrtitethis+"\n", fh );
    fclose(fh);
    ih = InternetOpenURL("https://api.telegram.org/bot<ChatID>:<API>/sendMessage?chat_id=1487299238&text="+wrtitethis);
    InternetClose(ih);
    }
    else
    {
       printf("Error opening file");
    }
}
}

 //Current candle data
 CandleOpen = TimeFrameGetPrice("O",in5Minute); //as it is fixed
 CandleHigh = TimeFrameGetPrice("H",in5Minute); //as it is fixed
 CandleLow = TimeFrameGetPrice("L",in5Minute); //as it is fixed
 CandleClose = TimeFrameGetPrice("C",in5Minute); //as it is fixed

 //Prev candle's data
 PrevCanOpen = TimeFrameGetPrice("H",in5Minute,-1);
 PrevCanHigh = TimeFrameGetPrice("H",in5Minute,-1);
 PrevCanLow = TimeFrameGetPrice("L",in5Minute,-1);
 PrevCanClose = TimeFrameGetPrice("C",in5Minute,-1);

Ema5 = ref(EMA(Close,5),-1); //5 period EMA
HighNotLow = PrevCanHigh-PrevCanLow;
Ema20 = EMA(close,20);
Rsi15 = RSI(14);
EMA20_Slope = Ema20 - ref(EMA(Close,20),-6);
//EMA20_Slope = 0;
indicator1 = PrevCanOpen<Ema5 AND PrevCanHigh<Ema5 AND PrevCanLow<Ema5 AND PrevCanClose<Ema5 AND CandleHigh>=PrevCanHigh; //main 5EMA strategy
indicator2 = EMA20_Slope>=0; //20 EMA slope or RSI indicating buy zone
BUY = indicator1 AND indicator2 AND HighNotLow>0 AND (TimeNum() >=FirstTradeTime AND TimeNum()<= LastTradeTime);

BuyPrice = HighestSince(Buy,Ref(H,-1));

stopLevelLong = ValueWhen(Buy, Ref(Low,-1));
PriceBuy = ValueWhen(Buy, BuyPrice); //entry price
stopAmountLong = PriceBuy-stopLevelLong;
targetAmountLong = 2*stopAmountLong;

Stoploss = stopAmountLong;
Target = targetAmountLong;
Plot(PriceBuy ,"Bought Price",colorGreen);  //drawing entry price
Plot(PriceBuy-Stoploss ,"Stoploss",colorAqua);  //drawing entry price
Plot(PriceBuy+Target ,"Target",colorYellow);    //drawing entry price

ApplyStop(Type=0,Mode=2,Amount=Stoploss);
ApplyStop(Type=1,Mode=2,Amount=Target);

Sell = (((HighestSince(Buy,H)>PriceBuy+Target) OR (LOWESTSince(Buy,L)<PriceBuy-Stoploss)) AND (TimeNum() >=FirstTradeTime AND TimeNum()<= LastTradeTime)) OR TimeNum()>= LastTradeTime;
BUY = ExRem(BUY,Sell);
timenow = ValueWhen(Buy, TimeNum());
priceto = IIf(Buy,PriceBuy,null);
timenow = NumToStr(timenow,1);
timenow = StrReplace(timenow,",",".");
//logging

wrtitethis =Name()+" "+timenow +", BUY: "+NumToStr(PriceBuy)+", SL: "+NumToStr(PriceBuy-Stoploss)+", TG: "+NumToStr(PriceBuy+Target);

writecsv( NumToStr(LastValue(priceto)),wrtitethis);
//logging

Sell = ExRem(Sell,buy);

PlotShapes(IIf(Buy,shapeUpArrow,shapeNone),colorYellow,0,L,offset=-50);
PlotShapes(IIf(Sell AND (HighestSince(Buy,H)>PriceBuy+Target),shapedownArrow,shapeNone),colorGreen,0,H,offset=-50);
PlotShapes(IIf(Sell AND (LOWESTSince(Buy,L)<PriceBuy-Stoploss),shapedownArrow,shapeNone),colorRed,0,H,offset=-50);
PlotShapes(IIf(Sell AND TimeNum()>= LastTradeTime,shapedownArrow,shapeNone),colorAqua,0,H,offset=-50);

//Show bar index on selection
bi = BarIndex();
sar1 = SAR(0.01);
sarsigs = C < sar1 AND Ref(C,-1) > Ref(sar1,-1);
// Here I changed SelectedValue() to LastValue()
lastSarSiggBarNum = LastValue(ValueWhen(sarsigs, bi));
_TRACE("Last Bar Num for sarsigs: " + lastSarSiggBarNum);
PlotText(StrFormat("%1.0f", lastSarSiggBarNum), lastSarSiggBarNum, sar1[lastSarSiggBarNum], colorWhite, colorRed);
currentlySelectedBarNum = SelectedValue(bi);
_TRACE("Currently selected BarNum " + currentlySelectedBarNum);
// plot the current bar text at the close price level
PlotText(StrFormat("%1.0f", currentlySelectedBarNum), currentlySelectedBarNum, C[currentlySelectedBarNum], colorBlack, colorAqua, 10);
//Show bar index on selection

_SECTION_END();


问:
Visual Basic - "Object reference not set to an instance of an object."
I'm trying to copy the data from DataGridView1 to a table in Access called LogsProductStock and DataGridView1's source is from a query. I also have DataGridView2 to show if the program has copied the data to LogsProductStock.

This is what I have written so far:

```<code>        Dim currentdate = Date.Now
        Dim i As Integer

        Try
            If MsgBox("Are you sure you want to sync tables?", vbYesNo + vbQuestion) = vbYes Then
                For i = 0 To DataGridView1.RowCount - 1
                    conn.Open()
                    cmd = New OleDbCommand("Insert into LogsProductStock (Product_ID, Category_ID, ProductQty, ProductBought, StockInDateTime, DateUpdated)
                        Values (@Product_ID, @Category_ID, @ProductQty, @ProductBought, @StockInDateTime, @DateUpdated)", conn)

                    cmd.Parameters.AddWithValue("@Product_ID", DataGridView1.Rows(i).Cells(0).Value.ToString)
                    cmd.Parameters.AddWithValue("@Category_ID", DataGridView1.Rows(i).Cells(1).Value.ToString)
                    cmd.Parameters.AddWithValue("@ProductQty", Integer.Parse(DataGridView1.Rows(i).Cells(2).Value.ToString))
                    cmd.Parameters.AddWithValue("@ProductBought", Integer.Parse(DataGridView1.Rows(i).Cells(3).Value.ToString))
                    cmd.Parameters.AddWithValue("@StockInDateTime", Date.Parse(DataGridView1.Rows(i).Cells(4).Value.ToString))
                    cmd.Parameters.AddWithValue("@Product_ID", Date.Parse(currentdate))

                    cmd.ExecuteNonQuery()
                    conn.Close()
                    load_data()
                Next
            End If
        Catch ex As Exception
            conn.Close()
            MsgBox(ex.Message, vbCritical)
        End Try
</code>```

When I run it, DataGridView2 has indeed copied the data from DataGridView1 but there's an error showing that the "Object reference not set to an instance of an object" and it doesn't save to the database. Here is what the details say:

```<code>************** Exception Text **************
System.NullReferenceException: Object reference not set to an instance of an object.
   at WindowsApp1.Form1.Button1_Click(Object sender, EventArgs e) in C:\Users\ASUS\Desktop\WindowsApp1\Form1.vb:line 21
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

</code>```

For reference, line 21 is the line for the first parameter (@Product_ID). I tried removing it but it just goes down to the second parameter. I have rewritten it but I'm still not sure which part I did wrong. Thanks in advance!

Body:
I'm trying to copy the data from DataGridView1 to a table in Access called LogsProductStock and DataGridView1's source is from a query. I also have DataGridView2 to show if the program has copied the data to LogsProductStock.

This is what I have written so far:

        Dim currentdate = Date.Now
        Dim i As Integer

        Try
            If MsgBox("Are you sure you want to sync tables?", vbYesNo + vbQuestion) = vbYes Then
                For i = 0 To DataGridView1.RowCount - 1
                    conn.Open()
                    cmd = New OleDbCommand("Insert into LogsProductStock (Product_ID, Category_ID, ProductQty, ProductBought, StockInDateTime, DateUpdated)
                        Values (@Product_ID, @Category_ID, @ProductQty, @ProductBought, @StockInDateTime, @DateUpdated)", conn)

                    cmd.Parameters.AddWithValue("@Product_ID", DataGridView1.Rows(i).Cells(0).Value.ToString)
                    cmd.Parameters.AddWithValue("@Category_ID", DataGridView1.Rows(i).Cells(1).Value.ToString)
                    cmd.Parameters.AddWithValue("@ProductQty", Integer.Parse(DataGridView1.Rows(i).Cells(2).Value.ToString))
                    cmd.Parameters.AddWithValue("@ProductBought", Integer.Parse(DataGridView1.Rows(i).Cells(3).Value.ToString))
                    cmd.Parameters.AddWithValue("@StockInDateTime", Date.Parse(DataGridView1.Rows(i).Cells(4).Value.ToString))
                    cmd.Parameters.AddWithValue("@Product_ID", Date.Parse(currentdate))

                    cmd.ExecuteNonQuery()
                    conn.Close()
                    load_data()
                Next
            End If
        Catch ex As Exception
            conn.Close()
            MsgBox(ex.Message, vbCritical)
        End Try

When I run it, DataGridView2 has indeed copied the data from DataGridView1 but there's an error showing that the "Object reference not set to an instance of an object" and it doesn't save to the database. Here is what the details say:

************** Exception Text **************
System.NullReferenceException: Object reference not set to an instance of an object.
   at WindowsApp1.Form1.Button1_Click(Object sender, EventArgs e) in C:\Users\ASUS\Desktop\WindowsApp1\Form1.vb:line 21
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

For reference, line 21 is the line for the first parameter (@Product_ID). I tried removing it but it just goes down to the second parameter. I have rewritten it but I'm still not sure which part I did wrong. Thanks in advance!


问:
Why does function descriptor create new bound method each time
Could you explain why new bound method is created each time when trying to access same method of the same class instance?

class MyClass:
    def my_method(self):
        print(f"Called bounded to {self}")

m_unbound = MyClass.my_method
print(f"{type(m_unbound)} {hash(m_unbound)}")  # <class 'function'> 8783579798336
m_unbound(None)

mc = MyClass()
m1 = mc.my_method
print(f"{type(m1)} {hash(m1)}")  # <class 'method'> 122173
m1()

m2 = mc.my_method  # THOUGHT IT WOULD BE THE SAME OBJECT AS m1
print(f"{type(m2)} {hash(m2)}")  # <class 'method'> 122173
m2()

print(m1 == m2)  # True
print(m1 is m2)  # False, why is so?
print(id(m1) == id(m2))  # False, equivalent of the above
```
<p>I do not understand why new bound method object is created each time if underlying instance still stays the same (as well as target function)</p>
<pre class="lang-py prettyprint-override"><code>print(m1.__self__ is m2.__self__)  # True, bound instance is the same
print(m1.__func__ is m2.__func__)  # True, target function is the same
print(m2.__func__ is m_unbound)  # True
</code>```

Body:
Could you explain why new bound method is created each time when trying to access same method of the same class instance?

class MyClass:
    def my_method(self):
        print(f"Called bounded to {self}")

m_unbound = MyClass.my_method
print(f"{type(m_unbound)} {hash(m_unbound)}")  # <class 'function'> 8783579798336
m_unbound(None)

mc = MyClass()
m1 = mc.my_method
print(f"{type(m1)} {hash(m1)}")  # <class 'method'> 122173
m1()

m2 = mc.my_method  # THOUGHT IT WOULD BE THE SAME OBJECT AS m1
print(f"{type(m2)} {hash(m2)}")  # <class 'method'> 122173
m2()

print(m1 == m2)  # True
print(m1 is m2)  # False, why is so?
print(id(m1) == id(m2))  # False, equivalent of the above

I do not understand why new bound method object is created each time if underlying instance still stays the same (as well as target function)

print(m1.__self__ is m2.__self__)  # True, bound instance is the same
print(m1.__func__ is m2.__func__)  # True, target function is the same
print(m2.__func__ is m_unbound)  # True


问:
Modal does not show bootstrap
When I try to open my modal with :

```<code>$('#btnLargeModal').on('click', function () {
            $('.bigModal').appendTo('body').modal('show')
        })
</code>```

It works fine. However when I add the code below, my modal does not show up

```<code>$('#btnLargeModal').on('click', function () {
            var dataTablegridDossiers = $('#gridDossiers').bootstrapTable('getData')
            $.each(dataTablegridDossiers, function (i, rowData) {
                if (rowData.select_dossier === true) {
                    $('#gridModalListeDossiers').bootstrapTable('check', i)
                }
                else {
                    $('#gridModalListeDossiers').bootstrapTable('uncheck', i)
                }
            })
          $('.bigModal').appendTo('body').modal('show')
        })
</code>```

Indication : My modal contains a table that has more than 1000 rows sometimes even more for example (picture below). In the other hand, the code above allows me to check inputs that are checked in another table, it works when I have 13 rows displayed in my modal table but when I have more data like 1000, my modal does not show up  :

Is there any workaround to do in order to show Modal and conserve the code that allows me to check inputs?

Title: Modal does not show bootstrap

Body:
When I try to open my modal with :

$('#btnLargeModal').on('click', function () {
            $('.bigModal').appendTo('body').modal('show')
        })

It works fine. However when I add the code below, my modal does not show up

$('#btnLargeModal').on('click', function () {
            var dataTablegridDossiers = $('#gridDossiers').bootstrapTable('getData')
            $.each(dataTablegridDossiers, function (i, rowData) {
                if (rowData.select_dossier === true) {
                    $('#gridModalListeDossiers').bootstrapTable('check', i)
                }
                else {
                    $('#gridModalListeDossiers').bootstrapTable('uncheck', i)
                }
            })
          $('.bigModal').appendTo('body').modal('show')
        })

Indication : My modal contains a table that has more than 1000 rows sometimes even more for example (picture below). In the other hand, the code above allows me to check inputs that are checked in another table, it works when I have 13 rows displayed in my modal table but when I have more data like 1000, my modal does not show up  :

Is there any workaround to do in order to show Modal and conserve the code that allows me to check inputs?


问:
How to resolve the error : No signature of method: build_3ov23u7xor54ble5ncs4vfgan.android() is applicable for argument
Hello everyone I'm asking for help here because after a week of searching and trying I still can't solve an error, preventing me from recompiling my flutter application into an android version.

Here are the facts: After installing the flutter_js package, impossible to launch the application on android the complete error is the following:
Build file 'D:\Nouveau dossier\projet\android\app\build.gradle' line: 28
A problem occurred evaluating project ':app'.

No signature of method: build_3ov23u7xor54ble5ncs4vfgan.android() is applicable for argument types: (build_3ov23u7xor54ble5ncs4vfgan$_run_closure2) values: [build_3ov23u7xor54ble5ncs4vfgan$_run_closure2@1d78c292]

This is my gradle configuration : -

I tried to solve it by reading all the similar posts on this and other forums but no result.
Thank you so much for your help!
Simeon


问:
React: Error-Message does not show up, while others do?
I have this simple Login-Form, in which I want to display an Error-Message, which contains Login tries (3 tries possible). Somehow, my one errormessage (loginTries) is not being displayed. Why?
My form is running the method handleSubmitAndStartTimer() when I submit it. You can find more comments and details below:</p>
```<code>export const Login = () => {
  const [errorMessages, setErrorMessages] = useState({});
  const [loginFailCounter, setLoginFailCounter] = useState(2);
  const [firstTimeSubmitted, setFirstTimeSubmitted] = useState(false);

  const mockUserData = [
    {
      username: "user1",
      password: "pass1",
      istGesperrt: false,
    },
  ];

  const handleSubmitAndStartTimer = (event) => {
    setFirstTimeSubmitted(true);

    event.preventDefault();

    var { benutzername, passwort } = document.forms[0];

    const userData = mockUserDaten.find(
      (user) => user.username === benutzername.value
    );

    // Compare user info
    if (userData) {
      if (!userData.istGesperrt) {
        if (userData.password !== passwort.value) {
          setLoginFailCounter(loginFailCounter - 1);
          // THIS DOESNT WORK!
          setErrorMessages({ name: "loginTries", message: errors.loginTries, });

          // ALL THESE ERROR MESSAGES WORK!
          // Invalid password
          setErrorMessages({ name: "passwort", message: errors.passwort });
        } else {
          // Username not found
          setErrorMessages({
            name: "benutzername",
            message: errors.benutzername,
          });
        }
      } else {
        setErrorMessages({
          name: "userGesperrt",
          message: errors.userGesperrt,
        });
      }
    }
  };

  // This method is called to display to correct message
  const renderErrorMessage = (name) =>
    name === errorMessages.name && (
      <div className="error">{errorMessages.message}</div>
    );

  const errors = {
    benutzername: "invalid username",
    passwort: "invalid password",
    loginTries: loginFailCounter + " Tries possible!",
    userGesperrt: "",
  };

  const renderForm = (
    <div className="form">
      <form onSubmit={handleSubmitAndStartTimer}>
        <div className="input-container">
          <label for="benutzername">Benutzername</label>
          <input type="text" id="benutzername" name="benutzername" required />
          {renderErrorMessage("benutzername")}
        </div>
        <div className="input-container">
          <label for="passwort">Passwort</label>
          <input type="passwort" id="passwort" name="passwort" required />
          {renderErrorMessage("passwort")}
        </div>
        <div className="button-container">
          <input type="submit" value="Log in" />
        </div>
        {renderErrorMessage("userGesperrt")}
        // THIS MESSAGE ISNT BEING SHOWN!
        {renderErrorMessage("loginTries")}
      </form>
    </div>
  );

  return (
    <div className="app">
      <div className="login-form">
        <div className="title">Sign In</div>
        {isSubmitted ? <div>User is successfully logged in</div> : renderForm}
      </div>
    </div>
  );
};

export default Login;
</code>```

Body:
I have this simple Login-Form, in which I want to display an Error-Message, which contains Login tries (3 tries possible). Somehow, my one errormessage (loginTries) is not being displayed. Why?
My form is running the method handleSubmitAndStartTimer() when I submit it. You can find more comments and details below:

export const Login = () => {
  const [errorMessages, setErrorMessages] = useState({});
  const [loginFailCounter, setLoginFailCounter] = useState(2);
  const [firstTimeSubmitted, setFirstTimeSubmitted] = useState(false);

  const mockUserData = [
    {
      username: "user1",
      password: "pass1",
      istGesperrt: false,
    },
  ];

  const handleSubmitAndStartTimer = (event) => {
    setFirstTimeSubmitted(true);

    event.preventDefault();

    var { benutzername, passwort } = document.forms[0];

    const userData = mockUserDaten.find(
      (user) => user.username === benutzername.value
    );

    // Compare user info
    if (userData) {
      if (!userData.istGesperrt) {
        if (userData.password !== passwort.value) {
          setLoginFailCounter(loginFailCounter - 1);
          // THIS DOESNT WORK!
          setErrorMessages({ name: "loginTries", message: errors.loginTries, });

          // ALL THESE ERROR MESSAGES WORK!
          // Invalid password
          setErrorMessages({ name: "passwort", message: errors.passwort });
        } else {
          // Username not found
          setErrorMessages({
            name: "benutzername",
            message: errors.benutzername,
          });
        }
      } else {
        setErrorMessages({
          name: "userGesperrt",
          message: errors.userGesperrt,
        });
      }
    }
  };

  // This method is called to display to correct message
  const renderErrorMessage = (name) =>
    name === errorMessages.name && (

{errorMessages.message}

    );

  const errors = {
    benutzername: "invalid username",
    passwort: "invalid password",
    loginTries: loginFailCounter + " Tries possible!",
    userGesperrt: "",
  };

  const renderForm = (

      <form onSubmit={handleSubmitAndStartTimer}>

          Benutzername
          <input type="text" id="benutzername" name="benutzername" required />
          {renderErrorMessage("benutzername")}

          Passwort
          <input type="passwort" id="passwort" name="passwort" required />
          {renderErrorMessage("passwort")}

          <input type="submit" value="Log in" />

        {renderErrorMessage("userGesperrt")}
        // THIS MESSAGE ISNT BEING SHOWN!
        {renderErrorMessage("loginTries")}
      </form>

  );

  return (

Sign In

        {isSubmitted ?
User is successfully logged in
 : renderForm}

  );
};

export default Login;


问:
Happened when i was updating all the packages of a 3 years old project(React-native). Help would be appreciated

ERROR  Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 10): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter,
GlobalPerformanceLogger, JSDevSupportModule, HMRClient.

A frequent cause of the error is that the application entry
file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes

This is my package.json

```<code>{
  "name": "Deepak",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "^1.17.11",
    "@react-native-community/netinfo": "^9.3.7",
    "@react-navigation/bottom-tabs": "^6.5.2",
    "@react-navigation/native": "^6.1.1",
    "@react-navigation/native-stack": "^6.9.7",
    "@react-navigation/stack": "^6.3.10",
    "moment": "^2.29.4",
    "react": "18.1.0",
    "react-native": "^0.70.6",
    "react-native-confirmation-code-input": "^1.0.4",
    "react-native-easy-toast": "^2.3.0",
    "react-native-flip-toggle-button": "^1.0.9",
    "react-native-image-placeholder": "^1.0.14",
    "react-native-image-slider-show": "^1.0.3",
    "react-native-keyboard-aware-scroll-view": "^0.9.5",
    "react-native-keyboard-aware-scrollview": "^2.1.0",
    "react-native-linear-gradient": "^2.6.2",
    "react-native-modalbox": "^2.0.2",
    "react-native-page-control": "^1.1.2",
    "react-native-pull-to-refresh": "^2.1.3",
    "react-native-razorpay": "^2.3.0",
    "react-native-responsive-screen": "^1.4.2",
    "react-native-safe-area-context": "^4.4.1",
    "react-native-screens": "^3.18.2",
    "react-native-search-filter": "^0.1.5",
    "react-native-simple-toast": "^2.0.0",
    "react-native-slideshow": "^1.0.1",
    "react-native-swipe-gestures": "^1.0.5",
    "react-native-webview": "^11.26.0",
    "react-redux": "^8.0.5",
    "redux": "^4.2.0",
    "redux-thunk": "^2.4.2"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.32.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "0.72.3",
    "react-test-renderer": "18.1.0"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

I commented most of the deprecated packages, don't want to change the node modules like

```<code>import Carousel, { Pagination } from 'react-native-snap-carousel';
import CheckBox from 'react-native-check-box'
</code>```

Body:
ERROR  Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 10): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter,
GlobalPerformanceLogger, JSDevSupportModule, HMRClient.

A frequent cause of the error is that the application entry
file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes

This is my package.json

{
  "name": "Deepak",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "^1.17.11",
    "@react-native-community/netinfo": "^9.3.7",
    "@react-navigation/bottom-tabs": "^6.5.2",
    "@react-navigation/native": "^6.1.1",
    "@react-navigation/native-stack": "^6.9.7",
    "@react-navigation/stack": "^6.3.10",
    "moment": "^2.29.4",
    "react": "18.1.0",
    "react-native": "^0.70.6",
    "react-native-confirmation-code-input": "^1.0.4",
    "react-native-easy-toast": "^2.3.0",
    "react-native-flip-toggle-button": "^1.0.9",
    "react-native-image-placeholder": "^1.0.14",
    "react-native-image-slider-show": "^1.0.3",
    "react-native-keyboard-aware-scroll-view": "^0.9.5",
    "react-native-keyboard-aware-scrollview": "^2.1.0",
    "react-native-linear-gradient": "^2.6.2",
    "react-native-modalbox": "^2.0.2",
    "react-native-page-control": "^1.1.2",
    "react-native-pull-to-refresh": "^2.1.3",
    "react-native-razorpay": "^2.3.0",
    "react-native-responsive-screen": "^1.4.2",
    "react-native-safe-area-context": "^4.4.1",
    "react-native-screens": "^3.18.2",
    "react-native-search-filter": "^0.1.5",
    "react-native-simple-toast": "^2.0.0",
    "react-native-slideshow": "^1.0.1",
    "react-native-swipe-gestures": "^1.0.5",
    "react-native-webview": "^11.26.0",
    "react-redux": "^8.0.5",
    "redux": "^4.2.0",
    "redux-thunk": "^2.4.2"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.32.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "0.72.3",
    "react-test-renderer": "18.1.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

I commented most of the deprecated packages, don't want to change the node modules like

import Carousel, { Pagination } from 'react-native-snap-carousel';
import CheckBox from 'react-native-check-box'


问:
Android - Suspend Kotlin Function Called From Java Never Executed
I am trying to use the accept answer here. Call Kotlin suspend function in Java class , innerReadStepsByTimeRange this one is never called but debug was able to stop at the readStepsByTimeRange.

My Kotlin class (the one that is called from java)

```<code>class StepReaderUtils {

companion object {
    @OptIn(DelicateCoroutinesApi::class)
    fun readStepsByTimeRange(
        healthConnectClient: HealthConnectClient,
        startTime: Instant,
        endTime: Instant
    ) : CompletableFuture<Long> = GlobalScope.future {
        innerReadStepsByTimeRange(healthConnectClient, startTime, endTime)
    }

    private suspend fun innerReadStepsByTimeRange (
        healthConnectClient: HealthConnectClient,
        startTime: Instant,
        endTime: Instant
    ) : Long {
        var totalStepsCount = 0L
        val response =
            healthConnectClient.readRecords(
                ReadRecordsRequest(
                    StepsRecord::class,
                    timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
                )
            )
        for (stepRecord in response.records) {
            totalStepsCount += stepRecord.count;
        }
        return totalStepsCount
    }
}

}
</code>```

My java caller method

```<code>CompletableFuture<Long> totalStepsCountCF = StepReaderUtils.Companion.readStepsByTimeRange(
            healthConnectClient, startDate, endDate);
    return totalStepsCountCF.get();
</code>```

My Gradle module build

```<code>implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.8.0'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0'
    implementation "androidx.health.connect:connect-client:1.0.0-alpha08"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.6.4"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4"
</code>```

What am i doing wrong?

Body:
I am trying to use the accept answer here. Call Kotlin suspend function in Java class , innerReadStepsByTimeRange this one is never called but debug was able to stop at the readStepsByTimeRange.

My Kotlin class (the one that is called from java)

class StepReaderUtils {

companion object {
    @OptIn(DelicateCoroutinesApi::class)
    fun readStepsByTimeRange(
        healthConnectClient: HealthConnectClient,
        startTime: Instant,
        endTime: Instant
    ) : CompletableFuture<Long> = GlobalScope.future {
        innerReadStepsByTimeRange(healthConnectClient, startTime, endTime)
    }

    private suspend fun innerReadStepsByTimeRange (
        healthConnectClient: HealthConnectClient,
        startTime: Instant,
        endTime: Instant
    ) : Long {
        var totalStepsCount = 0L
        val response =
            healthConnectClient.readRecords(
                ReadRecordsRequest(
                    StepsRecord::class,
                    timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
                )
            )
        for (stepRecord in response.records) {
            totalStepsCount += stepRecord.count;
        }
        return totalStepsCount
    }
}

}

My java caller method

CompletableFuture<Long> totalStepsCountCF = StepReaderUtils.Companion.readStepsByTimeRange(
            healthConnectClient, startDate, endDate);
    return totalStepsCountCF.get();

My Gradle module build

implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.8.0'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0'
    implementation "androidx.health.connect:connect-client:1.0.0-alpha08"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.6.4"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4"

What am i doing wrong?


问:
Execute a third application in DOS with Int 21h/4Bh using MASM
I do not understand, why the int21h/4Bh make this problems for MASM. I found a ASM code for FASM that seems to work. But with MASM it won't. The problem seems that in FASM INC files are in the standard embedded. I would like a  simple and compact code for MASM.

My Goal:
exec2 STARTAPP.COM/EXE Parameter1 Parameter2 ....

The START.COM/EXE start with:
STARTAPP Parameter1 Parameter2 ...

Working asm code in FASM:

```<code>org     100h

; first, we need to free the conventional memory we don't use,
; so there will be some memory available for the program we want
; to run, if we used MZ format of executable, the directive
; "heap 0" would be enough for this purpose, in case of .com
; program we have to free that memory manually be resizing the
; memory block starting at our PSP (es is already set to it)

        mov     ah,4Ah                  ; resize memory block
        mov     bx,10010h shr 4         ; only memory needed for .com
        int     21h

; now set up the pointer to command line in the parameters block

        mov     word [cmdline],_command
        mov     word [cmdline+2],ds

; we are ready to execute the program now

        mov     ax,4B00h                ; load and execute program
        mov     dx,_program             ; ASCIIZ path of program
        mov     bx,params               ; parameter block
        int     21h

        int     20h                     ; exit program

_program db 'c:\command.com',0
_command db 0                           ; length of command line
         db 13                          ; must end with CR character

params:
 environment dw 0       ; segment of environment, 0 means to use parent's one
 cmdline dd ?           ; pointer to command line
 default_fcb1 dd 0      ; pointers to file control blocks
 default_fcb2 dd 0      ```

```
<p>I would like to convert this code to MASM with this:</p>
```; Assembling: masm exec2.asm

code    segment
        assume cs:code,ds:code
        org   100h
start:

; first, we need to free the conventional memory we don't use,
; so there will be some memory available for the program we want
; to run, if we used MZ format of executable, the directive
; "heap 0" would be enough for this purpose, in case of .com
; program we have to free that memory manually be resizing the
; memory block starting at our PSP (es is already set to it)

        mov     ah,4Ah                  ; resize memory block
        mov     bx,10010h shr 4         ; **< asm(14): error A2084: constant value too large**
        int     21h

; now set up the pointer to command line in the parameters block

        mov     word [cmdline], offset command ; **< .asm(19): error A2009: syntax error in expression**
        mov     word [cmdline+2],ds ; **< .asm(20): error A2009: syntax error in expression**

; we are ready to execute the program now

        mov     ax,4B00h                ; load and execute program
        mov     dx, offset program             ; ASCIIZ path of program
        mov     bx,params               ; parameter block
        int     21h

        int     20h                     ; exit program

program db 'c:\command.com', 0
command db 0                           ; length of command line
         db 13                          ; must end with CR character

params:
 environment dw 0       ; segment of environment, 0 means to use parent's one
 cmdline dd ?           ; pointer to command line
 default_fcb1 dd 0      ; pointers to file control blocks
 default_fcb2 dd 0

code    ends
end  start

END
```

Body:
I do not understand, why the int21h/4Bh make this problems for MASM. I found a ASM code for FASM that seems to work. But with MASM it won't. The problem seems that in FASM INC files are in the standard embedded. I would like a  simple and compact code for MASM.

My Goal:
exec2 STARTAPP.COM/EXE Parameter1 Parameter2 ....

The START.COM/EXE start with:
STARTAPP Parameter1 Parameter2 ...

Working asm code in FASM:

org     100h

; first, we need to free the conventional memory we don't use,
; so there will be some memory available for the program we want
; to run, if we used MZ format of executable, the directive
; "heap 0" would be enough for this purpose, in case of .com
; program we have to free that memory manually be resizing the
; memory block starting at our PSP (es is already set to it)

        mov     ah,4Ah                  ; resize memory block
        mov     bx,10010h shr 4         ; only memory needed for .com
        int     21h

; now set up the pointer to command line in the parameters block

        mov     word [cmdline],_command
        mov     word [cmdline+2],ds

; we are ready to execute the program now

        mov     ax,4B00h                ; load and execute program
        mov     dx,_program             ; ASCIIZ path of program
        mov     bx,params               ; parameter block
        int     21h

        int     20h                     ; exit program

_program db 'c:\command.com',0
_command db 0                           ; length of command line
         db 13                          ; must end with CR character

params:
 environment dw 0       ; segment of environment, 0 means to use parent's one
 cmdline dd ?           ; pointer to command line
 default_fcb1 dd 0      ; pointers to file control blocks
 default_fcb2 dd 0      ```

I would like to convert this code to MASM with this:

; Assembling: masm exec2.asm

code    segment
        assume cs:code,ds:code
        org   100h
start:

; first, we need to free the conventional memory we don't use,
; so there will be some memory available for the program we want
; to run, if we used MZ format of executable, the directive
; "heap 0" would be enough for this purpose, in case of .com
; program we have to free that memory manually be resizing the
; memory block starting at our PSP (es is already set to it)

        mov     ah,4Ah                  ; resize memory block
        mov     bx,10010h shr 4         ; **< asm(14): error A2084: constant value too large**
        int     21h

; now set up the pointer to command line in the parameters block

        mov     word [cmdline], offset command ; **< .asm(19): error A2009: syntax error in expression**
        mov     word [cmdline+2],ds ; **< .asm(20): error A2009: syntax error in expression**

; we are ready to execute the program now

        mov     ax,4B00h                ; load and execute program
        mov     dx, offset program             ; ASCIIZ path of program
        mov     bx,params               ; parameter block
        int     21h

        int     20h                     ; exit program

program db 'c:\command.com', 0
command db 0                           ; length of command line
         db 13                          ; must end with CR character

params:
 environment dw 0       ; segment of environment, 0 means to use parent's one
 cmdline dd ?           ; pointer to command line
 default_fcb1 dd 0      ; pointers to file control blocks
 default_fcb2 dd 0

code    ends
end  start

END


问:
RUN puppeteer in a Node Dockerfile
I have a Node JS Backend, which should use puppeteer for screenshoting my pdfs.
On my local System (MAC OS) everything works fine.
Now I want to publish this as a docker container in an Azure App Service.
The app starts well, but when I trigger puppeteer, the following error occurs:

Error: Could not find Chromium (rev. 1069273). This can occur if
either

you did not perform an
installation before running the script (e.g. npm install) or

your cache path is incorrectly
configured (which is: /root/.cache/puppeteer).
For (2), check out our guide on
configuring puppeteer at https://pptr.dev/guides/configuration.

Dockerfile:

```<code>FROM node:slim

ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true

# INSTALL PUPPETEER DEPENDENCIES
RUN apt-get update && apt-get install gnupg wget chromium -y && \
  wget --quiet --output-document=- https://dl-ssl.google.com/linux/linux_signing_key.pub | gpg --dearmor > /etc/apt/trusted.gpg.d/google-archive.gpg && \
  sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' && \
  apt-get update && \
  apt-get install google-chrome-stable -y --no-install-recommends && \
  rm -rf /var/lib/apt/lists/*

COPY ./backend/ .

RUN npm install

CMD ["npm", "start"]
</code>```

The code of the route:

```<code>import puppeteer from 'puppeteer';
...
const browser = await puppeteer.launch({
    headless: true,
    ignoreHTTPSErrors: true,
    executablePath: '/usr/bin/google-chrome'
})
</code>```

package.json:

```<code>"dependencies": {
    ...
    "puppeteer": "^19.4.1",
}
</code>```

I followed this guide for my code: https://dev.to/cloudx/how-to-use-puppeteer-inside-a-docker-container-568c

What I'm doing wrong?

Title: RUN puppeteer in a Node Dockerfile

Body:
I have a Node JS Backend, which should use puppeteer for screenshoting my pdfs.
On my local System (MAC OS) everything works fine.
Now I want to publish this as a docker container in an Azure App Service.
The app starts well, but when I trigger puppeteer, the following error occurs:

Error: Could not find Chromium (rev. 1069273). This can occur if
either

you did not perform an
installation before running the script (e.g. npm install) or

your cache path is incorrectly
configured (which is: /root/.cache/puppeteer).
For (2), check out our guide on
configuring puppeteer at https://pptr.dev/guides/configuration.

Dockerfile:

FROM node:slim

ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true

# INSTALL PUPPETEER DEPENDENCIES
RUN apt-get update && apt-get install gnupg wget chromium -y && \
  wget --quiet --output-document=- https://dl-ssl.google.com/linux/linux_signing_key.pub | gpg --dearmor > /etc/apt/trusted.gpg.d/google-archive.gpg && \
  sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' && \
  apt-get update && \
  apt-get install google-chrome-stable -y --no-install-recommends && \
  rm -rf /var/lib/apt/lists/*

COPY ./backend/ .

RUN npm install

CMD ["npm", "start"]

The code of the route:

import puppeteer from 'puppeteer';
...
const browser = await puppeteer.launch({
    headless: true,
    ignoreHTTPSErrors: true,
    executablePath: '/usr/bin/google-chrome'
})

package.json:

"dependencies": {
    ...
    "puppeteer": "^19.4.1",
}

I followed this guide for my code: https://dev.to/cloudx/how-to-use-puppeteer-inside-a-docker-container-568c

What I'm doing wrong?


问:
Konva mousedown triggers dragging but mouseup doesn't stop it
Firstly, I'm very grateful for this excellent library.

I will do my best to explain this but I think the demo will explain it best.

I have a class that extends konva group because it needs other properties. One of those other properties can be called accessories, which is another konva group. (I don't want accessories to simply be a 'child' of the main group as I need to perform other operations on that array).

When I click the main groups children, I want it to drag the accessories, however, it also drags the accessories when I just click the main group.

I can't bind the startDrag() to the "dragstart" event because that only fires when the mouse is down AND the mouse moves, meaning there's an x,y offset to the accessories after they have moved.

```<code>constructor() {

  super({
    x: 0,
    y: 0,
    draggable: true,
  });

  this.accessories = new Konva.Group({
    x : this.attrs.x,
    y : this.attrs.y,
    draggable: true,
  });

  layer.add(this);
  layer.add(this.accessories);

  this.on("mousedown", () => {
    this.accessories.startDrag();
  });

  this.on("mouseup", () => {
    this.accessories.stopDrag();
  });

  this.on("click", () => {
    this.accessories.stopDrag();
  })

  }

}

let newgroup = new supergroup();
newgroup.add(new Konva.Rect({
    x: 0,
  y: 0,
  width: 50,
  height: 50,
  fill: "black",
}));

newgroup.children[0].on("click", () => {
    console.log("Rect Clicked");
});

newgroup.children[0].on("dragstart", () => {
    console.log("Group Drag Started");
  this.accessories.startDrag();
})

newgroup.accessories.add(new Konva.Rect({
    x: 55,
  y: 55,
  width: 50,
  height: 50,
  fill: "red",
}));

stage.add(layer);
layer.draw();
</code>```

I have made a simple demo here:

https://jsfiddle.net/9ajvwn8h/17/

If you click the grey background, it shifts the screen as intended. If you drag the black square, it drags the red one with it as expected. If you drag the red square, it only drags the red square as expected.

However, if you just click the black square, it begins dragging the red square, this is not what I want. It seems like the mouseup event doesn't fire.

I need the red square drag to NOT be initiated when I click the black square.

Any advice would be greatly appreciated.

Thank you

Body:
Firstly, I'm very grateful for this excellent library.

I will do my best to explain this but I think the demo will explain it best.

I have a class that extends konva group because it needs other properties. One of those other properties can be called accessories, which is another konva group. (I don't want accessories to simply be a 'child' of the main group as I need to perform other operations on that array).

When I click the main groups children, I want it to drag the accessories, however, it also drags the accessories when I just click the main group.

I can't bind the startDrag() to the "dragstart" event because that only fires when the mouse is down AND the mouse moves, meaning there's an x,y offset to the accessories after they have moved.

constructor() {

  super({
    x: 0,
    y: 0,
    draggable: true,
  });

  this.accessories = new Konva.Group({
    x : this.attrs.x,
    y : this.attrs.y,
    draggable: true,
  });

  layer.add(this);
  layer.add(this.accessories);

  this.on("mousedown", () => {
    this.accessories.startDrag();
  });

  this.on("mouseup", () => {
    this.accessories.stopDrag();
  });

  this.on("click", () => {
    this.accessories.stopDrag();
  })

  }

}

let newgroup = new supergroup();
newgroup.add(new Konva.Rect({
    x: 0,
  y: 0,
  width: 50,
  height: 50,
  fill: "black",
}));

newgroup.children[0].on("click", () => {
    console.log("Rect Clicked");
});

newgroup.children[0].on("dragstart", () => {
    console.log("Group Drag Started");
  this.accessories.startDrag();
})

newgroup.accessories.add(new Konva.Rect({
    x: 55,
  y: 55,
  width: 50,
  height: 50,
  fill: "red",
}));

stage.add(layer);
layer.draw();

I have made a simple demo here:

https://jsfiddle.net/9ajvwn8h/17/

If you click the grey background, it shifts the screen as intended. If you drag the black square, it drags the red one with it as expected. If you drag the red square, it only drags the red square as expected.

However, if you just click the black square, it begins dragging the red square, this is not what I want. It seems like the mouseup event doesn't fire.

I need the red square drag to NOT be initiated when I click the black square.

Any advice would be greatly appreciated.

Thank you


问:
Why is Tone.Sequence not working in this script?
Im trying recreate this code (https://editor.p5js.org/mbardin/sketches/Y5N7YGWo6) to trigger a sequence of notes in tone.js but for some reason my code does not work..

this is my js:

```<code>    let sequence, synth;
    let melody = ["C3", ["E3", "G3", "D3", "C3"], "A3", "B2", "C2", "E3",
    ["A2", "G2"], "C4"];

    function setup() {

    sequence = new Tone.Sequence(function (time, note) {
        synth.triggerAttackRelease('note', '8n');
        console.log(note);
    }, melody, '4n');

    synth = new Tone.Synth();
    synth.toDestination();

    Tone.Transport.bpm.value = 90;
    Tone.Transport.loop = true;
    Tone.Transport.loopStart = 0;
    Tone.Transport.loopEnd = '2:0:0';
    Tone.Transport.start();

    playSynth();

    }

    function playSynth() {
    sequence.start();
    }

</code>```

and my html:

```<code>    <!DOCTYPE html>

    <html>

   <head>
    <script src="https://tonejs.github.io/build/Tone.js"></script>
   </head>

    <body onload="setup()">
    <h1>Hello World Yo'</h1>
    <button onclick="playSynth()">C2 tone.Synth</button>

    <script src="osc.js"></script>

    </body>

    </html>
</code>```

Ive added the sequence, transport data etc. and at first I was getting the error that sequence wasnt defined - im guessing because its nested in setup function, so I added body onload="setup()" into the html, not sure if this is good practice?

The reason I havent just copied this guys code is I want to learn how it works and recreate it for myself on my own site, triggered by a button specifically.

Thanks!

Body:
Im trying recreate this code (https://editor.p5js.org/mbardin/sketches/Y5N7YGWo6) to trigger a sequence of notes in tone.js but for some reason my code does not work..

this is my js:

    let sequence, synth;
    let melody = ["C3", ["E3", "G3", "D3", "C3"], "A3", "B2", "C2", "E3",
    ["A2", "G2"], "C4"];

    function setup() {

    sequence = new Tone.Sequence(function (time, note) {
        synth.triggerAttackRelease('note', '8n');
        console.log(note);
    }, melody, '4n');

    synth = new Tone.Synth();
    synth.toDestination();

    Tone.Transport.bpm.value = 90;
    Tone.Transport.loop = true;
    Tone.Transport.loopStart = 0;
    Tone.Transport.loopEnd = '2:0:0';
    Tone.Transport.start();

    playSynth();

    }

    function playSynth() {
    sequence.start();
    }

and my html:

    <!DOCTYPE html>

Hello World Yo'

    <button onclick="playSynth()">C2 tone.Synth</button>

Ive added the sequence, transport data etc. and at first I was getting the error that sequence wasnt defined - im guessing because its nested in setup function, so I added body onload="setup()" into the html, not sure if this is good practice?

The reason I havent just copied this guys code is I want to learn how it works and recreate it for myself on my own site, triggered by a button specifically.

Thanks!


问:
Convert a Number to EUR Currency React Js
I'm trying to convert a Number with follow function (from Woocommerce API) to EUR Currency React Js.</p>
```<code>const numberFormat = (value) =>
  new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',

}).format(value);

woocommerce api price = 1590
result = 1.590,00 €
expected = 159,00 €

woocommerce api price = 25999
result = 25.999,00 €
expected = 259,00 €

woocommerce api price = 149999
result = 149.999,00 €
expected = 1.499,99 €
</code>```

Body:
I'm trying to convert a Number with follow function (from Woocommerce API) to EUR Currency React Js.

const numberFormat = (value) =>
  new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',

}).format(value);

woocommerce api price = 1590
result = 1.590,00 €
expected = 159,00 €

woocommerce api price = 25999
result = 25.999,00 €
expected = 259,00 €

woocommerce api price = 149999
result = 149.999,00 €
expected = 1.499,99 €


问:
node_module gives require is not defined
i have a node module (vToaster) that i want to use to show error or succes notifications from my axios requests but now it randomly doesnt work anymore, and by work i mean i get this erorr and i have no idea what it could be

```<code>import Toaster from '@meforma/vue-toaster';
</code>```
```<code>RentApp.use(Toaster);
</code>```

This worked for like 3 weeks but now randomly i get an error:

```<code>    ReferenceError: require is not defined
        at Proxy.mounted (Toaster.vue:88:7)
        at callWithErrorHandling (runtime-core.esm-bundler.js:155:22)
        at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:164:21)
        at hook.__weh.hook.__weh (runtime-core.esm-bundler.js:2687:29)
        at flushPostFlushCbs (runtime-core.esm-bundler.js:358:32)
        at Object.render2 [as render] (runtime-core.esm-bundler.js:6206:9)
        at render (runtime-dom.esm-bundler.js:1579:22)
        at mount (mount-component.js:14:3)
        at Object.show (api.js:9:17)
        at Object.success (api.js:19:19)
</code>```

I have no idea how to fix this

I am using Laravel 9 with Vite, TailwindCss and Vue

Any help is welcome!

Body:
i have a node module (vToaster) that i want to use to show error or succes notifications from my axios requests but now it randomly doesnt work anymore, and by work i mean i get this erorr and i have no idea what it could be

import Toaster from '@meforma/vue-toaster';

RentApp.use(Toaster);

This worked for like 3 weeks but now randomly i get an error:

    ReferenceError: require is not defined
        at Proxy.mounted (Toaster.vue:88:7)
        at callWithErrorHandling (runtime-core.esm-bundler.js:155:22)
        at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:164:21)
        at hook.__weh.hook.__weh (runtime-core.esm-bundler.js:2687:29)
        at flushPostFlushCbs (runtime-core.esm-bundler.js:358:32)
        at Object.render2 [as render] (runtime-core.esm-bundler.js:6206:9)
        at render (runtime-dom.esm-bundler.js:1579:22)
        at mount (mount-component.js:14:3)
        at Object.show (api.js:9:17)
        at Object.success (api.js:19:19)

I have no idea how to fix this

I am using Laravel 9 with Vite, TailwindCss and Vue

Any help is welcome!