问:
Jython install pygame and use it with java in order to connect my controller
I'm working on a java project and I need it to be able to handle the DualShock 4 controller. I saw that with Pygame  and a basic script I can use my controller (all the code is a the end). I can even use my Dualsense controller (PS5 controller) just with this code.

Therefore I wanted to use this very script in my java project using Jython. The issue is that I can't pip install pygame. I have the error

Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output

And I don't know how to handle it.

Furthermore, on this website : https://gatc.ca/2012/02/08/applet-deployment-using-pyj2d/ he create an applet of pygame but I really didn't understand how he managed to do that.

I haven't found a better way to use my controller with java.

here's the python code :

import pygame

from pygame.locals import *
pygame.init()
pygame.display.set_caption('game base')
screen = pygame.display.set_mode((500, 500), 0, 32)
clock = pygame.time.Clock()

pygame.joystick.init()
joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
for joystick in joysticks:
    print(joystick.get_name())

my_square = pygame.Rect(50, 50, 50, 50)
my_square_color = 0
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
motion = [0, 0]

while True:

    screen.fill((0, 0, 0))

    pygame.draw.rect(screen, colors[my_square_color], my_square)
    if abs(motion[0]) < 0.1:
        motion[0] = 0
    if abs(motion[1]) < 0.1:
        motion[1] = 0
    my_square.x += motion[0] * 10
    my_square.y += motion[1] * 10

    for event in pygame.event.get():
        if event.type == JOYBUTTONDOWN:
            print(event)
            if event.button == 0:
                my_square_color = (my_square_color + 1) % len(colors)
        if event.type == JOYBUTTONUP:
            print(event)
        if event.type == JOYAXISMOTION:
            print(event)
            if event.axis < 2:
                motion[event.axis] = event.value
        if event.type == JOYHATMOTION:
            print(event)
        if event.type == JOYDEVICEADDED:
            joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
            for joystick in joysticks:
                print(joystick.get_name())
        if event.type == JOYDEVICEREMOVED:
            joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

    pygame.display.update()
    clock.tick(60)
```
<p>and here's the Java code used to call this python script</p>
<pre class="lang-java prettyprint-override"><code>
import org.python.util.PythonInterpreter;

public class controller {

  public static void main(String[] args) {
        try {
        PythonInterpreter pyInterp = new PythonInterpreter() ;

        // importer le code python
        pyInterp.execfile("path2pythonScript/manette.py");

        pyInterp.close();
        } catch (Exception e) {
            e.printStackTrace();
      }
    }
}
</code>```

If anyone know whether how to install Pygame in my Jython standalone.jar or even a better way to connect my controller I'll take it.

edit : Here's the full output when I try to pip install

```<code>jython -m pip install pygame==1.9.6

DEPRECATION: pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.
WARNING: The directory '/Users/sami/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting pygame==1.9.6
  Downloading pygame-1.9.6.tar.gz (3.2 MB)
    ERROR: Command errored out with exit status 1:
     command: /Users/sami/jython2.7.3/bin/jython -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/tmp/pip-install-36qzq9/pygame/setup.py'"'"'; __file__='"'"'/private/tmp/pip-install-36qzq9/pygame/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/tmp/pip-pip-egg-info-q8Wv8X
         cwd: /private/tmp/pip-install-36qzq9/pygame/
    Complete output (20 lines):

    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using UNIX configuration...

    Hunting dependencies...
    /bin/sh: sdl-config: command not found
    /bin/sh: sdl-config: command not found
    /bin/sh: sdl-config: command not found
    WARNING: "sdl-config" failed!
    /bin/sh: pkg-config: command not found
    /bin/sh: pkg-config: command not found
    /bin/sh: pkg-config: command not found
    WARNING: "pkg-config freetype2" failed!
    /bin/sh: freetype-config: command not found
    /bin/sh: freetype-config: command not found
    /bin/sh: freetype-config: command not found
    WARNING: "freetype-config" failed!
    Unable to run "sdl-config". Please make sure a development version of SDL is installed.
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
</code>```

I use macOS Ventura
But I don't need to install it on my computer, I need to use it in the Jython package which is independent of the OS used I guess. I can use a Windows laptop If there is solution with it

Edit 2 : SDL is now installed but I still got this error message when I try to install pygame with the same command :

```<code>Collecting pygame
  Downloading pygame-2.0.3.tar.gz (5.8 MB)
    ERROR: Command errored out with exit status 1:
     command: /Users/sami/jython2.7.3/bin/jython -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/tmp/pip-install-3gu1yA/pygame/setup.py'"'"'; __file__='"'"'/private/tmp/pip-install-3gu1yA/pygame/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/tmp/pip-pip-egg-info-ntnoiG
         cwd: /private/tmp/pip-install-3gu1yA/pygame/
    Complete output (34 lines):

    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using UNIX configuration...

    Hunting dependencies...
    SDL     : found 2.26.1
    FONT    : not found
    ('FONT', 'SDL_ttf.h', 'libSDL2_ttf.so', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    IMAGE   : not found
    ('IMAGE', 'SDL_image.h', 'libSDL2_image.so', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    MIXER   : not found
    ('MIXER', 'SDL_mixer.h', 'libSDL2_mixer.so', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    PNG     : not found
    ('PNG', 'png.h', 'libpng', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    JPEG    : not found
    ('JPEG', 'jpeglib.h', 'libjpeg', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    SCRAP   : found
    PORTMIDI: not found
    ('PORTMIDI', 'portmidi.h', 'libportmidi.so', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    PORTTIME: not found
    ('PORTTIME', 'porttime.h', 'libporttime.so', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    FREETYPE: found 24.3.18
    WARNING:root:Some pygame dependencies were not found. Pygame can still compile and install, but games that depend on those missing dependencies will not run. Use -auto to continue building without all dependencies.

    ---
    For help with compilation see:
        https://www.pygame.org/wiki/Compilation
    To contribute to pygame development see:
        https://www.pygame.org/contribute.html
    ---

    Missing dependencies
    ----------------------------------------
</code>```

With the -auto flag I got this error :

```<code>/Users//jython2.7.3/bin/jython -m pip install pygame==1.9.6 -auto

Usage:
  /Users//jython2.7.3/bin/jython -m pip install [options] <requirement specifier> [package-index-options] ...
  /Users//jython2.7.3/bin/jython -m pip install [options] -r <requirements file> [package-index-options] ...
  /Users//jython2.7.3/bin/jython -m pip install [options] [-e] <vcs project url> ...
  /Users//jython2.7.3/bin/jython -m pip install [options] [-e] <local project path> ...
  /Users//jython2.7.3/bin/jython -m pip install [options] <archive url/path> ...

no such option: -a
</code>```

Body:
I'm working on a java project and I need it to be able to handle the DualShock 4 controller. I saw that with Pygame  and a basic script I can use my controller (all the code is a the end). I can even use my Dualsense controller (PS5 controller) just with this code.

Therefore I wanted to use this very script in my java project using Jython. The issue is that I can't pip install pygame. I have the error

Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output

And I don't know how to handle it.

Furthermore, on this website : https://gatc.ca/2012/02/08/applet-deployment-using-pyj2d/ he create an applet of pygame but I really didn't understand how he managed to do that.

I haven't found a better way to use my controller with java.

here's the python code :

import pygame

from pygame.locals import *
pygame.init()
pygame.display.set_caption('game base')
screen = pygame.display.set_mode((500, 500), 0, 32)
clock = pygame.time.Clock()

pygame.joystick.init()
joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
for joystick in joysticks:
    print(joystick.get_name())

my_square = pygame.Rect(50, 50, 50, 50)
my_square_color = 0
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
motion = [0, 0]

while True:

    screen.fill((0, 0, 0))

    pygame.draw.rect(screen, colors[my_square_color], my_square)
    if abs(motion[0]) < 0.1:
        motion[0] = 0
    if abs(motion[1]) < 0.1:
        motion[1] = 0
    my_square.x += motion[0] * 10
    my_square.y += motion[1] * 10

    for event in pygame.event.get():
        if event.type == JOYBUTTONDOWN:
            print(event)
            if event.button == 0:
                my_square_color = (my_square_color + 1) % len(colors)
        if event.type == JOYBUTTONUP:
            print(event)
        if event.type == JOYAXISMOTION:
            print(event)
            if event.axis < 2:
                motion[event.axis] = event.value
        if event.type == JOYHATMOTION:
            print(event)
        if event.type == JOYDEVICEADDED:
            joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
            for joystick in joysticks:
                print(joystick.get_name())
        if event.type == JOYDEVICEREMOVED:
            joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

    pygame.display.update()
    clock.tick(60)

and here's the Java code used to call this python script

import org.python.util.PythonInterpreter;

public class controller {

  public static void main(String[] args) {
        try {
        PythonInterpreter pyInterp = new PythonInterpreter() ;

        // importer le code python
        pyInterp.execfile("path2pythonScript/manette.py");

        pyInterp.close();
        } catch (Exception e) {
            e.printStackTrace();
      }
    }
}

If anyone know whether how to install Pygame in my Jython standalone.jar or even a better way to connect my controller I'll take it.

edit : Here's the full output when I try to pip install

jython -m pip install pygame==1.9.6

DEPRECATION: pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.
WARNING: The directory '/Users/sami/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting pygame==1.9.6
  Downloading pygame-1.9.6.tar.gz (3.2 MB)
    ERROR: Command errored out with exit status 1:
     command: /Users/sami/jython2.7.3/bin/jython -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/tmp/pip-install-36qzq9/pygame/setup.py'"'"'; __file__='"'"'/private/tmp/pip-install-36qzq9/pygame/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/tmp/pip-pip-egg-info-q8Wv8X
         cwd: /private/tmp/pip-install-36qzq9/pygame/
    Complete output (20 lines):

    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using UNIX configuration...

    Hunting dependencies...
    /bin/sh: sdl-config: command not found
    /bin/sh: sdl-config: command not found
    /bin/sh: sdl-config: command not found
    WARNING: "sdl-config" failed!
    /bin/sh: pkg-config: command not found
    /bin/sh: pkg-config: command not found
    /bin/sh: pkg-config: command not found
    WARNING: "pkg-config freetype2" failed!
    /bin/sh: freetype-config: command not found
    /bin/sh: freetype-config: command not found
    /bin/sh: freetype-config: command not found
    WARNING: "freetype-config" failed!
    Unable to run "sdl-config". Please make sure a development version of SDL is installed.
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

I use macOS Ventura
But I don't need to install it on my computer, I need to use it in the Jython package which is independent of the OS used I guess. I can use a Windows laptop If there is solution with it

Edit 2 : SDL is now installed but I still got this error message when I try to install pygame with the same command :

Collecting pygame
  Downloading pygame-2.0.3.tar.gz (5.8 MB)
    ERROR: Command errored out with exit status 1:
     command: /Users/sami/jython2.7.3/bin/jython -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/tmp/pip-install-3gu1yA/pygame/setup.py'"'"'; __file__='"'"'/private/tmp/pip-install-3gu1yA/pygame/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/tmp/pip-pip-egg-info-ntnoiG
         cwd: /private/tmp/pip-install-3gu1yA/pygame/
    Complete output (34 lines):

    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using UNIX configuration...

    Hunting dependencies...
    SDL     : found 2.26.1
    FONT    : not found
    ('FONT', 'SDL_ttf.h', 'libSDL2_ttf.so', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    IMAGE   : not found
    ('IMAGE', 'SDL_image.h', 'libSDL2_image.so', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    MIXER   : not found
    ('MIXER', 'SDL_mixer.h', 'libSDL2_mixer.so', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    PNG     : not found
    ('PNG', 'png.h', 'libpng', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    JPEG    : not found
    ('JPEG', 'jpeglib.h', 'libjpeg', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    SCRAP   : found
    PORTMIDI: not found
    ('PORTMIDI', 'portmidi.h', 'libportmidi.so', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    PORTTIME: not found
    ('PORTTIME', 'porttime.h', 'libporttime.so', ['/usr/include', '/usr/include/SDL2', '/usr/local/include', '/usr/local/include/SDL2', '/usr/X11R6/include', '/opt/homebrew/include/SDL2'], ['/usr/lib', '/usr/lib64', '/usr/X11R6/lib', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu', '/usr/lib/arm-linux-gnueabihf/', '/usr/lib/aarch64-linux-gnu/', '/usr/local/lib', '/usr/local/lib64', '/usr/local/X11R6/lib', '/usr/local/lib/i386-linux-gnu', '/usr/local/lib/x86_64-linux-gnu', '/usr/local/lib/arm-linux-gnueabihf/', '/usr/local/lib/aarch64-linux-gnu/', '/opt/homebrew/lib'])
    FREETYPE: found 24.3.18
    WARNING:root:Some pygame dependencies were not found. Pygame can still compile and install, but games that depend on those missing dependencies will not run. Use -auto to continue building without all dependencies.

    ---
    For help with compilation see:
        https://www.pygame.org/wiki/Compilation
    To contribute to pygame development see:
        https://www.pygame.org/contribute.html
    ---

    Missing dependencies
    ----------------------------------------

With the -auto flag I got this error :

/Users//jython2.7.3/bin/jython -m pip install pygame==1.9.6 -auto

Usage:
  /Users//jython2.7.3/bin/jython -m pip install [options] <requirement specifier> [package-index-options] ...
  /Users//jython2.7.3/bin/jython -m pip install [options] -r <requirements file> [package-index-options] ...
  /Users//jython2.7.3/bin/jython -m pip install [options] [-e] <vcs project url> ...
  /Users//jython2.7.3/bin/jython -m pip install [options] [-e] <local project path> ...
  /Users//jython2.7.3/bin/jython -m pip install [options] <archive url/path> ...

no such option: -a


来源: stackexchange

问:
Lambda function that poll events from SQS only the first day of the month
I need a lambda function that poll events from a fifo SQS queue only the first day of the month. Is it possible?

For example:

One lambda adds some events to a queue only the first day of the month.

Another lambda should process queue's messages in the same day.

Requirements

Each message must be processed by a dedicated lambda invocation

Lambda Function's Concurrency Limit is set to 1.

The polling from the queue should occurr only the first day of the month, since on other days the queue is empty.

I'm looking for a solution like the one suggested by AWS here. The only difference is that the polling should only take place on the first day of the month in order to save money.

ContentLicense: CC BY-SA 4.0


问:
On maya, Is there a way to edit the size of a multi attribute after creation?
I have this snippet:

```<code>maya.cmds.addAttr("null1",
                  longName="a",
                  attributeType="compound",
                  numberOfChildren=2,
                  multi=True)

maya.cmds.addAttr("null1",
                  longName="b",
                  attributeType="long",
                  parent="a")

maya.cmds.addAttr("null1",
                  longName="caaaa",
                  attributeType="message",
                  parent="a")

maya.cmds.setAttr("null1.a", size=3)

maya.cmds.addAttr("null1",
                  longName="caaaaasdg",
                  attributeType="message",
                  parent="a")
</code>```

According to the docs, there's a flag called size to edit the size of a multi array attribute but it says it's only a hint? Is there another way?
https://help.autodesk.com/cloudhelp/2022/ENU/Maya-Tech-Docs/CommandsPython/setAttr.html#flagsize

Body:
I have this snippet:

maya.cmds.addAttr("null1",
                  longName="a",
                  attributeType="compound",
                  numberOfChildren=2,
                  multi=True)

maya.cmds.addAttr("null1",
                  longName="b",
                  attributeType="long",
                  parent="a")

maya.cmds.addAttr("null1",
                  longName="caaaa",
                  attributeType="message",
                  parent="a")

maya.cmds.setAttr("null1.a", size=3)

maya.cmds.addAttr("null1",
                  longName="caaaaasdg",
                  attributeType="message",
                  parent="a")

According to the docs, there's a flag called size to edit the size of a multi array attribute but it says it's only a hint? Is there another way?
https://help.autodesk.com/cloudhelp/2022/ENU/Maya-Tech-Docs/CommandsPython/setAttr.html#flagsize


问:
PaddleOCR model not detecting angled text even though use_cls is true
I am running a pre-trained PaddleOCR model (detection + recognition + cls) in Sagemaker following this tutorial. The inference works and I am able to successfully read words from images and get their confidences and bounding boxes. I am creating my model like this:

```<code>ocr = PaddleOCR(det_model_dir='/opt/program/inference/en_PP-OCRv3_det_infer',
                rec_model_dir='/opt/program/inference/en_PP-OCRv3_rec_infer',
                cls_model_dir='/opt/program/inference/ch_ppocr_mobile_v2.0_cls_infer',
                lang='en',
                use_angle_cls=True,
                label_list=['0', '90', '180'],
                use_pdserving=False)
</code>```

and running inference like this:

```<code>result = ocr.ocr(imgpath)
</code>```

My result looks like this:

```<code>[
  [
    [
      [
        [137.0, 463.0],
        [252.0, 463.0],
        [252.0, 495.0],
        [137.0, 495.0]
      ], ('Hello', 0.9691440463066101)
    ],
    [
      [
        [162.0, 524.0],
        [234.0, 524.0],
        [234.0, 534.0],
        [162.0, 534.0]
      ], ('Text', 0.9424589276313782)
    ],
    [
      [
        [185.0, 537.0],
        [204.0, 537.0],
        [204.0, 545.0],
        [185.0, 545.0]
      ], ('World', 0.994895339012146)
    ]
  ]
]
</code>```

However, when I pass the same image to the OCR model that is rotated 90 degress the result is empty. This leads me to believe that the angle_cls detection is not working. I have tried explicitly specifying use_angle_cls=True, when I create the model AND doing so when I invoke the model via ocr.ocr(imgpath, use_angle_cls=True) however the result is still empty. Is there some additional param I should be specifing when I create or invoke the model in order to use CLS?

Here is some additional debug output from when I create the model:

```<code>Namespace(alpha=1.0, benchmark=False, beta=1.0, cls_batch_num=6, cls_image_shape='3, 48, 192', cls_model_dir='/opt/program/inference/ch_ppocr_mobile_v2.0_cls_infer', cls_thresh=0.9, cpu_threads=10, crop_res_save_dir='./output', det=True, det_algorithm='DB', det_box_type='quad', det_db_box_thresh=0.6, det_db_score_mode='fast', det_db_thresh=0.3, det_db_unclip_ratio=1.5, det_east_cover_thresh=0.1, det_east_nms_thresh=0.2, det_east_score_thresh=0.8, det_limit_side_len=960, det_limit_type='max', det_model_dir='/opt/program/inference/en_PP-OCRv3_det_infer', det_pse_box_thresh=0.85, det_pse_min_area=16, det_pse_scale=1, det_pse_thresh=0, det_sast_nms_thresh=0.2, det_sast_score_thresh=0.5, draw_img_save_dir='./inference_results', drop_score=0.5, e2e_algorithm='PGNet', e2e_char_dict_path='./ppocr/utils/ic15_dict.txt', e2e_limit_side_len=768, e2e_limit_type='max', e2e_model_dir=None, e2e_pgnet_mode='fast', e2e_pgnet_score_thresh=0.5, e2e_pgnet_valid_set='totaltext', enable_mkldnn=False, fourier_degree=5, gpu_mem=500, help='==SUPPRESS==', image_dir=None, image_orientation=False, ir_optim=True, kie_algorithm='LayoutXLM', label_list=['0', '90'], lang='en', layout=True, layout_dict_path=None, layout_model_dir=None, layout_nms_threshold=0.5, layout_score_threshold=0.5, max_batch_size=10, max_text_length=25, merge_no_span_structure=True, min_subgraph_size=15, mode='structure', ocr=True, ocr_order_method=None, ocr_version='PP-OCRv3', output='./output', page_num=0, precision='fp32', process_id=0, re_model_dir=None, rec=True, rec_algorithm='SVTR_LCNet', rec_batch_num=6, rec_char_dict_path='/opt/program/ppocr/utils/en_dict.txt', rec_image_inverse=True, rec_image_shape='3, 48, 320', rec_model_dir='/opt/program/inference/en_PP-OCRv3_rec_infer', recovery=False, save_crop_res=False, save_log_path='./log_output/', scales=[8, 16, 32], ser_dict_path='../train_data/XFUND/class_list_xfun.txt', ser_model_dir=None, show_log=True, sr_batch_num=1, sr_image_shape='3, 32, 128', sr_model_dir=None, structure_version='PP-StructureV2', table=True, table_algorithm='TableAttn', table_char_dict_path=None, table_max_len=488, table_model_dir=None, total_process_num=1, type='ocr', use_angle_cls=True, use_dilation=False, use_gpu=True, use_mp=False, use_npu=False, use_onnx=False, use_pdf2docx_api=False, use_pdserving=False, use_space_char=True, use_tensorrt=False, use_visual_backbone=True, use_xpu=False, vis_font_path='./doc/fonts/simfang.ttf', warmup=False)
</code>```

Body:
I am running a pre-trained PaddleOCR model (detection + recognition + cls) in Sagemaker following this tutorial. The inference works and I am able to successfully read words from images and get their confidences and bounding boxes. I am creating my model like this:

ocr = PaddleOCR(det_model_dir='/opt/program/inference/en_PP-OCRv3_det_infer',
                rec_model_dir='/opt/program/inference/en_PP-OCRv3_rec_infer',
                cls_model_dir='/opt/program/inference/ch_ppocr_mobile_v2.0_cls_infer',
                lang='en',
                use_angle_cls=True,
                label_list=['0', '90', '180'],
                use_pdserving=False)

and running inference like this:

result = ocr.ocr(imgpath)

My result looks like this:

[
  [
    [
      [
        [137.0, 463.0],
        [252.0, 463.0],
        [252.0, 495.0],
        [137.0, 495.0]
      ], ('Hello', 0.9691440463066101)
    ],
    [
      [
        [162.0, 524.0],
        [234.0, 524.0],
        [234.0, 534.0],
        [162.0, 534.0]
      ], ('Text', 0.9424589276313782)
    ],
    [
      [
        [185.0, 537.0],
        [204.0, 537.0],
        [204.0, 545.0],
        [185.0, 545.0]
      ], ('World', 0.994895339012146)
    ]
  ]
]

However, when I pass the same image to the OCR model that is rotated 90 degress the result is empty. This leads me to believe that the angle_cls detection is not working. I have tried explicitly specifying use_angle_cls=True, when I create the model AND doing so when I invoke the model via ocr.ocr(imgpath, use_angle_cls=True) however the result is still empty. Is there some additional param I should be specifing when I create or invoke the model in order to use CLS?

Here is some additional debug output from when I create the model:

Namespace(alpha=1.0, benchmark=False, beta=1.0, cls_batch_num=6, cls_image_shape='3, 48, 192', cls_model_dir='/opt/program/inference/ch_ppocr_mobile_v2.0_cls_infer', cls_thresh=0.9, cpu_threads=10, crop_res_save_dir='./output', det=True, det_algorithm='DB', det_box_type='quad', det_db_box_thresh=0.6, det_db_score_mode='fast', det_db_thresh=0.3, det_db_unclip_ratio=1.5, det_east_cover_thresh=0.1, det_east_nms_thresh=0.2, det_east_score_thresh=0.8, det_limit_side_len=960, det_limit_type='max', det_model_dir='/opt/program/inference/en_PP-OCRv3_det_infer', det_pse_box_thresh=0.85, det_pse_min_area=16, det_pse_scale=1, det_pse_thresh=0, det_sast_nms_thresh=0.2, det_sast_score_thresh=0.5, draw_img_save_dir='./inference_results', drop_score=0.5, e2e_algorithm='PGNet', e2e_char_dict_path='./ppocr/utils/ic15_dict.txt', e2e_limit_side_len=768, e2e_limit_type='max', e2e_model_dir=None, e2e_pgnet_mode='fast', e2e_pgnet_score_thresh=0.5, e2e_pgnet_valid_set='totaltext', enable_mkldnn=False, fourier_degree=5, gpu_mem=500, help='==SUPPRESS==', image_dir=None, image_orientation=False, ir_optim=True, kie_algorithm='LayoutXLM', label_list=['0', '90'], lang='en', layout=True, layout_dict_path=None, layout_model_dir=None, layout_nms_threshold=0.5, layout_score_threshold=0.5, max_batch_size=10, max_text_length=25, merge_no_span_structure=True, min_subgraph_size=15, mode='structure', ocr=True, ocr_order_method=None, ocr_version='PP-OCRv3', output='./output', page_num=0, precision='fp32', process_id=0, re_model_dir=None, rec=True, rec_algorithm='SVTR_LCNet', rec_batch_num=6, rec_char_dict_path='/opt/program/ppocr/utils/en_dict.txt', rec_image_inverse=True, rec_image_shape='3, 48, 320', rec_model_dir='/opt/program/inference/en_PP-OCRv3_rec_infer', recovery=False, save_crop_res=False, save_log_path='./log_output/', scales=[8, 16, 32], ser_dict_path='../train_data/XFUND/class_list_xfun.txt', ser_model_dir=None, show_log=True, sr_batch_num=1, sr_image_shape='3, 32, 128', sr_model_dir=None, structure_version='PP-StructureV2', table=True, table_algorithm='TableAttn', table_char_dict_path=None, table_max_len=488, table_model_dir=None, total_process_num=1, type='ocr', use_angle_cls=True, use_dilation=False, use_gpu=True, use_mp=False, use_npu=False, use_onnx=False, use_pdf2docx_api=False, use_pdserving=False, use_space_char=True, use_tensorrt=False, use_visual_backbone=True, use_xpu=False, vis_font_path='./doc/fonts/simfang.ttf', warmup=False)


问:
Ffmpeg hls live stream video freezes for a second but audio continues and video catches up
I am using the latest version of ffmpeg to create a hls live stream todo this i am using the following command

```<code>/root/ffmpeg -y -loglevel debug -threads 0 -probesize 512000 -analyzeduration 512000 -user_agent "Chrome/98.0.4758.102" -i https://example.com/input.m3u8 -c:v copy -c:a copy -async 1 -tune zerolatency -fflags +genpts -hls_init_time 2.002 -hls_time 2.002 -hls_list_size 20 -hls_flags delete_segments+append_list -hls_segment_type mpegts -hls_segment_filename "/var/www/html/hls/segment_%05d.ts" -f hls "/var/www/html/hls/playlist.m3u8"
</code>```

I initially tried using fmp4 but i noticed the video would lag behind major and the audio would end up well ahead so i switched to mpegts

i managed to fix the audio issue here using -async 1 on fmp4 this made no diffrence now i have a small issue where my stream will open and play but the video will freez every few seconds while the audio continues and then the video will jump to catch back up and continue then it will do it again and again and again

dose anyone know what may be causing this issue i tried swapping to x264 in stead of copying the video stream and using force key frames to set a key frame every 2 seconds but this resulted in well the same issue if not a little worse

i kind of expected the stream to play perfect with the settings i have and with the logs set to debug i cant see any errors at all

Body:
I am using the latest version of ffmpeg to create a hls live stream todo this i am using the following command

/root/ffmpeg -y -loglevel debug -threads 0 -probesize 512000 -analyzeduration 512000 -user_agent "Chrome/98.0.4758.102" -i https://example.com/input.m3u8 -c:v copy -c:a copy -async 1 -tune zerolatency -fflags +genpts -hls_init_time 2.002 -hls_time 2.002 -hls_list_size 20 -hls_flags delete_segments+append_list -hls_segment_type mpegts -hls_segment_filename "/var/www/html/hls/segment_%05d.ts" -f hls "/var/www/html/hls/playlist.m3u8"

I initially tried using fmp4 but i noticed the video would lag behind major and the audio would end up well ahead so i switched to mpegts

i managed to fix the audio issue here using -async 1 on fmp4 this made no diffrence now i have a small issue where my stream will open and play but the video will freez every few seconds while the audio continues and then the video will jump to catch back up and continue then it will do it again and again and again

dose anyone know what may be causing this issue i tried swapping to x264 in stead of copying the video stream and using force key frames to set a key frame every 2 seconds but this resulted in well the same issue if not a little worse

i kind of expected the stream to play perfect with the settings i have and with the logs set to debug i cant see any errors at all


问:
npm start is sending a weird "file not found" on fresh install of react app
```<code>npm install
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\15029\mushrooms/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\15029\mushrooms\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\15029\AppData\Local\npm-cache\_logs\2022-12-13T23_57_54_280Z-debug-0.log
</code>```

I've deleted and re-installed node. I tried NPM update, NPM install. I've verified the package.json file 100% exists. I don't know what else to do. This is a fresh create-react-app installation.

I have been having a boatload of problems with NPM lately. All I did was create-react-app and then install Tailwindcss from the tailwind docs. I have the package.json file how is it telling me it doesn't exist? I also installed react-scripts.

Body:
npm install
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\15029\mushrooms/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\15029\mushrooms\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\15029\AppData\Local\npm-cache\_logs\2022-12-13T23_57_54_280Z-debug-0.log

I've deleted and re-installed node. I tried NPM update, NPM install. I've verified the package.json file 100% exists. I don't know what else to do. This is a fresh create-react-app installation.

I have been having a boatload of problems with NPM lately. All I did was create-react-app and then install Tailwindcss from the tailwind docs. I have the package.json file how is it telling me it doesn't exist? I also installed react-scripts.


问:
I get the following error when trying to create a mongodb connection in a test with jest. Error: Error: getaddrinfo EAI_AGAIN mongo
I get the following error when trying to create a mongodb connection in a test with jest.
Error: Error: getaddrinfo EAI_AGAIN mongo

test.js:
`

```<code>const {MongoClient} = require('mongodb');

let plugin = this
let connection
let db
beforeAll(async () => {

    plugin.cfg = {
        mongo: {
            url: 'mongodb://mongo:27017/',
            dbwildduck: 'wildduck',
            dbwebsite: 'website',
        },
        redis: {
            host: 'redis',
            port: 6379,
            db: 3
        },
    }

    plugin.db = {
        wildduck: null,
        website: null,
        redis: null
    }

    try {
        connection = await MongoClient.connect(plugin.cfg.mongo.url);
        db = await connection.db(plugin.db.wildduck);

    } catch (error) {
        throw error
    }
})
</code>```

`

when I debug the test, it gets to the first line inside the "try":
``connection = await MongoClient.connect(plugin.cfg.mongo.url);

it reaches that line and waits until the error mentioned above appears

I need to create this connection with mongodb to pass it by parameter to a method so that it can make the queries that it has inside

I need to create this connection with mongodb to pass it by parameter to a method so that it can make the queries that it has inside

Body:
I get the following error when trying to create a mongodb connection in a test with jest.
Error: Error: getaddrinfo EAI_AGAIN mongo

test.js:
`

const {MongoClient} = require('mongodb');

let plugin = this
let connection
let db
beforeAll(async () => {

    plugin.cfg = {
        mongo: {
            url: 'mongodb://mongo:27017/',
            dbwildduck: 'wildduck',
            dbwebsite: 'website',
        },
        redis: {
            host: 'redis',
            port: 6379,
            db: 3
        },
    }

    plugin.db = {
        wildduck: null,
        website: null,
        redis: null
    }

    try {
        connection = await MongoClient.connect(plugin.cfg.mongo.url);
        db = await connection.db(plugin.db.wildduck);

    } catch (error) {
        throw error
    }
})

`

when I debug the test, it gets to the first line inside the "try":
``connection = await MongoClient.connect(plugin.cfg.mongo.url);

it reaches that line and waits until the error mentioned above appears

I need to create this connection with mongodb to pass it by parameter to a method so that it can make the queries that it has inside

I need to create this connection with mongodb to pass it by parameter to a method so that it can make the queries that it has inside


问:
How can I extend Pytube?
I want extend pytube on python. But I have some error. <<ImportError: cannot import name 'youtube' from 'pytube' (C: \Users\ DELL\AppData\I
cal Programs \Python \Python311\Lib\site-packages\pytube

init.py>> someone can help me please?

I tried to coding a YouTubedownloader

Title: How can I extend Pytube?


问:
Intercept/Block outgoing requests from Node.js server
I have a simple index.html file with a function to send a request:

```<code><!DOCTYPE html>
<html>
    <head>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    </head>
    <body>
        <button onclick="sendReq()">
            Send request
        </button>
        <script>
            function sendReq() {
                axios.get("http://ip-api.com/json")
            }
        </script>
    </body>
</html>
</code>```

Note: in this file, requests can be sent not only using the axios method, but also using XMLHttpRequest and fetch.

And also I have a server written in standard http from node

```<code>const http = require("http"),
  proxy = require('node-global-proxy').default,
  fs = require("fs")

const PROXY_URL = "localhost:5050"
const SERVER_PORT = 5000
const PROXY_SRV_PORT = 5050

const server = http.createServer((req, res) => {
  fs.readFile(`${__dirname}/index.html`, (err, data) => {
    res.writeHead(200)
    res.end(data)
  })
})

const proxy_srv = http.createServer((req, res) => {
  console.log(`[proxy_srv] New req accepted. Url: ${req.url}`)
})

const test = async() => {
  proxy.system()
  proxy.setConfig({
    http: `http://${PROXY_URL}`,
    https: `https://${PROXY_URL}`
  })
  proxy.start()

  // A request sent directly from the server is intercepted, but outgoing requests from [server] are not intercepted
  await http.get("http://jsonplaceholder.typicode.com/")
}

const bootstrap = () => {
  try {
    server.listen(SERVER_PORT)
    proxy_srv.listen(PROXY_SRV_PORT)
    console.log(`[server] Started on port ${SERVER_PORT} \n[proxy_srv] Started on port ${PROXY_SRV_PORT}`)
  } catch(e) {
    console.log(e)
  }
}

bootstrap()
test()
</code>```

If you run this code you will see something like:

```<code>[server] Started on port 5000
[proxy_srv] Started on port 5050
[proxy_srv] New req accepted. Url: http://jsonplaceholder.typicode.com/
</code>```

But if you try to send a request in the browser from the host http://localhost:5000/, then nothing will happen, and the global proxy will not see requests coming from the server

In reality, instead of a small http server, I have a huge express server with a bunch of APIs, and instead of an html file, I have an build of react ts application, but since this does not change the essence of the problem, I decided not to load the already bloated question

I will be eternally grateful for any answer.
Thanks in advance.

I need to intercept/block outgoing requests to a specific domain from a client

Important: I don't have access to request intitiators as I'm trying to intercept/block requests initiated inside an iframe, so I need a way to intercept/block it at the lowest possible level, whether it's the TCP connection initiation stage or sending the request to the server

I understand that I am doing something wrong. I've tried using http.globalAgent but I don't understand how to use this to add the proxy with url field of my proxy to every request outgoing from the server.

Body:
I have a simple index.html file with a function to send a request:

<!DOCTYPE html>

        <button onclick="sendReq()">
            Send request
        </button>

Note: in this file, requests can be sent not only using the axios method, but also using XMLHttpRequest and fetch.

And also I have a server written in standard http from node

const http = require("http"),
  proxy = require('node-global-proxy').default,
  fs = require("fs")

const PROXY_URL = "localhost:5050"
const SERVER_PORT = 5000
const PROXY_SRV_PORT = 5050

const server = http.createServer((req, res) => {
  fs.readFile(`${__dirname}/index.html`, (err, data) => {
    res.writeHead(200)
    res.end(data)
  })
})

const proxy_srv = http.createServer((req, res) => {
  console.log(`[proxy_srv] New req accepted. Url: ${req.url}`)
})

const test = async() => {
  proxy.system()
  proxy.setConfig({
    http: `http://${PROXY_URL}`,
    https: `https://${PROXY_URL}`
  })
  proxy.start()

  // A request sent directly from the server is intercepted, but outgoing requests from [server] are not intercepted
  await http.get("http://jsonplaceholder.typicode.com/")
}

const bootstrap = () => {
  try {
    server.listen(SERVER_PORT)
    proxy_srv.listen(PROXY_SRV_PORT)
    console.log(`[server] Started on port ${SERVER_PORT} \n[proxy_srv] Started on port ${PROXY_SRV_PORT}`)
  } catch(e) {
    console.log(e)
  }
}

bootstrap()
test()

If you run this code you will see something like:

[server] Started on port 5000
[proxy_srv] Started on port 5050
[proxy_srv] New req accepted. Url: http://jsonplaceholder.typicode.com/

But if you try to send a request in the browser from the host http://localhost:5000/, then nothing will happen, and the global proxy will not see requests coming from the server

In reality, instead of a small http server, I have a huge express server with a bunch of APIs, and instead of an html file, I have an build of react ts application, but since this does not change the essence of the problem, I decided not to load the already bloated question

I will be eternally grateful for any answer.
Thanks in advance.

I need to intercept/block outgoing requests to a specific domain from a client

Important: I don't have access to request intitiators as I'm trying to intercept/block requests initiated inside an iframe, so I need a way to intercept/block it at the lowest possible level, whether it's the TCP connection initiation stage or sending the request to the server

I understand that I am doing something wrong. I've tried using http.globalAgent but I don't understand how to use this to add the proxy with url field of my proxy to every request outgoing from the server.


问:
RaspberryPi GPIO assembly program digitalRead returning HIGH without any physical button press
This Question is a Repost, I figured I would just start all over again seeing as how there were several issues regarding context and formatting in it

Program Function:

The function of my program is to blink LEDs on and off through the use of a loop when one of three buttons is pressed.

When BTN_LEFT is input and read as HIGH, the program should ideally branch to the BLNKR_LEFT loop where it should blink LED_LEFT on and off until BTN_LEFT is read as LOW.

When BTN_HZRD is read as HIGH, the program should branch to the BLNKR_HZRD loop and blink LED_LEFT and LED_RIGHT on and off until BTN_HZRD is read as LOW

When BTN_RIGHT is input and read as HIGH, the program should branch to the BLNKR_RIGHT loop and blink LED_RIGHT on and off until BTN_RIGHT is read as LOW.

During these three BLNKR loops, when their respective BTN inputs are returning LOW, the program should branch back to the INPUT loop and continue reading for input from any of the three buttons.

// to compile: g++ redLed.s -lwiringPi -g -o redLed
// Program will power an LED when button is pressed, and when button is not pressed, LED will remain off

.equ INPUT, 0
.equ OUTPUT, 1
.equ LOW, 0
.equ HIGH, 1

.equ LED_LEFT, 29   // wiringPi 29 (bcm 21)
.equ LED_RIGHT, 28  // wiringPi 28 (bcm 20)
.equ BTN_LEFT, 23   // wiringPi 23 (bcm 13)
.equ BTN_HZRD, 22   // wiringPi 22 (bcm 6)
.equ BTN_RIGHT, 21  // wiringPi 21 (bcm 5)

.text
.global main
main:
// int main()
    push {lr} // {
    bl wiringPiSetup // wiringPiSetup(); // initialize the wiringPi library

    // Initialize our WPI inputs and outputs
    mov r0, #LED_LEFT // pinMode(29,OUTPUT); // set the wpi 29 pin for output
    mov r1, #OUTPUT
    bl pinMode

    mov r0, #LED_RIGHT // pinMode(28,OUTPUT); // set the wpi 28 pin for output
    mov r1, #OUTPUT
    bl pinMode

    mov r0, #BTN_LEFT  // pinMode(23,INPUT); // set the wpi 23 pin for input
    mov r1, #INPUT
    bl pinMode

    mov r0, #BTN_HZRD // pinMode(22,INPUT); // set the wpi 22 pin for input
    mov r1, #INPUT
    bl pinMode

    mov r0, #BTN_RIGHT // pinMode(21,INPUT); // set the wpi 21 pin for input
    mov r1, #INPUT
    bl pinMode

    // Searches for an input from any button, if there is no input, then the program will keep looping
INPUT:
    // Set both LEDs to LOW
    mov r0, #LED_LEFT
    mov r1, #LOW
    bl digitalWrite

    mov r0, #LED_RIGHT
    mov r1, #LOW
    bl digitalWrite

    // Read for input from BTN_LEFT, BTN_RIGHT, or BTN_HZRD
    mov r0, #BTN_LEFT
    bl digitalRead    // digitalRead(BTN_LEFT);

    mov r1, #HIGH
    cmp r0, r1
    bleq BLNKR_LEFT

    // Read for input from BTN_HZRD
    mov r0, #BTN_HZRD
    bl digitalRead

    mov r1, #HIGH
    cmp r0, r1
    bleq BLNKR_HZRD

    // Read for input from BTN_RIGHT
    mov r0, #BTN_RIGHT
    bl digitalRead

    mov r1, #HIGH
    cmp r0, r1
    bleq BLNKR_RIGHT
    b INPUT

BLNKR_LEFT:
    // If BTN_LEFT is not being pressed then the program will return to INPUT
    mov r0, #BTN_LEFT
    bl digitalRead

    mov r1, #LOW
    cmp r0, r1
    bleq INPUT

    mov r0, #LED_LEFT // digitalWrite(29,HIGH); // write high volt signal to pin 29
    mov r1, #HIGH
    bl digitalWrite

    ldr r0, =#350 // delay(350); // Delay for 350 milliseconds
    bl delay

    mov r0, #LED_LEFT // digitalWrite(29,LOW); // write low voltage to wpi 29 to turn off the led
    mov r1, #LOW
    bl digitalWrite

    ldr r0, =#350
    bl delay

    b BLNKR_LEFT

BLNKR_HZRD:
    // If BTN_HZRD isnt being pressed then the program will branch back to INPUT
    mov r0, #BTN_HZRD
    bl digitalRead

    mov r1, #LOW
    cmp r0, r1
    bleq INPUT

    // Turn on both LED_LEFT and LED_RIGHT
    mov r0, #LED_LEFT
    mov r1, #HIGH
    bl digitalWrite

    mov r0, #LED_RIGHT
    mov r1, #HIGH
    bl digitalWrite

    // delay for 350 milliseconds
    ldr r0, =#350
    bl delay

    // Turn off both LED_LEFT and LED_RIGHT
    mov r0, #LED_LEFT
    mov r1, #LOW
    bl digitalWrite

    mov r0,#LED_RIGHT
    mov r1, #LOW
    bl digitalWrite

    // Delay for 350 milliseconds
    ldr r0, =#350
    bl delay

    b BLNKR_HZRD

BLNKR_RIGHT:
    // If BTN_RIGHT isnt being pressed then the program will branch back to INPUT
    mov r0, #BTN_RIGHT
    bl digitalRead

    cmp r0, #LOW
    bleq INPUT

    // Turn on LED_RIGHT
    mov r0, #LED_RIGHT
    mov r1, #HIGH
    bl digitalWrite

    // delay for 350 milliseconds
    ldr r0, =#350
    bl delay

    // Turn off LED_RIGHT
    mov r0,#LED_RIGHT
    mov r1, #LOW
    bl digitalWrite

    // Delay for 350 milliseconds
    ldr r0, =#350
    bl delay

    b BLNKR_RIGHT

    mov r0, #0 // return 0;
    pop {pc} // }
```

The Problem:

When I run the program, either the BLKNR_LEFT or BLNKR_HZRD loop will begin to run without any physical press of either of the three BTNs, depending on which cmp is executed first.

When I run the program, upon execution of digitalRead for BTN_LEFT or BTN_HZRD, the value stored in r0 will be HIGH even though I did not physically press the button, however, upon execution of digitalRead for BTN_RIGHT, r0 will correctly display either HIGH or LOW depending on whether the button is physically being pressed or not.

I have tried using different button switches, but that didn't seem to fix the issue with BTN_LEFT and BTN_HZRD returning HIGH. Image of my wiring I believe my issue might be lying in my breadboard wiring,and any help regarding this issue would be very appreciated.

Solution:

So, it turns out the pins that I had my BTN values connected to BCM 5 BCM 6 were by default supposed to register as HIGH, the only one that wasn't defaulted at HIGH was BCM 13 which worked fine. I did not feel interested enough in fixing this or changing the reading of the pins so I simply re-pinned BTN_LEFT and BTN_HZRD to BCM 13 and BCM 19. Of course, I re-pinned BTN_RIGHT to BCM 26. These three BCM pins are by default on my gpio readall returning as LOW and my program works fine now. Thank you guys for all the help because even though the problem was so simple I wouldn't have learnt how to use such a debugger without coming here.

Linked below is a screenshot of gpio readall in which the voltage on BCM pins 5 and 6 are displaying 1, while BCM pins 13, 19, and 26 are reading a voltage of 0. I have tried using PUD_DOWN internal resistors to combat any sort of floating pins there may be.

screenshot of gpio readall

Body:
This Question is a Repost, I figured I would just start all over again seeing as how there were several issues regarding context and formatting in it

Program Function:

The function of my program is to blink LEDs on and off through the use of a loop when one of three buttons is pressed.

When BTN_LEFT is input and read as HIGH, the program should ideally branch to the BLNKR_LEFT loop where it should blink LED_LEFT on and off until BTN_LEFT is read as LOW.

When BTN_HZRD is read as HIGH, the program should branch to the BLNKR_HZRD loop and blink LED_LEFT and LED_RIGHT on and off until BTN_HZRD is read as LOW

When BTN_RIGHT is input and read as HIGH, the program should branch to the BLNKR_RIGHT loop and blink LED_RIGHT on and off until BTN_RIGHT is read as LOW.

During these three BLNKR loops, when their respective BTN inputs are returning LOW, the program should branch back to the INPUT loop and continue reading for input from any of the three buttons.

// to compile: g++ redLed.s -lwiringPi -g -o redLed
// Program will power an LED when button is pressed, and when button is not pressed, LED will remain off

.equ INPUT, 0
.equ OUTPUT, 1
.equ LOW, 0
.equ HIGH, 1

.equ LED_LEFT, 29   // wiringPi 29 (bcm 21)
.equ LED_RIGHT, 28  // wiringPi 28 (bcm 20)
.equ BTN_LEFT, 23   // wiringPi 23 (bcm 13)
.equ BTN_HZRD, 22   // wiringPi 22 (bcm 6)
.equ BTN_RIGHT, 21  // wiringPi 21 (bcm 5)

.text
.global main
main:
// int main()
    push {lr} // {
    bl wiringPiSetup // wiringPiSetup(); // initialize the wiringPi library

    // Initialize our WPI inputs and outputs
    mov r0, #LED_LEFT // pinMode(29,OUTPUT); // set the wpi 29 pin for output
    mov r1, #OUTPUT
    bl pinMode

    mov r0, #LED_RIGHT // pinMode(28,OUTPUT); // set the wpi 28 pin for output
    mov r1, #OUTPUT
    bl pinMode

    mov r0, #BTN_LEFT  // pinMode(23,INPUT); // set the wpi 23 pin for input
    mov r1, #INPUT
    bl pinMode

    mov r0, #BTN_HZRD // pinMode(22,INPUT); // set the wpi 22 pin for input
    mov r1, #INPUT
    bl pinMode

    mov r0, #BTN_RIGHT // pinMode(21,INPUT); // set the wpi 21 pin for input
    mov r1, #INPUT
    bl pinMode

    // Searches for an input from any button, if there is no input, then the program will keep looping
INPUT:
    // Set both LEDs to LOW
    mov r0, #LED_LEFT
    mov r1, #LOW
    bl digitalWrite

    mov r0, #LED_RIGHT
    mov r1, #LOW
    bl digitalWrite

    // Read for input from BTN_LEFT, BTN_RIGHT, or BTN_HZRD
    mov r0, #BTN_LEFT
    bl digitalRead    // digitalRead(BTN_LEFT);

    mov r1, #HIGH
    cmp r0, r1
    bleq BLNKR_LEFT

    // Read for input from BTN_HZRD
    mov r0, #BTN_HZRD
    bl digitalRead

    mov r1, #HIGH
    cmp r0, r1
    bleq BLNKR_HZRD

    // Read for input from BTN_RIGHT
    mov r0, #BTN_RIGHT
    bl digitalRead

    mov r1, #HIGH
    cmp r0, r1
    bleq BLNKR_RIGHT
    b INPUT

BLNKR_LEFT:
    // If BTN_LEFT is not being pressed then the program will return to INPUT
    mov r0, #BTN_LEFT
    bl digitalRead

    mov r1, #LOW
    cmp r0, r1
    bleq INPUT

    mov r0, #LED_LEFT // digitalWrite(29,HIGH); // write high volt signal to pin 29
    mov r1, #HIGH
    bl digitalWrite

    ldr r0, =#350 // delay(350); // Delay for 350 milliseconds
    bl delay

    mov r0, #LED_LEFT // digitalWrite(29,LOW); // write low voltage to wpi 29 to turn off the led
    mov r1, #LOW
    bl digitalWrite

    ldr r0, =#350
    bl delay

    b BLNKR_LEFT

BLNKR_HZRD:
    // If BTN_HZRD isnt being pressed then the program will branch back to INPUT
    mov r0, #BTN_HZRD
    bl digitalRead

    mov r1, #LOW
    cmp r0, r1
    bleq INPUT

    // Turn on both LED_LEFT and LED_RIGHT
    mov r0, #LED_LEFT
    mov r1, #HIGH
    bl digitalWrite

    mov r0, #LED_RIGHT
    mov r1, #HIGH
    bl digitalWrite

    // delay for 350 milliseconds
    ldr r0, =#350
    bl delay

    // Turn off both LED_LEFT and LED_RIGHT
    mov r0, #LED_LEFT
    mov r1, #LOW
    bl digitalWrite

    mov r0,#LED_RIGHT
    mov r1, #LOW
    bl digitalWrite

    // Delay for 350 milliseconds
    ldr r0, =#350
    bl delay

    b BLNKR_HZRD

BLNKR_RIGHT:
    // If BTN_RIGHT isnt being pressed then the program will branch back to INPUT
    mov r0, #BTN_RIGHT
    bl digitalRead

    cmp r0, #LOW
    bleq INPUT

    // Turn on LED_RIGHT
    mov r0, #LED_RIGHT
    mov r1, #HIGH
    bl digitalWrite

    // delay for 350 milliseconds
    ldr r0, =#350
    bl delay

    // Turn off LED_RIGHT
    mov r0,#LED_RIGHT
    mov r1, #LOW
    bl digitalWrite

    // Delay for 350 milliseconds
    ldr r0, =#350
    bl delay

    b BLNKR_RIGHT

    mov r0, #0 // return 0;
    pop {pc} // }

The Problem:

When I run the program, either the BLKNR_LEFT or BLNKR_HZRD loop will begin to run without any physical press of either of the three BTNs, depending on which cmp is executed first.

When I run the program, upon execution of digitalRead for BTN_LEFT or BTN_HZRD, the value stored in r0 will be HIGH even though I did not physically press the button, however, upon execution of digitalRead for BTN_RIGHT, r0 will correctly display either HIGH or LOW depending on whether the button is physically being pressed or not.

I have tried using different button switches, but that didn't seem to fix the issue with BTN_LEFT and BTN_HZRD returning HIGH. Image of my wiring I believe my issue might be lying in my breadboard wiring,and any help regarding this issue would be very appreciated.

Solution:

So, it turns out the pins that I had my BTN values connected to BCM 5 BCM 6 were by default supposed to register as HIGH, the only one that wasn't defaulted at HIGH was BCM 13 which worked fine. I did not feel interested enough in fixing this or changing the reading of the pins so I simply re-pinned BTN_LEFT and BTN_HZRD to BCM 13 and BCM 19. Of course, I re-pinned BTN_RIGHT to BCM 26. These three BCM pins are by default on my gpio readall returning as LOW and my program works fine now. Thank you guys for all the help because even though the problem was so simple I wouldn't have learnt how to use such a debugger without coming here.

Linked below is a screenshot of gpio readall in which the voltage on BCM pins 5 and 6 are displaying 1, while BCM pins 13, 19, and 26 are reading a voltage of 0. I have tried using PUD_DOWN internal resistors to combat any sort of floating pins there may be.

screenshot of gpio readall


问:
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'value')
I want to read the following values from my form like donutName, email, company, comments, quantity,... in my onMounted part but it says "Uncaught (in promise) TypeError: Cannot read properties of null (reading 'value')". But when I put my values outside of my onmounted it only gets the values but nothing from my donut.

This is my code:

```<code><script setup>
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

import { ref, onMounted } from "vue";

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

const renderer = new THREE.WebGLRenderer();
onMounted(() => {
  document.querySelector(".hero__btn").addEventListener("click", () => {
    postDonut();
  });

  renderer.setSize(window.innerWidth / 2, window.innerHeight / 2);
  document
    .querySelector(".configurator__donut")
    .appendChild(renderer.domElement);

  // change camera aspect ratio on resize
  window.addEventListener("resize", () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth / 2, window.innerHeight / 2);
  });

  renderer.setClearColor(0xffffff, 1);

  // orbit controls
  const controls = new OrbitControls(camera, renderer.domElement);

  // ambient light
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
  scene.add(ambientLight);

  // directional light
  const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  directionalLight.position.set(30, 20, 10);
  scene.add(directionalLight);

  // load gltf model
  let donut;
  const loader = new GLTFLoader();
  loader.load(
    "/model/Donut_chocolate.gltf",
    function (gltf) {
      donut = gltf.scene;
      donut.scale.set(5, 5, 5);
      donut.position.set(0, 0, 0);
      gltf.scene.rotation.x = Math.PI * -0.2;
      const material = new THREE.MeshStandardMaterial({
        color: 0x000000,
        flatShading: true,
        depthWrite: false,
        blending: THREE.MixOperation,
        transparent: true,
        alphaTest: 0.5,
      });
      //get the children
      const children = donut.children;

      // set the default donut
      donut.children[2].visible = false;
      donut.children[3].visible = false;
      donut.children[1].material.color.set(0xffffff);
      donut.children[4].visible = false;

      console.log(children);

      //   let dough = children[0];
      //   let glazeColor = children[1].material.color;
      //   let sprinkels = children[2];
      //   let sprinkelsColor = children[2].material.color;
      //   let marshmallows = children[3];
      //   let chocolate = children[4];

      scene.add(donut);
    },
    undefined,
    function (error) {
      console.error(error);
    }
  );

  // create the card for the company logo
  const planeGeometry = new THREE.PlaneGeometry(0.15, 0.1);
  const planeMaterial = new THREE.MeshLambertMaterial({ color: 0xd2d2d2 });
  let companyCard = new THREE.Mesh(planeGeometry, planeMaterial);
  companyCard.name = "companyCard";
  companyCard.position.set(0.15, 0, 0.103);
  companyCard.rotation.y = 0.06 * Math.PI;
  companyCard.rotation.x = -0.15 * Math.PI;
  scene.add(companyCard);

  // add the logo to the donut companyCard
  const branding = document.getElementById("company__logo");
  branding.addEventListener("change", (e) => {
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      // Load the new texture
      const texture = new THREE.TextureLoader().load(reader.result);

      // Get the plane object
      const plane = scene.getObjectByName("companyCard");

      // Update the map property of the plane's material
      plane.material.map = texture;

      // Mark the material as needsUpdate
      plane.material.needsUpdate = true;
    };
  });

  // function to change topping
  const toppings = document.querySelectorAll(".topping__button");
  toppings.forEach((top) => {
    top.addEventListener("click", (e) => {
      if (e.target.value === "sprinkels") {
        donut.children[2].visible = true;
        donut.children[3].visible = false;
        donut.children[4].visible = false;
      } else if (e.target.value === "marshmallows") {
        donut.children[2].visible = false;
        donut.children[3].visible = true;
        donut.children[4].visible = false;
      } else if (e.target.value === "chocolade") {
        donut.children[2].visible = false;
        donut.children[3].visible = false;
        donut.children[4].visible = true;
      }
      topping = e.target.value;
      console.log(topping);
    });
  });

  // function to check if sprinkels are visible and open div suiker
  const sprinkelsButton = document.querySelector(".topping__button");
  sprinkelsButton.addEventListener("click", (e) => {
    if (donut.children[2].visible === true) {
      document.querySelector(".suiker").style.visibility = "visible";
      document.querySelector(".suiker").style.height = "auto";
    }
  });

  // function to close the suiker menu if the topping is not sprinkels
  const toppingButtons = document.querySelectorAll(".topping__button");
  toppingButtons.forEach((top) => {
    top.addEventListener("click", (e) => {
      if (e.target.value !== "sprinkels") {
        document.querySelector(".suiker").style.visibility = "hidden";
        document.querySelector(".suiker").style.height = "0";
      }
    });
  });

  // function to change color of topping sprinkels
  const toppingSprinkels = document.querySelectorAll(".sprinkels__button");
  toppingSprinkels.forEach((sprinkle) => {
    sprinkle.addEventListener("click", (e) => {
      donut.children[2].material.color.set(e.target.value);
      toppingColor = e.target.value;
      console.log(toppingColor);
    });
  });

  // function to display the branding on the donut with addLogo class without eventlistener
  const addLogo = document.querySelector(".addLogo");
  addLogo.addEventListener("click", (e) => {
    companyCard.visible = true;
  });

  // function to hide the branding on the donut with removeLogo class without eventlistener
  const removeLogo = document.querySelector(".removeLogo");
  removeLogo.addEventListener("click", (e) => {
    companyCard.visible = false;
  });

  const icing = document.querySelectorAll(".glaze__button");
  icing.forEach((ice) => {
    ice.addEventListener("click", (e) => {
      donut.children[1].material.color.set(e.target.value);
      console.log(e.target.value);
      glazeColor = e.target.value;
    });
  });

  let glazeColor = null;
  let topping = null;
  let toppingColor = null;
  let donutName = document.querySelector("#donutName").value;
  let company = document.querySelector("#company").value;
  let companyLogo = document.querySelector("#company__logo").value;
  let email = document.querySelector("#email").value;
  let snapshot = null;
  let quantity = document.querySelector("#quantity").value;
  let comment = document.querySelector("#comment").value;

  function postDonut() {
    console.log(glazeColor);
    let donut = {
      glazeColor: glazeColor,
      topping: topping,
      toppingColor: toppingColor,
      donutName: donutName,
      company: company,
      companyLogo: companyLogo,
      email: email,
      snapshot: snapshot,
      quantity: quantity,
      comment: comment,
    };
    fetch("https://donuttello-backend-5chz.onrender.com/api/v1/donuts/create", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(donut),
    })
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      });
  }
});

camera.position.z = 0.5;

function animate() {
  requestAnimationFrame(animate);

  renderer.render(scene, camera);
}
animate();
</script>

<template>
  <div>
    <div class="configurator__details">
      <h1 class="configurator__h1">Configurator</h1>
      <h2>Toppings</h2>
      <button class="topping__button" value="sprinkels" data-sprinkel="0">
        Sprinkels
      </button>
      <button class="topping__button" value="marshmallows" data-sprinkel="1">
        Marshmallows
      </button>
      <button class="topping__button" value="chocolade" data-sprinkel="2">
        Chocolade
      </button>

      <div class="suiker">
        <h2>Sprinkels</h2>
        <button value="#ff007f" class="sprinkels__button">rood</button>
        <button value="#ffffff" class="sprinkels__button">wit</button>
        <button value="#7d9a59" class="sprinkels__button">groen</button>
        <button value="#edbf04" class="sprinkels__button">geel</button>
        <button value="#673f37" class="sprinkels__button">bruin</button>
        <button value="#58a2e9" class="sprinkels__button">blauw</button>
        <button value="#800080" class="sprinkels__button">paars</button>
      </div>

      <h2>Glazuur</h2>
      <button value="#f174ba" class="glaze__button">lichtroos</button>
      <button value="#e72870" class="glaze__button">roos</button>
      <button value="#bb7e52" class="glaze__button">lichtbruin</button>
      <button value="#673f37" class="glaze__button">bruin</button>
      <button value="#da9034" class="glaze__button">oranje</button>
      <button value="#edbf04" class="glaze__button">geel</button>
      <button value="#7d9a59" class="glaze__button">groen</button>
      <button value="#bed4c8" class="glaze__button">appelblauwzeegroen</button>
      <button value="#ffffff" class="glaze__button">wit</button>
      <button value="#1e0802" class="glaze__button">zwart</button>

      <h2>Bedrijfslogo</h2>
      <button class="addLogo">Ja</button>
      <button class="removeLogo">Nee</button>
      <input
        type="file"
        id="company__logo"
        name="logo"
        accept="image/png, image/jpeg, image/jpg"
      />
    </div>
    <form class="configurator__info" @submit.prevent="postDonut">
      <div class="configurator__formulier">
        <h1 class="details__h1">Details</h1>
        <div class="configurator__form">
          <input
            v-model="donutName"
            type="text"
            id="donutName"
            name="donutName"
            required
          />
          <label for="donutName" class="configurator__label--wrapper">
            <span class="configurator__text">Naam Donut</span>
          </label>
        </div>

        <div class="configurator__form">
          <input
            v-model="company"
            type="text"
            id="company"
            name="company"
            required
          />
          <label for="company" class="configurator__label--wrapper">
            <span class="configurator__text">Naam Bedrijf</span>
          </label>
        </div>
        <div class="configurator__form">
          <input
            v-model="email"
            type="email"
            name="email"
            autocomplete="on"
            required
          />
          <label for="email" id="email" class="configurator__label--wrapper">
            <span class="configurator__text">Email</span>
          </label>
        </div>
        <div class="configurator__form">
          <input
            id="quantity"
            v-model="quantity"
            type="number"
            name="quantity"
            autocomplete="on"
            required
          />
          <label for="quantity" class="configurator__label--wrapper">
            <span class="configurator__text">Aantal Donuts</span>
          </label>
        </div>
        <div class="configurator__form">
          <input v-model="comment" type="text" id="comment" name="comment" required />
          <label for="comment" class="configurator__label--wrapper">
            <span class="configurator__text">Opmerkingen</span>
          </label>
        </div>
        <div class="configurator__button">
          <button type="submit" class="hero__btn">Verstuur je donut!</button>
        </div>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      donutName: "",
      company: "",
      email: "",
      quantity: "",
      comment: "",
    };
  },
};
</script>

</code>```

I tried this in a thousand ways but nothing seems to work.

Body:
I want to read the following values from my form like donutName, email, company, comments, quantity,... in my onMounted part but it says "Uncaught (in promise) TypeError: Cannot read properties of null (reading 'value')". But when I put my values outside of my onmounted it only gets the values but nothing from my donut.

This is my code:

<template>

Configurator

Toppings

      <button class="topping__button" value="sprinkels" data-sprinkel="0">
        Sprinkels
      </button>
      <button class="topping__button" value="marshmallows" data-sprinkel="1">
        Marshmallows
      </button>
      <button class="topping__button" value="chocolade" data-sprinkel="2">
        Chocolade
      </button>

Sprinkels

        <button value="#ff007f" class="sprinkels__button">rood</button>
        <button value="#ffffff" class="sprinkels__button">wit</button>
        <button value="#7d9a59" class="sprinkels__button">groen</button>
        <button value="#edbf04" class="sprinkels__button">geel</button>
        <button value="#673f37" class="sprinkels__button">bruin</button>
        <button value="#58a2e9" class="sprinkels__button">blauw</button>
        <button value="#800080" class="sprinkels__button">paars</button>

Glazuur

      <button value="#f174ba" class="glaze__button">lichtroos</button>
      <button value="#e72870" class="glaze__button">roos</button>
      <button value="#bb7e52" class="glaze__button">lichtbruin</button>
      <button value="#673f37" class="glaze__button">bruin</button>
      <button value="#da9034" class="glaze__button">oranje</button>
      <button value="#edbf04" class="glaze__button">geel</button>
      <button value="#7d9a59" class="glaze__button">groen</button>
      <button value="#bed4c8" class="glaze__button">appelblauwzeegroen</button>
      <button value="#ffffff" class="glaze__button">wit</button>
      <button value="#1e0802" class="glaze__button">zwart</button>

Bedrijfslogo

      <button class="addLogo">Ja</button>
      <button class="removeLogo">Nee</button>
      <input
        type="file"
        id="company__logo"
        name="logo"
        accept="image/png, image/jpeg, image/jpg"
      />

    <form class="configurator__info" @submit.prevent="postDonut">

Details

          <input
            v-model="donutName"
            type="text"
            id="donutName"
            name="donutName"
            required
          />

            Naam Donut

          <input
            v-model="company"
            type="text"
            id="company"
            name="company"
            required
          />

            Naam Bedrijf

          <input
            v-model="email"
            type="email"
            name="email"
            autocomplete="on"
            required
          />

            Email

          <input
            id="quantity"
            v-model="quantity"
            type="number"
            name="quantity"
            autocomplete="on"
            required
          />

            Aantal Donuts

          <input v-model="comment" type="text" id="comment" name="comment" required />

            Opmerkingen

          <button type="submit" class="hero__btn">Verstuur je donut!</button>

    </form>

</template>

I tried this in a thousand ways but nothing seems to work.


问:
WebSocket connection to 'ws://test.mosquitto.org:8080/mqtt' failed
There are similar questions on stackoverflow asked on this topic, and I have read through them all but still can't see what I am doing wrong.

I am trying to connect with (for now) the mosquitto test broker, using websockets.
As far as I can see, I have the correct host and port setup.

I created file websockets-4.htm (which I have pasted at the bottom of this post), and when I open it, I get the following feedback:

```<code>connecting to test.mosquitto.org
WebSocket connection to 'ws://test.mosquitto.org:8080/mqtt' failed
  k._doConnect @mqttws31.min.js:36
  k.connect @mqttws31.min.js:31
  I.connect @mqttws31.min.js:65
  MQTTconnect @websockets-4.htm:53
  (anonymous) @websockets-4.htm:61
</code>```

Can anyone see what I am doing wrong?

Here is the websockets-4.htm file:

(Note: I just added a function to be called on 'client.onFailure', however I am not even sure if this is a valid property)

```<code><html>
<head>
  <title>MQTT WebSocket Example</title>
  <style></style>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript">
  </script>
  <script type = "text/javascript" language="javascript">
    var mqtt;

    host = "test.mosquitto.org"
    port = 8080;
    clientId = "myclientid111_" + parseInt(Math.random() * 100, 10)

// Create a client instance
    var client = new Paho.MQTT.Client(host, Number(port), clientId);

// set callback handlers
    client.onConnectionLost = onConnectionLost;
    client.onMessageArrived = onMessageArrived;
    client.onFailure = onFailedConnection;

// called when the client connects
    function onConnect() {
      console.log("onConnect");
      message = new Paho.MQTT.Message("topic1");
      message.destinationName = "topic1";
      client.send(message);
    }

// called when the client loses its connection
    function onConnectionLost(responseObject) {
      if (responseObject.errorCode !== 0) {
        console.log("onConnectionLost:"+responseObject.errorMessage);
      }
    }

    function onFailedConnection(responseObject) {
      if (responseObject.errorCode !== 0) {
        console.log("onFailedConnection:"+responseObject.errorMessage);
      }
    }

// called when a message arrives
    function onMessageArrived(message) {
      console.log("onMessageArrived:"+message.payloadString);
    }

    function MQTTconnect() {
      console.log("connecting to " + host);
// connect the client
//client.connect({onSuccess:onConnect});
client.connect({onSuccess:onConnect, cleanSession:true, useSSL:false, keepAliveInterval:10}); // line 53
}

</script>
</head>
<body>
  <h1>Main Body</h1>
  <script>
MQTTconnect();  // line 61
</script>
</body>
</html>
</code>```

Body:
There are similar questions on stackoverflow asked on this topic, and I have read through them all but still can't see what I am doing wrong.

I am trying to connect with (for now) the mosquitto test broker, using websockets.
As far as I can see, I have the correct host and port setup.

I created file websockets-4.htm (which I have pasted at the bottom of this post), and when I open it, I get the following feedback:

connecting to test.mosquitto.org
WebSocket connection to 'ws://test.mosquitto.org:8080/mqtt' failed
  k._doConnect @mqttws31.min.js:36
  k.connect @mqttws31.min.js:31
  I.connect @mqttws31.min.js:65
  MQTTconnect @websockets-4.htm:53
  (anonymous) @websockets-4.htm:61

Can anyone see what I am doing wrong?

Here is the websockets-4.htm file:

(Note: I just added a function to be called on 'client.onFailure', however I am not even sure if this is a valid property)

  <title>MQTT WebSocket Example</title>

Main Body


问:
I can't remove the background from a resized transparent png image
I have a transparent png image. i'm trying to resize it using a function.

```<code>function resize_image($image, int $newWidth, int $newHeight) {
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    imagealphablending($newImage, false);
    imagesavealpha($newImage,true);
    $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
    imagefilledrectangle($newImage, 0, 0, $newWidth, $newHeight, $transparent);
    $src_w = imagesx($image);
    $src_h = imagesy($image);
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h);
    return $newImage;
}
</code>```

But it still return a png with a colored background.

It seems it only works on transparent bakcground with opacity = 0. How can I solve the problem?
I tried removing the two lines that reprocess the background, but it doesn't change anything.

Body:
I have a transparent png image. i'm trying to resize it using a function.

function resize_image($image, int $newWidth, int $newHeight) {
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    imagealphablending($newImage, false);
    imagesavealpha($newImage,true);
    $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
    imagefilledrectangle($newImage, 0, 0, $newWidth, $newHeight, $transparent);
    $src_w = imagesx($image);
    $src_h = imagesy($image);
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h);
    return $newImage;
}

But it still return a png with a colored background.

It seems it only works on transparent bakcground with opacity = 0. How can I solve the problem?
I tried removing the two lines that reprocess the background, but it doesn't change anything.


问:
build and run an RNN regression model
below is an example of an RNN regression model with two layers.

layer 1 uses an LSTM module with 5 hidden units.

layer 2 uses a fully connected module with one unit

```<code>class RNN(nn.Module):
    def __init__(self, i_size, h_size, n_layers, o_size, dropout=0.1, bidirectional=True):
        super(RNN, self).__init__()
        self.num_directions = bidirectional+1
        self.rnn = nn.LSTM(
            input_size=i_size,
            hidden_size=h_size,
            num_layers=n_layers,
            dropout=dropout,
            bidirectional=bidirectional
        )
        self.out = nn.Linear(h_size, o_size)

    def forward(self, x, h_state):
        r_out, hidden_state = self.rnn(x, h_state)

        hidden_size = hidden_state[-1].size(-1)
        r_out = r_out.view(-1, self.num_directions, hidden_size)
        outs = self.out(r_out)

        return outs, hidden_state
</code>```
```<code># Globals

INPUT_SIZE = 7
HIDDEN_SIZE = 64
NUM_LAYERS = 3
OUTPUT_SIZE = 1
BATCH_SIZE = 128
# Hyper parameters

learning_rate = 0.001
num_epochs = 300

rnn = RNN(INPUT_SIZE, HIDDEN_SIZE, NUM_LAYERS, OUTPUT_SIZE,bidirectional=False)
rnn.cuda()

optimiser = torch.optim.Adam(rnn.parameters(), lr=learning_rate)
criterion = nn.MSELoss()

hidden_state = None
</code>```
```<code>history = []
X_test_cuda = torch.tensor(X_test).float().cuda()
y_test_cuda = torch.tensor(y_test).float().cuda()

# we use all the data in one batch
inputs_cuda = torch.tensor(X_train).float().cuda()
labels_cuda = torch.tensor(y_train).float().cuda()

for epoch in range(num_epochs):
    rnn.train()
    output, _ = rnn(inputs_cuda, hidden_state)
    # print(output.size())

    loss = criterion(output[:,0,:].view(-1), labels_cuda)
    optimiser.zero_grad()
    loss.backward()                     # back propagation
    optimiser.step()                    # update the parameters

    if epoch % 20 == 0:
        rnn.eval()
        test_output, _ = rnn(X_test_cuda, hidden_state)
        test_loss = criterion(test_output.view(-1), y_test_cuda)
        print('epoch {}, loss {}, eval loss {}'.format(epoch, loss.item(), test_loss.item()))
    else:
        print('epoch {}, loss {}'.format(epoch, loss.item()))
    history.append(loss.item())
</code>```

I have so many questions that I don't understand about this code

some general questions:

how does this code work? which are the two layers?

what does the for loop do? how does it work?

some specific questions:

what does "super(RNN, self)._init_()" doing here

what does "self.num_directions = bidirection + 1"

```<code>r_out, hidden_state = self.rnn(x, h_state)
</code>```

does this code mean passing in the data after all the parameter has been passed in?

```<code>optimiser = torch.optim.Adam(rnn.parameters(), lr=learning_rate)
</code>```

is this the way of optimization for RNN?

can someone explain to me what is the whole IF part does in the for loop?

sorry for having so many questions. there aren't many people around me that could explain this to me, and I am also a beginner at this.

if you could help me with it I will be really appreciated it!

Title: build and run an RNN regression model

Body:
below is an example of an RNN regression model with two layers.

layer 1 uses an LSTM module with 5 hidden units.

layer 2 uses a fully connected module with one unit

class RNN(nn.Module):
    def __init__(self, i_size, h_size, n_layers, o_size, dropout=0.1, bidirectional=True):
        super(RNN, self).__init__()
        self.num_directions = bidirectional+1
        self.rnn = nn.LSTM(
            input_size=i_size,
            hidden_size=h_size,
            num_layers=n_layers,
            dropout=dropout,
            bidirectional=bidirectional
        )
        self.out = nn.Linear(h_size, o_size)

    def forward(self, x, h_state):
        r_out, hidden_state = self.rnn(x, h_state)

        hidden_size = hidden_state[-1].size(-1)
        r_out = r_out.view(-1, self.num_directions, hidden_size)
        outs = self.out(r_out)

        return outs, hidden_state

# Globals

INPUT_SIZE = 7
HIDDEN_SIZE = 64
NUM_LAYERS = 3
OUTPUT_SIZE = 1
BATCH_SIZE = 128
# Hyper parameters

learning_rate = 0.001
num_epochs = 300

rnn = RNN(INPUT_SIZE, HIDDEN_SIZE, NUM_LAYERS, OUTPUT_SIZE,bidirectional=False)
rnn.cuda()

optimiser = torch.optim.Adam(rnn.parameters(), lr=learning_rate)
criterion = nn.MSELoss()

hidden_state = None

history = []
X_test_cuda = torch.tensor(X_test).float().cuda()
y_test_cuda = torch.tensor(y_test).float().cuda()

# we use all the data in one batch
inputs_cuda = torch.tensor(X_train).float().cuda()
labels_cuda = torch.tensor(y_train).float().cuda()

for epoch in range(num_epochs):
    rnn.train()
    output, _ = rnn(inputs_cuda, hidden_state)
    # print(output.size())

    loss = criterion(output[:,0,:].view(-1), labels_cuda)
    optimiser.zero_grad()
    loss.backward()                     # back propagation
    optimiser.step()                    # update the parameters

    if epoch % 20 == 0:
        rnn.eval()
        test_output, _ = rnn(X_test_cuda, hidden_state)
        test_loss = criterion(test_output.view(-1), y_test_cuda)
        print('epoch {}, loss {}, eval loss {}'.format(epoch, loss.item(), test_loss.item()))
    else:
        print('epoch {}, loss {}'.format(epoch, loss.item()))
    history.append(loss.item())

I have so many questions that I don't understand about this code

some general questions:

how does this code work? which are the two layers?

what does the for loop do? how does it work?

some specific questions:

what does "super(RNN, self)._init_()" doing here

what does "self.num_directions = bidirection + 1"

r_out, hidden_state = self.rnn(x, h_state)

does this code mean passing in the data after all the parameter has been passed in?

optimiser = torch.optim.Adam(rnn.parameters(), lr=learning_rate)

is this the way of optimization for RNN?

can someone explain to me what is the whole IF part does in the for loop?

sorry for having so many questions. there aren't many people around me that could explain this to me, and I am also a beginner at this.

if you could help me with it I will be really appreciated it!


问:
Selecting a Typescript enums value with a string vs. a variable type string
I am confused as to why an enum's value can be selected with a variable assigned a string, but can not be selected with a variable that is typed as a string.

```<code>const selector = "VALUE"
const selectorWithType: string = "VALUE"

enum TestEnum {
    VALUE = "VALUE"
}

//this works
const test: TestEnum = TestEnum[selector]

//this does not work
const testWithType: TestEnum = TestEnum[selectorWithType]
</code>```

Playground Link

Is there a way to make this work? I am confused as to why this is even an issue, especially since test === testWithType resolved to true.

Body:
I am confused as to why an enum's value can be selected with a variable assigned a string, but can not be selected with a variable that is typed as a string.

const selector = "VALUE"
const selectorWithType: string = "VALUE"

enum TestEnum {
    VALUE = "VALUE"
}

//this works
const test: TestEnum = TestEnum[selector]

//this does not work
const testWithType: TestEnum = TestEnum[selectorWithType]

Playground Link

Is there a way to make this work? I am confused as to why this is even an issue, especially since test === testWithType resolved to true.


问:
How to override default font set by a CSS library (onsen-css-components.css in OnsenUI)?
The font for my H1 element in the following page structure is being overridden by OnsenUI CSS and I can't figure out why or how to override it successfully:

```<code><div class="page__content page--material__content">
    <div id="cmbcontent" class="source-serif-pro-font-light">
                 <h1 style="color: rgb(99, 81, 109);">My text here</h1>
</code>```

Onsen's CSS class page__content is defined as follows in their CSS:

```<code>.page__content h1 {
  font-family: 'Roboto', 'Noto', sans-serif;
  -webkit-font-smoothing: antialiased;
  font-weight: 400;
  margin: 0.6em 0;
  padding: 0;
}
</code>```

and page--material__content is the same:

```<code>.page--material__content h1 {
  font-family: 'Roboto', 'Noto', sans-serif;
  -webkit-font-smoothing: antialiased;
  font-weight: 400;
  margin: 0.6em 0;
  padding: 0;
}
</code>```

My index.css file includes the following rule for the font, and is included after onsen CSS in my HTML file.

```<code>.source-serif-pro-font-light {
    font-family: 'Source Serif Pro Light', serif;
    font-weight: 300;
    font-style: normal;
}
</code>```

In my code I use JQuery to set the font: $('#cmbcontent, #cmbcontent h1, #cmbcontent h3').addClass('source-serif-pro-font-light');
and I've confirmed by inspection that it's then set on those elements but it's being overridden by rules for ".page--material__content h1" and/or ".page__content h1" in onsen-css-components.css (I'm using the .min version)
Even doing $('#cmbcontent > h1').addClass('source-serif-pro-font-light'); or $('#cmbcontent > h1').css('font-family', "'Source Serif Pro Light', serif;"); doesn't work, and yet I think these should as my understanding is more specific CSS rules override less specific ones.

This is happening using OnsenUI 2.11.2 in Chrome (latest version) launched from Microsoft Cordova Tools in VSCode on Windows 10.

Any suggestions please?
Thanks

Body:
The font for my H1 element in the following page structure is being overridden by OnsenUI CSS and I can't figure out why or how to override it successfully:

My text here

Onsen's CSS class page__content is defined as follows in their CSS:

.page__content h1 {
  font-family: 'Roboto', 'Noto', sans-serif;
  -webkit-font-smoothing: antialiased;
  font-weight: 400;
  margin: 0.6em 0;
  padding: 0;
}

and page--material__content is the same:

.page--material__content h1 {
  font-family: 'Roboto', 'Noto', sans-serif;
  -webkit-font-smoothing: antialiased;
  font-weight: 400;
  margin: 0.6em 0;
  padding: 0;
}

My index.css file includes the following rule for the font, and is included after onsen CSS in my HTML file.

.source-serif-pro-font-light {
    font-family: 'Source Serif Pro Light', serif;
    font-weight: 300;
    font-style: normal;
}

In my code I use JQuery to set the font: $('#cmbcontent, #cmbcontent h1, #cmbcontent h3').addClass('source-serif-pro-font-light');
and I've confirmed by inspection that it's then set on those elements but it's being overridden by rules for ".page--material__content h1" and/or ".page__content h1" in onsen-css-components.css (I'm using the .min version)
Even doing $('#cmbcontent > h1').addClass('source-serif-pro-font-light'); or $('#cmbcontent > h1').css('font-family', "'Source Serif Pro Light', serif;"); doesn't work, and yet I think these should as my understanding is more specific CSS rules override less specific ones.

This is happening using OnsenUI 2.11.2 in Chrome (latest version) launched from Microsoft Cordova Tools in VSCode on Windows 10.

Any suggestions please?
Thanks


问:
Matter js: How to remove objects from a stack?
Matter.js....
Hi: I'm trying to remove some objects contained in a stack from the screen.
My code creates the objects, does everything it's supposed to, but I need to remove 'electrons' from the screen. After hours of research, study and guessing, I haven't been able to do it. I've spent most of my time trying to apply 'Composite.remove'.
Thank you for any help that you can provide...

relevant parts of my code:

```<code>
const leftEngine   = Engine.create()

const leftWorld   = leftEngine.world

const leftRender = Render.create({
  element: document.querySelector('#left'),
  engine: leftEngine,
  options:{
        wireframes: false,
        width: w*0.1,
        height: h*0.6,
        background: '#000'
    }
})

const createelectron1 = function(x, y) {
    return Bodies.circle(Math.random()*w*0.1, Math.random()*h, 2, {
    restitution: 1,
    friction: 0,
    frictionAir: 0,
    render: {
        fillStyle: "red",
        visible: true
      }
  });
}

const createatom1 = function(x, y) {
    return Bodies.circle(Math.random()*w*0.1, Math.random()*h, 5, {
    isStatic: true,
    restitution: 1,
    render: {
        fillStyle: "white",
        visible: true
    }
    });
  }

makeleftelectrons();
makeleftatoms();

function makeleftelectrons(){
    const initialShapes = Composites.stack(w*0.1, 0, electrondens, 20, 2, 4, function(x, y){
    return createelectron1(x, y)
})

}
function makeleftatoms(){
const initialShapes2 = Composites.stack(w*0.1, 0, 10, 10, 2, 4,  function(x, y){
  return createatom1(x, y)
})

const initialShapes = Composites.stack(w*0.1, 0, electrondens, 20, 2, 4, function(x, y){
  return createelectron1(x, y)
})

const initialShapes2 = Composites.stack(w*0.1, 0, 10, 10, 2, 4,  function(x, y){
  return createatom1(x, y)
})

const currentLeft = [
  initialShapes,
  initialShapes2,
  leftground,
  leftceiling
]

currentLeft.forEach(body =>{
  World.add(leftWorld, body)
})

Matter.Runner.run(leftEngine)

Render.run(leftRender)
const leftRunner = Matter.Runner.create()
Matter.Runner.run(leftRunner, leftEngine)

//additional code:

function removeCircle(removenum) {
    Composite.remove(initialShapes, bodies[removenum].id);
}

atomdensityslider.oninput = function() {
    electrondens = Number(atomdensityslider.value).valueOf();
    for (let removenum= 0; removenum < 1000; removenum++) {
        removeCircle(removenum);
    }
}
</code>```

Body:
Matter.js....
Hi: I'm trying to remove some objects contained in a stack from the screen.
My code creates the objects, does everything it's supposed to, but I need to remove 'electrons' from the screen. After hours of research, study and guessing, I haven't been able to do it. I've spent most of my time trying to apply 'Composite.remove'.
Thank you for any help that you can provide...

relevant parts of my code:

const leftEngine   = Engine.create()

const leftWorld   = leftEngine.world

const leftRender = Render.create({
  element: document.querySelector('#left'),
  engine: leftEngine,
  options:{
        wireframes: false,
        width: w*0.1,
        height: h*0.6,
        background: '#000'
    }
})

const createelectron1 = function(x, y) {
    return Bodies.circle(Math.random()*w*0.1, Math.random()*h, 2, {
    restitution: 1,
    friction: 0,
    frictionAir: 0,
    render: {
        fillStyle: "red",
        visible: true
      }
  });
}

const createatom1 = function(x, y) {
    return Bodies.circle(Math.random()*w*0.1, Math.random()*h, 5, {
    isStatic: true,
    restitution: 1,
    render: {
        fillStyle: "white",
        visible: true
    }
    });
  }

makeleftelectrons();
makeleftatoms();

function makeleftelectrons(){
    const initialShapes = Composites.stack(w*0.1, 0, electrondens, 20, 2, 4, function(x, y){
    return createelectron1(x, y)
})

}
function makeleftatoms(){
const initialShapes2 = Composites.stack(w*0.1, 0, 10, 10, 2, 4,  function(x, y){
  return createatom1(x, y)
})

const initialShapes = Composites.stack(w*0.1, 0, electrondens, 20, 2, 4, function(x, y){
  return createelectron1(x, y)
})

const initialShapes2 = Composites.stack(w*0.1, 0, 10, 10, 2, 4,  function(x, y){
  return createatom1(x, y)
})

const currentLeft = [
  initialShapes,
  initialShapes2,
  leftground,
  leftceiling
]

currentLeft.forEach(body =>{
  World.add(leftWorld, body)
})

Matter.Runner.run(leftEngine)

Render.run(leftRender)
const leftRunner = Matter.Runner.create()
Matter.Runner.run(leftRunner, leftEngine)

//additional code:

function removeCircle(removenum) {
    Composite.remove(initialShapes, bodies[removenum].id);
}

atomdensityslider.oninput = function() {
    electrondens = Number(atomdensityslider.value).valueOf();
    for (let removenum= 0; removenum < 1000; removenum++) {
        removeCircle(removenum);
    }
}