问:
Python IndexError in my Nearest Neighbour Algorithm for TSP
I am trying to solve TSP using the nearest algorithm, but I got stuck at the IndexError: boolean index did not match indexed array along dimension 0; dimension is 1 but corresponding boolean dimension is 38. For my algorithm I'm using a distance matrix 38x38 that was transformed from .tsp format.

```<code>import numpy as np
import tsplib95
import networkx

# load the tsplib problem
problem = tsplib95.load('dj38.tsp')

# convert into a networkx.Graph
graph = problem.get_graph()

# convert into a numpy distance matrix
distance_matrix = networkx.to_numpy_matrix(graph)

def NN(A, start):
    """Nearest neighbor algorithm.
    A is an NxN array indicating distance between N locations
    start is the index of the starting location
    Returns the path and cost of the found solution
    """
    path = [start]
    cost = 0
    n = A.shape[0]
    mask = np.ones(n, dtype=bool)  # boolean values indicating which locations have not been visited
    mask[start] = False

    for i in range(n-1):
        last = path[-1]
        next_ind = np.argmin(A[last][mask]) # find minimum of remaining locations
        next_loc = np.arange(n)[mask][next_ind] # convert to original location
        path.append(next_loc)
        mask[next_loc] = False
        cost += A[last, next_loc]

    return path, cost

#print(distance_matrix)

#print(distance_matrix.shape)

print(NN(distance_matrix,1))

</code>```

the distance matrix is 38x38 and looks like this

```<code>[[   0.  291.  794. ... 1852. 1625. 1858.]
 [ 291.    0.  513. ... 1599. 1413. 1649.]
 [ 794.  513.    0. ... 1331. 1288. 1514.]
 ...
 [1852. 1599. 1331. ...    0.  441.  444.]
 [1625. 1413. 1288. ...  441.    0.  236.]
 [1858. 1649. 1514. ...  444.  236.    0.]]
</code>```

and the error I'm getting is the following

```<code>Traceback (most recent call last):
  File "/Users/Irina/PycharmProjects/pythonProject/main.py", line 51, in <module>
    print(NN(distance_matrix,1))
          ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/Irina/PycharmProjects/pythonProject/main.py", line 36, in NN
    next_ind = np.argmin(A[last][mask]) # find minimum of remaining locations
                         ~~~~~~~^^^^^^
  File "/Users/Irina/PycharmProjects/pythonProject/venv/lib/python3.11/site-packages/numpy/matrixlib/defmatrix.py", line 193, in __getitem__
    out = N.ndarray.__getitem__(self, index)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
IndexError: boolean index did not match indexed array along dimension 0; dimension is 1 but corresponding boolean dimension is 38
</code>```

Any help will be much appreciated. Thanks.

Body:
I am trying to solve TSP using the nearest algorithm, but I got stuck at the IndexError: boolean index did not match indexed array along dimension 0; dimension is 1 but corresponding boolean dimension is 38. For my algorithm I'm using a distance matrix 38x38 that was transformed from .tsp format.

import numpy as np
import tsplib95
import networkx

# load the tsplib problem
problem = tsplib95.load('dj38.tsp')

# convert into a networkx.Graph
graph = problem.get_graph()

# convert into a numpy distance matrix
distance_matrix = networkx.to_numpy_matrix(graph)

def NN(A, start):
    """Nearest neighbor algorithm.
    A is an NxN array indicating distance between N locations
    start is the index of the starting location
    Returns the path and cost of the found solution
    """
    path = [start]
    cost = 0
    n = A.shape[0]
    mask = np.ones(n, dtype=bool)  # boolean values indicating which locations have not been visited
    mask[start] = False

    for i in range(n-1):
        last = path[-1]
        next_ind = np.argmin(A[last][mask]) # find minimum of remaining locations
        next_loc = np.arange(n)[mask][next_ind] # convert to original location
        path.append(next_loc)
        mask[next_loc] = False
        cost += A[last, next_loc]

    return path, cost

#print(distance_matrix)

#print(distance_matrix.shape)

print(NN(distance_matrix,1))

the distance matrix is 38x38 and looks like this

[[   0.  291.  794. ... 1852. 1625. 1858.]
 [ 291.    0.  513. ... 1599. 1413. 1649.]
 [ 794.  513.    0. ... 1331. 1288. 1514.]
 ...
 [1852. 1599. 1331. ...    0.  441.  444.]
 [1625. 1413. 1288. ...  441.    0.  236.]
 [1858. 1649. 1514. ...  444.  236.    0.]]

and the error I'm getting is the following

Traceback (most recent call last):
  File "/Users/Irina/PycharmProjects/pythonProject/main.py", line 51, in <module>
    print(NN(distance_matrix,1))
          ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/Irina/PycharmProjects/pythonProject/main.py", line 36, in NN
    next_ind = np.argmin(A[last][mask]) # find minimum of remaining locations
                         ~~~~~~~^^^^^^
  File "/Users/Irina/PycharmProjects/pythonProject/venv/lib/python3.11/site-packages/numpy/matrixlib/defmatrix.py", line 193, in __getitem__
    out = N.ndarray.__getitem__(self, index)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
IndexError: boolean index did not match indexed array along dimension 0; dimension is 1 but corresponding boolean dimension is 38

Any help will be much appreciated. Thanks.


来源: stackexchange

问:
Add idToken generated by identitytoolkit.googleapis.com api to firebase javascript web client
My platform sends out links to phone numbers; when a user opens the link I need to verify that the person opening the link has access to the phone number that received the link. I send the access code from my backend to the phone number that received the link. The client app then receives the access code, submits it to the back end, and receives an idToken and refreshToken in exchange. But I need help figuring out how to get this idToken generated by the identitytoolkit.googleapis.com API to the user on firebase web SDK so that the SDK can continue to manage token persistence for me.

I have tried adding the token using signInWithCustomToken, but it results in an "INVALID_CUSTOM_TOKEN" error.

ContentLicense: CC BY-SA 4.0


问:
Runtime error while installing stable-diffusion RuntimeError: Couldn't install requirements for Web UI
I'm jumping back into programming after a long time. Can someone help me with the error pasted below. I tried reinstalling everything and restarting but the below still seems to be happening. I also wasn't able to find any other posts about this error...

`

```<code>Creating venv in directory venv using python "C:\Users\jophy\AppData\Local\Programs\Python\Python310\python.exe"
venv "C:\Users\jophy\stable-diffusion-webui\venv\Scripts\Python.exe"
Python 3.10.0a6 (tags/v3.10.0a6:cc12888, Mar  1 2021, 18:17:49) [MSC v.1928 64 bit (AMD64)]
Commit hash: 4af3ca5393151d61363c30eef4965e694eeac15e
Installing torch and torchvision
Installing gfpgan
Installing clip
Installing open_clip
Cloning Stable Diffusion into repositories\stable-diffusion-stability-ai...
Cloning Taming Transformers into repositories\taming-transformers...
Cloning K-diffusion into repositories\k-diffusion...
Cloning CodeFormer into repositories\CodeFormer...
Cloning BLIP into repositories\BLIP...
Installing requirements for CodeFormer
Installing requirements for Web UI
Traceback (most recent call last):
  File "C:\Users\jophy\stable-diffusion-webui\launch.py", line 294, in <module>
    prepare_environment()
  File "C:\Users\jophy\stable-diffusion-webui\launch.py", line 246, in prepare_environment
    run_pip(f"install -r {requirements_file}", "requirements for Web UI")
  File "C:\Users\jophy\stable-diffusion-webui\launch.py", line 78, in run_pip
    return run(f'"{python}" -m pip {args} --prefer-binary{index_url_line}', desc=f"Installing {desc}", errdesc=f"Couldn't install {desc}")
  File "C:\Users\jophy\stable-diffusion-webui\launch.py", line 49, in run
    raise RuntimeError(message)
RuntimeError: Couldn't install requirements for Web UI.
Command: "C:\Users\jophy\stable-diffusion-webui\venv\Scripts\python.exe" -m pip install -r requirements_versions.txt --prefer-binary
Error code: 1
stdout: Collecting blendmodes==2022
  Downloading blendmodes-2022-py3-none-any.whl (10 kB)
Collecting transformers==4.19.2
  Downloading transformers-4.19.2-py3-none-any.whl (4.2 MB)
Collecting accelerate==0.12.0
  Downloading accelerate-0.12.0-py3-none-any.whl (143 kB)
Requirement already satisfied: basicsr==1.4.2 in c:\users\jophy\stable-diffusion-webui\venv\lib\site-packages (from -r requirements_versions.txt (line 4)) (1.4.2)
Collecting gfpgan==1.3.8
  Downloading gfpgan-1.3.8-py3-none-any.whl (52 kB)
Collecting gradio==3.9
  Downloading gradio-3.9-py3-none-any.whl (11.6 MB)
Collecting numpy==1.23.3
  Downloading numpy-1.23.3-cp310-cp310-win_amd64.whl (14.6 MB)
Collecting Pillow==9.2.0
  Downloading Pillow-9.2.0-cp310-cp310-win_amd64.whl (3.3 MB)
Collecting realesrgan==0.3.0
  Downloading realesrgan-0.3.0-py3-none-any.whl (26 kB)
Requirement already satisfied: torch in c:\users\jophy\stable-diffusion-webui\venv\lib\site-packages (from -r requirements_versions.txt (line 10)) (1.12.1+cu113)
Collecting omegaconf==2.2.3
  Downloading omegaconf-2.2.3-py3-none-any.whl (79 kB)
Collecting pytorch_lightning==1.7.6
  Downloading pytorch_lightning-1.7.6-py3-none-any.whl (707 kB)
Collecting scikit-image==0.19.2
  Downloading scikit_image-0.19.2-cp310-cp310-win_amd64.whl (12.6 MB)
Collecting fonts
  Downloading fonts-0.0.3-py3-none-any.whl (4.2 kB)
Collecting font-roboto
  Downloading font-roboto-0.0.1.tar.gz (2.4 MB)
Collecting timm==0.6.7
  Downloading timm-0.6.7-py3-none-any.whl (509 kB)
Collecting fairscale==0.4.9
  Downloading fairscale-0.4.9.tar.gz (265 kB)
  Installing build dependencies: started
  Installing build dependencies: finished with status 'done'
  Getting requirements to build wheel: started
  Getting requirements to build wheel: finished with status 'error'

stderr:   ERROR: Command errored out with exit status 1:
   command: 'C:\Users\jophy\stable-diffusion-webui\venv\Scripts\python.exe' 'C:\Users\jophy\stable-diffusion-webui\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py' get_requires_for_build_wheel 'C:\Users\jophy\AppData\Local\Temp\tmpcts1w9ak'
       cwd: C:\Users\jophy\AppData\Local\Temp\pip-install-2lg61b1i\fairscale_a091169903304caf89f292450b799084
  Complete output (25 lines):
  Traceback (most recent call last):
    File "C:\Users\jophy\stable-diffusion-webui\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 280, in <module>
      main()
    File "C:\Users\jophy\stable-diffusion-webui\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 263, in main
      json_out['return_val'] = hook(**hook_input['kwargs'])
    File "C:\Users\jophy\stable-diffusion-webui\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 114, in get_requires_for_build_wheel
      return hook(config_settings)
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\build_meta.py", line 338, in get_requires_for_build_wheel
      return self._get_build_requires(config_settings, requirements=['wheel'])
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\build_meta.py", line 320, in _get_build_requires
      self.run_setup()
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\build_meta.py", line 484, in run_setup
      super(_BuildMetaLegacyBackend,
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\build_meta.py", line 335, in run_setup
      exec(code, locals())
    File "<string>", line 57, in <module>
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\__init__.py", line 86, in setup
      _install_setup_requires(attrs)
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\__init__.py", line 75, in _install_setup_requires
      dist = MinimalDistribution(attrs)
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\__init__.py", line 57, in __init__
      super().__init__(filtered)
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\dist.py", line 473, in __init__
      for ep in metadata.entry_points(group='distutils.setup_keywords'):
  TypeError: entry_points() got an unexpected keyword argument 'group'
  ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/46/75/5469e7e401ef3181b536d5747036ed335c894f7414f97c13dca47ea6d9f7/fairscale-0.4.9.tar.gz#sha256=802145e14e38d4b32280eab2e56d14ef153f84296f7fe2ef0e91fd4eb3d65a28 (from https://pypi.org/simple/fairscale/) (requires-python:>=3.8). Command errored out with exit status 1: 'C:\Users\jophy\stable-diffusion-webui\venv\Scripts\python.exe' 'C:\Users\jophy\stable-diffusion-webui\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py' get_requires_for_build_wheel 'C:\Users\jophy\AppData\Local\Temp\tmpcts1w9ak' Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement fairscale==0.4.9
ERROR: No matching distribution found for fairscale==0.4.9
WARNING: You are using pip version 21.0.1; however, version 22.3.1 is available.
You should consider upgrading via the 'C:\Users\jophy\stable-diffusion-webui\venv\Scripts\python.exe -m pip install --upgrade pip' command.

Press any key to continue . . .
</code>```

`

I tried reinstalling everything but have not seen any progress past this point. any help would be appreciated!

Body:
I'm jumping back into programming after a long time. Can someone help me with the error pasted below. I tried reinstalling everything and restarting but the below still seems to be happening. I also wasn't able to find any other posts about this error...

`

Creating venv in directory venv using python "C:\Users\jophy\AppData\Local\Programs\Python\Python310\python.exe"
venv "C:\Users\jophy\stable-diffusion-webui\venv\Scripts\Python.exe"
Python 3.10.0a6 (tags/v3.10.0a6:cc12888, Mar  1 2021, 18:17:49) [MSC v.1928 64 bit (AMD64)]
Commit hash: 4af3ca5393151d61363c30eef4965e694eeac15e
Installing torch and torchvision
Installing gfpgan
Installing clip
Installing open_clip
Cloning Stable Diffusion into repositories\stable-diffusion-stability-ai...
Cloning Taming Transformers into repositories\taming-transformers...
Cloning K-diffusion into repositories\k-diffusion...
Cloning CodeFormer into repositories\CodeFormer...
Cloning BLIP into repositories\BLIP...
Installing requirements for CodeFormer
Installing requirements for Web UI
Traceback (most recent call last):
  File "C:\Users\jophy\stable-diffusion-webui\launch.py", line 294, in <module>
    prepare_environment()
  File "C:\Users\jophy\stable-diffusion-webui\launch.py", line 246, in prepare_environment
    run_pip(f"install -r {requirements_file}", "requirements for Web UI")
  File "C:\Users\jophy\stable-diffusion-webui\launch.py", line 78, in run_pip
    return run(f'"{python}" -m pip {args} --prefer-binary{index_url_line}', desc=f"Installing {desc}", errdesc=f"Couldn't install {desc}")
  File "C:\Users\jophy\stable-diffusion-webui\launch.py", line 49, in run
    raise RuntimeError(message)
RuntimeError: Couldn't install requirements for Web UI.
Command: "C:\Users\jophy\stable-diffusion-webui\venv\Scripts\python.exe" -m pip install -r requirements_versions.txt --prefer-binary
Error code: 1
stdout: Collecting blendmodes==2022
  Downloading blendmodes-2022-py3-none-any.whl (10 kB)
Collecting transformers==4.19.2
  Downloading transformers-4.19.2-py3-none-any.whl (4.2 MB)
Collecting accelerate==0.12.0
  Downloading accelerate-0.12.0-py3-none-any.whl (143 kB)
Requirement already satisfied: basicsr==1.4.2 in c:\users\jophy\stable-diffusion-webui\venv\lib\site-packages (from -r requirements_versions.txt (line 4)) (1.4.2)
Collecting gfpgan==1.3.8
  Downloading gfpgan-1.3.8-py3-none-any.whl (52 kB)
Collecting gradio==3.9
  Downloading gradio-3.9-py3-none-any.whl (11.6 MB)
Collecting numpy==1.23.3
  Downloading numpy-1.23.3-cp310-cp310-win_amd64.whl (14.6 MB)
Collecting Pillow==9.2.0
  Downloading Pillow-9.2.0-cp310-cp310-win_amd64.whl (3.3 MB)
Collecting realesrgan==0.3.0
  Downloading realesrgan-0.3.0-py3-none-any.whl (26 kB)
Requirement already satisfied: torch in c:\users\jophy\stable-diffusion-webui\venv\lib\site-packages (from -r requirements_versions.txt (line 10)) (1.12.1+cu113)
Collecting omegaconf==2.2.3
  Downloading omegaconf-2.2.3-py3-none-any.whl (79 kB)
Collecting pytorch_lightning==1.7.6
  Downloading pytorch_lightning-1.7.6-py3-none-any.whl (707 kB)
Collecting scikit-image==0.19.2
  Downloading scikit_image-0.19.2-cp310-cp310-win_amd64.whl (12.6 MB)
Collecting fonts
  Downloading fonts-0.0.3-py3-none-any.whl (4.2 kB)
Collecting font-roboto
  Downloading font-roboto-0.0.1.tar.gz (2.4 MB)
Collecting timm==0.6.7
  Downloading timm-0.6.7-py3-none-any.whl (509 kB)
Collecting fairscale==0.4.9
  Downloading fairscale-0.4.9.tar.gz (265 kB)
  Installing build dependencies: started
  Installing build dependencies: finished with status 'done'
  Getting requirements to build wheel: started
  Getting requirements to build wheel: finished with status 'error'

stderr:   ERROR: Command errored out with exit status 1:
   command: 'C:\Users\jophy\stable-diffusion-webui\venv\Scripts\python.exe' 'C:\Users\jophy\stable-diffusion-webui\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py' get_requires_for_build_wheel 'C:\Users\jophy\AppData\Local\Temp\tmpcts1w9ak'
       cwd: C:\Users\jophy\AppData\Local\Temp\pip-install-2lg61b1i\fairscale_a091169903304caf89f292450b799084
  Complete output (25 lines):
  Traceback (most recent call last):
    File "C:\Users\jophy\stable-diffusion-webui\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 280, in <module>
      main()
    File "C:\Users\jophy\stable-diffusion-webui\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 263, in main
      json_out['return_val'] = hook(**hook_input['kwargs'])
    File "C:\Users\jophy\stable-diffusion-webui\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py", line 114, in get_requires_for_build_wheel
      return hook(config_settings)
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\build_meta.py", line 338, in get_requires_for_build_wheel
      return self._get_build_requires(config_settings, requirements=['wheel'])
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\build_meta.py", line 320, in _get_build_requires
      self.run_setup()
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\build_meta.py", line 484, in run_setup
      super(_BuildMetaLegacyBackend,
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\build_meta.py", line 335, in run_setup
      exec(code, locals())
    File "<string>", line 57, in <module>
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\__init__.py", line 86, in setup
      _install_setup_requires(attrs)
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\__init__.py", line 75, in _install_setup_requires
      dist = MinimalDistribution(attrs)
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\__init__.py", line 57, in __init__
      super().__init__(filtered)
    File "C:\Users\jophy\AppData\Local\Temp\pip-build-env-13ap864h\overlay\Lib\site-packages\setuptools\dist.py", line 473, in __init__
      for ep in metadata.entry_points(group='distutils.setup_keywords'):
  TypeError: entry_points() got an unexpected keyword argument 'group'
  ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/46/75/5469e7e401ef3181b536d5747036ed335c894f7414f97c13dca47ea6d9f7/fairscale-0.4.9.tar.gz#sha256=802145e14e38d4b32280eab2e56d14ef153f84296f7fe2ef0e91fd4eb3d65a28 (from https://pypi.org/simple/fairscale/) (requires-python:>=3.8). Command errored out with exit status 1: 'C:\Users\jophy\stable-diffusion-webui\venv\Scripts\python.exe' 'C:\Users\jophy\stable-diffusion-webui\venv\lib\site-packages\pip\_vendor\pep517\_in_process.py' get_requires_for_build_wheel 'C:\Users\jophy\AppData\Local\Temp\tmpcts1w9ak' Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement fairscale==0.4.9
ERROR: No matching distribution found for fairscale==0.4.9
WARNING: You are using pip version 21.0.1; however, version 22.3.1 is available.
You should consider upgrading via the 'C:\Users\jophy\stable-diffusion-webui\venv\Scripts\python.exe -m pip install --upgrade pip' command.

Press any key to continue . . .

`

I tried reinstalling everything but have not seen any progress past this point. any help would be appreciated!


问:
Consuming a message sent by OneSignal
I have vue js application and i am consuming messages sent from a php script like this

```<code>     document.addEventListener("deviceready", OneSignalInit, false);
      function OneSignalInit() {
        // Uncomment to set OneSignal device logging to VERBOSE
        // window.plugins.OneSignal.setLogLevel(6, 0);

        // NOTE: Update the setAppId value below with your OneSignal AppId.
        window["plugins"].OneSignal.setAppId("");
        window["plugins"].OneSignal.setNotificationOpenedHandler(function(jsonData) {
            console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
        });

        // iOS - Prompts the user for notification permissions.
        //    * Since this shows a generic native prompt, we recommend instead using an In-App Message to prompt for notification permission (See step 6) to better communicate to your users what notifications they will get.

window["plugins"].OneSignal.setNotificationReceivedHandler(function(jsonData) {
        this.$router.push({path: '/my_ads'});
    });

window["plugins"].OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
            console.log("User accepted notifications: " + accepted);
        });
      }
</code>```

In my code above, this gives me a notification that shows on android. I would like to send a message that do not require a notification prompt but i would like to consume the message sent inside my application i.e use the message sent and do something with it i.e go to another route

this.$router.push({path: '/another_route'});

How can i do that?

Title: Consuming a message sent by OneSignal

Body:
I have vue js application and i am consuming messages sent from a php script like this

     document.addEventListener("deviceready", OneSignalInit, false);
      function OneSignalInit() {
        // Uncomment to set OneSignal device logging to VERBOSE
        // window.plugins.OneSignal.setLogLevel(6, 0);

        // NOTE: Update the setAppId value below with your OneSignal AppId.
        window["plugins"].OneSignal.setAppId("");
        window["plugins"].OneSignal.setNotificationOpenedHandler(function(jsonData) {
            console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
        });

        // iOS - Prompts the user for notification permissions.
        //    * Since this shows a generic native prompt, we recommend instead using an In-App Message to prompt for notification permission (See step 6) to better communicate to your users what notifications they will get.

window["plugins"].OneSignal.setNotificationReceivedHandler(function(jsonData) {
        this.$router.push({path: '/my_ads'});
    });

window["plugins"].OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
            console.log("User accepted notifications: " + accepted);
        });
      }

In my code above, this gives me a notification that shows on android. I would like to send a message that do not require a notification prompt but i would like to consume the message sent inside my application i.e use the message sent and do something with it i.e go to another route

this.$router.push({path: '/another_route'});

How can i do that?


问:
Java script google api to get authorization code
I done this code using tutorial but it does not work, it simply does open pop-up to enter your credentials for google. What is wrong with this code?</p>
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="sign-in-button">Sign in</button>
    <script src="https://apis.google.com/js/api.js"></script>
    <script>
        gapi.auth2.init({
            client_id: "655720894976-2rkkoov9efteqna8hq3vbc632brur2jf.apps.googleusercontent.com"
        });
        document.getElementById("sign-in-button").addEventListener("click", function() {
            // Get an authorization code
            gapi.auth2.getAuthInstance().grantOfflineAccess({
                scope: "https://www.googleapis.com/auth/cloud-platform"
            }).then(function(response) {
                var authorizationCode = response.code;
            });
        });
    </script>
</body>
</html>
</code>```

Body:
I done this code using tutorial but it does not work, it simply does open pop-up to enter your credentials for google. What is wrong with this code?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <button id="sign-in-button">Sign in</button>


问:
Enable AWS lambda Python to Connect to MySQL via SSH Tunnelling
This is the first time I am trying to connect to database (WP in this case) via SSH with lambda function.  I can connect to this DB via SSH from client(mySQL Workbench).  From other posts it looks like SSHTunnel is a good option to use in lambda function.

I created a package installing sshtunnel, created layer, and attached layer to function.  Used post from Gabe Olokun (https://www.linkedin.com/pulse/add-external-python-libraries-aws-lambda-using-layers-gabe-olokun) that has worked successfully for other packages.

When I run a basic function, I get the following error:
"Unable to import module 'lambda_function': No module named '_cffi_backend'"

I have two import statements.  pymysql works with no issues.  I followed same process to create that package, create layer and attach.

```<code>import pymysql.cursors
from sshtunnel import SSHTunnelForwarder
</code>```

Using Python 3.9

I have searched and come up with nothing.  Appreciate any help.  #rookie :)

Body:
This is the first time I am trying to connect to database (WP in this case) via SSH with lambda function.  I can connect to this DB via SSH from client(mySQL Workbench).  From other posts it looks like SSHTunnel is a good option to use in lambda function.

I created a package installing sshtunnel, created layer, and attached layer to function.  Used post from Gabe Olokun (https://www.linkedin.com/pulse/add-external-python-libraries-aws-lambda-using-layers-gabe-olokun) that has worked successfully for other packages.

When I run a basic function, I get the following error:
"Unable to import module 'lambda_function': No module named '_cffi_backend'"

I have two import statements.  pymysql works with no issues.  I followed same process to create that package, create layer and attach.

import pymysql.cursors
from sshtunnel import SSHTunnelForwarder

Using Python 3.9

I have searched and come up with nothing.  Appreciate any help.  #rookie :)


问:
Range slider getting stuck when using buttons/keydowns to move it
I have this range slider that is having some issues, I want the step of the slider to be 1 until it is over 36, in which I then want the step to be 3. It seems to be working okay besides during some cases. If a user was to click on the slider to make it move, and then use the previous or next buttons to move the slider afterward, the slider gets stuck at 33 and does not move if you use the buttons.

The next issue I am encountering is when using the slider, if you were to click on the slider to move it and then use the keydown functions I added using > or < on your keyboard, the step will double for some reason, being 2 below 36 and 6 above 36? Any help would be appreciated.

        function updateImage(sliderValue) {

          // Get the image and arrow button elements
          const backwardArrow = document.querySelector('.backward-arrow');
          const forwardArrow = document.querySelector('.forward-arrow');
        }
    var regionSubstring = 'neus'
    var finalSubstring = '2mtemp'
    var finalSubstringModel = 'nam12k'
                  // Get the buttons and range slider elements
          var prevButton = document.getElementById('prev-button');
          var nextButton = document.getElementById('next-button');
          var rangeSlider = document.getElementById('range-slider');
            var step = rangeSlider.step;
            var sliderValue = rangeSlider.value
          // Add event listeners to the buttons
            rangeSlider.addEventListener("input", function() {
            if (finalSubstringModel.includes("nam12k")) {
        // If the value of the slider is greater than 36, set the step size to 3
        if (rangeSlider.value >= 36) {
          var step = 3;
        } else {
          var step = 1;
        }
        // Update the step attribute of the slider
           rangeSlider.setAttribute("step", step);
            console.log(rangeSlider.value);
        }});
              // Add event listeners to the buttons
            if (finalSubstringModel.includes("gfs")) {
        // If the value of the slider is greater than 36, set the step size to 3
          var step = 6;
        // Update the step attribute of the slider
           rangeSlider.setAttribute("step", step);
        };
          prevButton.addEventListener('click', function() {
                          if (finalSubstringModel.includes("nam12k")) {
        // If the value of the slider is greater than 36, set the step size to 3
        if (rangeSlider.value >= 36) {
          var step = 3;
        } else {
          var step = 1;
        }
              event.preventDefault();
            // Decrement the value of the range slider by the step value
            rangeSlider.value -= step;
          updateImage(rangeSlider.value)

          }});
            rangeSlider.addEventListener('input', function() {

        });

          nextButton.addEventListener('click', function() {
                          if (finalSubstringModel.includes("nam12k")) {
        // If the value of the slider is greater than 36, set the step size to 3
        if (rangeSlider.value >= 36) {
          var step = 3;
        } else {
          var step = 1;
        }
              event.preventDefault();
            // Increment the value of the range slider by the step value
            val = parseInt(rangeSlider.value);
            val += step;
            rangeSlider.value = val;
            updateImage(rangeSlider.value);

          }});

            document.addEventListener('keydown', function(e) {

                            if (finalSubstringModel.includes("nam12k")) {
        // If the value of the slider is greater than 36, set the step size to 3
        if (rangeSlider.value >= 36) {

          var step = 3;
        } else {
          var step = 1;
        }

          if (e.keyCode == 39) { //right
            val = parseInt(rangeSlider.value);
            val += step;
            rangeSlider.value = val;
              console.log(val)

              // console.log(step)
          } else if (e.keyCode == 37) { //left
            val = parseInt(rangeSlider.value);
            val -= step;
            rangeSlider.value = val;
              console.log(val)

          }
          updateImage(rangeSlider.value)
        }})```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <input type='range' min='0' max='84' value='0' step='1'  oninput='updateImage(this.value)' id='range-slider' class='slider'/>
        <div>
    <button id='prev-button' class='prev'>Prev</button>
<button id='next-button' class='next'>Next</button></code>```

Body:
I have this range slider that is having some issues, I want the step of the slider to be 1 until it is over 36, in which I then want the step to be 3. It seems to be working okay besides during some cases. If a user was to click on the slider to make it move, and then use the previous or next buttons to move the slider afterward, the slider gets stuck at 33 and does not move if you use the buttons.

The next issue I am encountering is when using the slider, if you were to click on the slider to move it and then use the keydown functions I added using > or < on your keyboard, the step will double for some reason, being 2 below 36 and 6 above 36? Any help would be appreciated.

        function updateImage(sliderValue) {

          // Get the image and arrow button elements
          const backwardArrow = document.querySelector('.backward-arrow');
          const forwardArrow = document.querySelector('.forward-arrow');
        }
    var regionSubstring = 'neus'
    var finalSubstring = '2mtemp'
    var finalSubstringModel = 'nam12k'
                  // Get the buttons and range slider elements
          var prevButton = document.getElementById('prev-button');
          var nextButton = document.getElementById('next-button');
          var rangeSlider = document.getElementById('range-slider');
            var step = rangeSlider.step;
            var sliderValue = rangeSlider.value
          // Add event listeners to the buttons
            rangeSlider.addEventListener("input", function() {
            if (finalSubstringModel.includes("nam12k")) {
        // If the value of the slider is greater than 36, set the step size to 3
        if (rangeSlider.value >= 36) {
          var step = 3;
        } else {
          var step = 1;
        }
        // Update the step attribute of the slider
           rangeSlider.setAttribute("step", step);
            console.log(rangeSlider.value);
        }});
              // Add event listeners to the buttons
            if (finalSubstringModel.includes("gfs")) {
        // If the value of the slider is greater than 36, set the step size to 3
          var step = 6;
        // Update the step attribute of the slider
           rangeSlider.setAttribute("step", step);
        };
          prevButton.addEventListener('click', function() {
                          if (finalSubstringModel.includes("nam12k")) {
        // If the value of the slider is greater than 36, set the step size to 3
        if (rangeSlider.value >= 36) {
          var step = 3;
        } else {
          var step = 1;
        }
              event.preventDefault();
            // Decrement the value of the range slider by the step value
            rangeSlider.value -= step;
          updateImage(rangeSlider.value)

          }});
            rangeSlider.addEventListener('input', function() {

        });

          nextButton.addEventListener('click', function() {
                          if (finalSubstringModel.includes("nam12k")) {
        // If the value of the slider is greater than 36, set the step size to 3
        if (rangeSlider.value >= 36) {
          var step = 3;
        } else {
          var step = 1;
        }
              event.preventDefault();
            // Increment the value of the range slider by the step value
            val = parseInt(rangeSlider.value);
            val += step;
            rangeSlider.value = val;
            updateImage(rangeSlider.value);

          }});

            document.addEventListener('keydown', function(e) {

                            if (finalSubstringModel.includes("nam12k")) {
        // If the value of the slider is greater than 36, set the step size to 3
        if (rangeSlider.value >= 36) {

          var step = 3;
        } else {
          var step = 1;
        }

          if (e.keyCode == 39) { //right
            val = parseInt(rangeSlider.value);
            val += step;
            rangeSlider.value = val;
              console.log(val)

              // console.log(step)
          } else if (e.keyCode == 37) { //left
            val = parseInt(rangeSlider.value);
            val -= step;
            rangeSlider.value = val;
              console.log(val)

          }
          updateImage(rangeSlider.value)
        }})

        <input type='range' min='0' max='84' value='0' step='1'  oninput='updateImage(this.value)' id='range-slider' class='slider'/>

    <button id='prev-button' class='prev'>Prev</button>
<button id='next-button' class='next'>Next</button>


问:
How can I avoid creating a new session when a user enters the same url and instead lets the new user join the host session?
I am trying to make an application which lets the first person to enter the url navigate to his specific hostId. The next person who comes to the same url is supposed to join the "hosts" session. This works, but it simultaneously creates a new session with the new user while also pushing the user to the hosts session. I do think it has something to do with the code where I am saying: "If (!host) { socket.emit("host:joined") }." And since the second user's host is "null" at the first render it also calls for emit("host:joined"), instead of only the "socket.emit("user:joined") (which is in the StartPage component).

How can the second user ONLY join the host session, without creating a new session?

```<code>    const socket = socketio.connect(import.meta.env.VITE_APP_SOCKET_URL)

    function App() {
      const [host, setHost] = useState(null)
      const [loading, setLoading] = useState(true)
      const [showModal, setShowModal] = useState(false)
      const [queueList, setQueueList] = useState([])

    useEffect(() => {
        if (!host) {
          socket.emit("host:joined")
        }

    console.log("socket.id", socket.id)
    socket.on("host:joined", (hostId) => {
      setHost(hostId)
      setLoading(false)
    })
    socket.on("user:joined", (id) => {
      console.log("user joined session:", id)
    })
    socket.on("playlist", (data) => {
      setQueueList(data)
    })

    if (host === undefined) {
      socket.emit("disconnect")
    }

    console.log("HOST", host)
    return () => {
      console.log("Cleaning up")
      socket.off("host:joined")
      socket.off("disconnect")
      socket.off("playlist")
    }

    }, [host, queueList])

    return (
        <div className="App">
          {loading && <LoadingSpinner />}

      <Routes>
        <Route
          path="/:id"
          element={
            <StartPage
              socket={socket}
              host={host}
              queueList={queueList}
              setShowModal={setShowModal}
              showModal={showModal}
            />
          }
        />
        {host && <Route path="/" element={<Navigate to={`/${host}`} />} />}
      </Routes>
    </div>
  )
}

    export default App
</code>```

Startpage component:

```<code>const StartPage = ({ socket, host, queueList, setShowModal, showModal }) => {
  const { id } = useParams()
  useEffect(() => {
    if (id !== socket.id) {
      socket.emit("user:joined", id)
    }
  }, [id])
  return (
    <>
    </>
  )
}

export default StartPage
</code>```

Socket_controller:

```<code>let io = null

let sessions = []

// Create a session when host enters the site
const handleConnect = function (id) {
  console.log("ID", id)
  if (!id) {
    console.log("Host joined with id:", this.id)
    let session = {
      id: this.id,
      playlist: [],
      users: [],
    }

    if (sessions.find((session) => session.id === this.id)) {
      return
    } else {
      sessions.push(session)
      this.join(session)
    }
    io.to(session).emit("host:joined", this.id)
  } else {
    console.log("User joined with id:", this.id)

    const session = sessions.find((session) => session.id === id)
    console.log("session", session)
    session.users.push(this.id)
    this.join(session)
    io.to(session).emit("host:joined", id)
    console.log("sessions", sessions)
  }
}

/**
 * Export controller and attach handlers to events
 */
module.exports = function (socket, _io) {
  io = _io

  // handle host connect
  socket.on("host:joined", handleConnect)

  socket.on("user:joined", handleConnect)
}
</code>```

Backend and frontend consoles:

I have tried many different things, such as using a loadingspinner while host i loading. I've tried refactoring both in the controller and on the frontend. The positive thing is that it works as intended visually, which means that the two users are on the same session and can share information. However, I can see in the code that it is not corrent as new sessions are created, and also the second user is joining twice.

Body:
I am trying to make an application which lets the first person to enter the url navigate to his specific hostId. The next person who comes to the same url is supposed to join the "hosts" session. This works, but it simultaneously creates a new session with the new user while also pushing the user to the hosts session. I do think it has something to do with the code where I am saying: "If (!host) { socket.emit("host:joined") }." And since the second user's host is "null" at the first render it also calls for emit("host:joined"), instead of only the "socket.emit("user:joined") (which is in the StartPage component).

How can the second user ONLY join the host session, without creating a new session?

    const socket = socketio.connect(import.meta.env.VITE_APP_SOCKET_URL)

    function App() {
      const [host, setHost] = useState(null)
      const [loading, setLoading] = useState(true)
      const [showModal, setShowModal] = useState(false)
      const [queueList, setQueueList] = useState([])

    useEffect(() => {
        if (!host) {
          socket.emit("host:joined")
        }

    console.log("socket.id", socket.id)
    socket.on("host:joined", (hostId) => {
      setHost(hostId)
      setLoading(false)
    })
    socket.on("user:joined", (id) => {
      console.log("user joined session:", id)
    })
    socket.on("playlist", (data) => {
      setQueueList(data)
    })

    if (host === undefined) {
      socket.emit("disconnect")
    }

    console.log("HOST", host)
    return () => {
      console.log("Cleaning up")
      socket.off("host:joined")
      socket.off("disconnect")
      socket.off("playlist")
    }

    }, [host, queueList])

    return (

          {loading && <LoadingSpinner />}

      <Routes>
        <Route
          path="/:id"
          element={
            <StartPage
              socket={socket}
              host={host}
              queueList={queueList}
              setShowModal={setShowModal}
              showModal={showModal}
            />
          }
        />
        {host && <Route path="/" element={<Navigate to={`/${host}`} />} />}
      </Routes>

  )
}

    export default App

Startpage component:

const StartPage = ({ socket, host, queueList, setShowModal, showModal }) => {
  const { id } = useParams()
  useEffect(() => {
    if (id !== socket.id) {
      socket.emit("user:joined", id)
    }
  }, [id])
  return (
    <>
    </>
  )
}

export default StartPage

Socket_controller:

let io = null

let sessions = []

// Create a session when host enters the site
const handleConnect = function (id) {
  console.log("ID", id)
  if (!id) {
    console.log("Host joined with id:", this.id)
    let session = {
      id: this.id,
      playlist: [],
      users: [],
    }

    if (sessions.find((session) => session.id === this.id)) {
      return
    } else {
      sessions.push(session)
      this.join(session)
    }
    io.to(session).emit("host:joined", this.id)
  } else {
    console.log("User joined with id:", this.id)

    const session = sessions.find((session) => session.id === id)
    console.log("session", session)
    session.users.push(this.id)
    this.join(session)
    io.to(session).emit("host:joined", id)
    console.log("sessions", sessions)
  }
}

/**
 * Export controller and attach handlers to events
 */
module.exports = function (socket, _io) {
  io = _io

  // handle host connect
  socket.on("host:joined", handleConnect)

  socket.on("user:joined", handleConnect)
}

Backend and frontend consoles:

I have tried many different things, such as using a loadingspinner while host i loading. I've tried refactoring both in the controller and on the frontend. The positive thing is that it works as intended visually, which means that the two users are on the same session and can share information. However, I can see in the code that it is not corrent as new sessions are created, and also the second user is joining twice.


问:
Unable to import pdfkit Python 3.9
Running Python3.9 on a Ubuntu Linux Box and properly went through the step installing pdfkit:

pip3 install pdfkit

sudo apt install wkhtmltopdf

Error says :

```<code>Traceback (most recent call last):
  File "/home/shawn/Development/Websites/MDSova/restapi/app.py", line 8, in <module>
    from messaging import Mailbox
  File "/home/shawn/Development/Websites/MDSova/restapi/messaging.py", line 8, in <module>
    import pdfkit
ModuleNotFoundError: No module named 'pdfkit'
</code>```

The app was run inside an active environment.

I've read many responses to a similar question; however I have not run across a way to fix it.  Does anyone have any suggestions?

Title: Unable to import pdfkit Python 3.9

Body:
Running Python3.9 on a Ubuntu Linux Box and properly went through the step installing pdfkit:

pip3 install pdfkit

sudo apt install wkhtmltopdf

Error says :

Traceback (most recent call last):
  File "/home/shawn/Development/Websites/MDSova/restapi/app.py", line 8, in <module>
    from messaging import Mailbox
  File "/home/shawn/Development/Websites/MDSova/restapi/messaging.py", line 8, in <module>
    import pdfkit
ModuleNotFoundError: No module named 'pdfkit'

The app was run inside an active environment.

I've read many responses to a similar question; however I have not run across a way to fix it.  Does anyone have any suggestions?


问:
jquery Datatable column data on export shows only half text when there is a long text
Iam new JS and jquery datatable . I have implemented a datatable and implemented paginations buttons to export in excel,csv,pdf,print.

I have columns in my table which I want to style a certain way , when there is a long text , it should only be showing starting of string and rest should be hidden, the text is enclosed(styled) to look like separate items [can have more than one item].

When I implement it that way , when I export my table only the text visible in table is exported(which is the starting), not the whole data coming in. Iknow this is a simple issue , but Iam very new and Iam not able to figure it out. Help would be much appreciated.[enter image description here](https://i.stack.imgur.com/q5WJ1.png)

This is my code for one of the columns in datatable.

{
    title: "Capability",
    data: 'Capabilities',
    render: function (data, type, row, meta) {

        let strHTML = '';
        let wordWrap = '';

        for (let i = 0; i < row.Capabilities.length; i++)
          if (row.Capabilities[i].length > 10) {
              wordWrap = '...';
          }
          else {
              wordWrap = '';
          }
        strHTML += '' + row.Capabilities[i].Name.substr(0, 50) + wordWrap + ''
    }

    return strHTML;
}
```


问:
puppeteer-extra-plugin-recaptcha Add New Provider
I've been searching for a way to use puppeteer-extra-plugin-recaptcha with other providers but so far I've only found one repository for capmonster : puppeteer-extra-plugin-recaptcha-capmonster but haven't come across any other provider nor even the way to make a provider, they say they've gone into detail about in API docs but I couldn't find any more details about how to make a custom provider. Any help would be really appreciated.


问:
Accessing truedepth camera on Browser
Is there any way of accessing truedepth camera of iPhones on the browser and using it?

I have checked webkitjs documentation, but they don't have anything related to this

Title: Accessing truedepth camera on Browser


问:
How to get boolean value in firebase realtime database?
I have a realtime database that im using in flutter.
I assign the firebase authentication key as the key for each user.
this is a snapshot of the database

```<code>"user": {
    "uFkR1Z1UoVTVUmbpDmgU7BXGT852": {
      "admin": true,
      "email": "****",
      "fullName": "ziad212",
      "phoneNo": "011111111"
    }
  }
</code>```

I need to get the boolean value in admin node.

I have tried the following but it always give me false and the value does not change.
(User.isAdmin is a static bool value for the current session)

```<code>static isAdmin()async{
  if(AuthenticationRepository.auth.currentUser?.uid !=null){

  var currentId = AuthenticationRepository.auth.currentUser!.uid;
  final  snapshot =await database.ref('user/$currentId/admin').get();

  User.isAdmin =snapshot.value as bool;

  }
}
</code>```

I have also tried Querying the whole user into a map and trying to access the value admin but still the same result
what am i doing wrong?
Thanks in advance

Body:
I have a realtime database that im using in flutter.
I assign the firebase authentication key as the key for each user.
this is a snapshot of the database

"user": {
    "uFkR1Z1UoVTVUmbpDmgU7BXGT852": {
      "admin": true,
      "email": "****",
      "fullName": "ziad212",
      "phoneNo": "011111111"
    }
  }

I need to get the boolean value in admin node.

I have tried the following but it always give me false and the value does not change.
(User.isAdmin is a static bool value for the current session)

static isAdmin()async{
  if(AuthenticationRepository.auth.currentUser?.uid !=null){

  var currentId = AuthenticationRepository.auth.currentUser!.uid;
  final  snapshot =await database.ref('user/$currentId/admin').get();

  User.isAdmin =snapshot.value as bool;

  }
}

I have also tried Querying the whole user into a map and trying to access the value admin but still the same result
what am i doing wrong?
Thanks in advance


问:
Live agent support for a chat bot in python in Flask app
Please help with how to add Live agent support for a chat bot written in python by Flask app (webhook in meta developer):
so if the user of the bot choose to chat with a real person - the webhook flask app will transfer the chat to an agent.
I want to do it without services of 3rd party company. I want to do it using some python imports.
Do you have an example for a solution?

Thank you

I tried finding solutions but failed.


问:
Flutter Socket disconnects when app is in background
Socket id is disconnecting while app is in background

Used the socket.disconnect() function and try to reconnect but fails


问:
Can an extension dynamically change Gnome Shell Styles?
I'm working on a simple extension to color the Top Panel using a color specified in a local config file. I know that you can override Gnome Shell Styles by adding rules to stylesheet.css, however this seems to be for rules that are statically known and not determined at runtime. I would like to override the Shell's #panel background style with the color that extension.js reads from a file, is this possible in Gnome JavaScript?


问:
Rstudio Crashes after I close the shiny app (using "pool" package)
I basically have an shiny app like in this example:

```<code>library(shiny)
library(DBI)
library(pool)

# create the connection
pool <- dbPool(
  drv = RMySQL::MySQL(),
  dbname = "shinydemo",
  host = "shiny-demo.csa7qlmguqrf.us-east-1.rds.amazonaws.com",
  username = "guest",
  password = "guest"
)
onStop(function() {
  message("closing...")
  pool::poolClose(pool)
})

# === UI ====
ui <- fluidPage(
  textInput("ID", "Enter your ID:", "5"),
  tableOutput("tbl"),
  numericInput("nrows", "How many cities to show?", 10),
  plotOutput("popPlot")
)

#==== SERVER ====
server <- function(input, output, session) {
  output$tbl <- renderTable({
    sql <- "SELECT * FROM City WHERE ID = ?id;"
    query <- sqlInterpolate(pool, sql, id = input$ID)
    dbGetQuery(pool, query)
  })
  output$popPlot <- renderPlot({
    query <- paste0("SELECT * FROM City LIMIT ",
                    as.integer(input$nrows)[1], ";")
    df <- dbGetQuery(pool, query)
    pop <- df$Population
    names(pop) <- df$Name
    barplot(pop)
  })
}

#=== Run the App====
shinyApp(ui, server)

</code>```

And the error has been already asked in this post years ago, but the answer does not solve the issue on my side. (they suggest to get the latest "later" package, but I did and the error remains).
So the error is that: once I click on the Stop bottom on my RStudio Server Session (to stop the shiny App dashboard that runs fine) it does not stop. Instead, a window pop-out appears saying: Terminate R (And no message error appears in the console)

I tried for hours to solve this annoyin behaviour (it makes me recall the system environment variables everytime I restart the Rstudio session) and I found a temporal solution: pressing "Esc" button on the "Console", to Stop the process, avoiding that "Terminate R" pop-out. Then it really stops and I can rerun again the Shiny app. I want to remark that the "Stop" icon (see circle in red, on the attached picture)does not work properly. The "Esc" works instead.
Anybody knows why is this happening? I will also report it in GitHub "pool" issues. Although I am not completely sure if the issue is from the package.

I am using R.4.1.0 (also my connection is to Postgress using a odbc driver, but is not displayed in the code. My session is running in RStudio Workbench 2021.092 (Build 382.pro1). I am ussing "pool" v.0.1.6.

Body:
I basically have an shiny app like in this example:

library(shiny)
library(DBI)
library(pool)

# create the connection
pool <- dbPool(
  drv = RMySQL::MySQL(),
  dbname = "shinydemo",
  host = "shiny-demo.csa7qlmguqrf.us-east-1.rds.amazonaws.com",
  username = "guest",
  password = "guest"
)
onStop(function() {
  message("closing...")
  pool::poolClose(pool)
})

# === UI ====
ui <- fluidPage(
  textInput("ID", "Enter your ID:", "5"),
  tableOutput("tbl"),
  numericInput("nrows", "How many cities to show?", 10),
  plotOutput("popPlot")
)

#==== SERVER ====
server <- function(input, output, session) {
  output$tbl <- renderTable({
    sql <- "SELECT * FROM City WHERE ID = ?id;"
    query <- sqlInterpolate(pool, sql, id = input$ID)
    dbGetQuery(pool, query)
  })
  output$popPlot <- renderPlot({
    query <- paste0("SELECT * FROM City LIMIT ",
                    as.integer(input$nrows)[1], ";")
    df <- dbGetQuery(pool, query)
    pop <- df$Population
    names(pop) <- df$Name
    barplot(pop)
  })
}

#=== Run the App====
shinyApp(ui, server)

And the error has been already asked in this post years ago, but the answer does not solve the issue on my side. (they suggest to get the latest "later" package, but I did and the error remains).
So the error is that: once I click on the Stop bottom on my RStudio Server Session (to stop the shiny App dashboard that runs fine) it does not stop. Instead, a window pop-out appears saying: Terminate R (And no message error appears in the console)

I tried for hours to solve this annoyin behaviour (it makes me recall the system environment variables everytime I restart the Rstudio session) and I found a temporal solution: pressing "Esc" button on the "Console", to Stop the process, avoiding that "Terminate R" pop-out. Then it really stops and I can rerun again the Shiny app. I want to remark that the "Stop" icon (see circle in red, on the attached picture)does not work properly. The "Esc" works instead.
Anybody knows why is this happening? I will also report it in GitHub "pool" issues. Although I am not completely sure if the issue is from the package.

I am using R.4.1.0 (also my connection is to Postgress using a odbc driver, but is not displayed in the code. My session is running in RStudio Workbench 2021.092 (Build 382.pro1). I am ussing "pool" v.0.1.6.


问:
Label Studio ML Backend version conflict with Label Studio itself
Following the Label Studio documentation (e.g. https://labelstud.io/tutorials/dummy_model.html), you require both label-studio and label-studio installed. When I try to install these in the same environment, I always end up with version conflicts. I tried various versions manually.

```<code>$ poetry add label-studio-ml
$ poetry add label-studio

Because no versions of label-studio match >1.7.0,<2.0.0
 and label-studio (1.7.0) depends on label-studio-converter (0.0.48rc0), label-studio (>=1.7.0,<2.0.0) requires label-studio-converter (0.0.48rc0).
And because label-studio-converter (0.0.48rc0) depends on label-studio-tools (0.0.1), label-studio (>=1.7.0,<2.0.0) requires label-studio-tools (0.0.1).
And because label-studio-ml (1.0.8) depends on label-studio-tools (0.0.0.dev11)
 and no versions of label-studio-ml match >1.0.8,<2.0.0, label-studio (>=1.7.0,<2.0.0) is incompatible with label-studio-ml (>=1.0.8,<2.0.0).
So, because <my module> depends on both label-studio-ml (^1.0.8) and label-studio (^1.7.0), version solving failed.
</code>```

I don't want to make things more complex than they need to be by managing two environments for the same service. Do you know a version combination that does not run into a conflict?

(Also, this is a bad look on label-studio's side, if any LS dev is reading. Does not make me inclined to look into the enterprise option.)

Body:
Following the Label Studio documentation (e.g. https://labelstud.io/tutorials/dummy_model.html), you require both label-studio and label-studio installed. When I try to install these in the same environment, I always end up with version conflicts. I tried various versions manually.

$ poetry add label-studio-ml
$ poetry add label-studio

Because no versions of label-studio match >1.7.0,<2.0.0
 and label-studio (1.7.0) depends on label-studio-converter (0.0.48rc0), label-studio (>=1.7.0,<2.0.0) requires label-studio-converter (0.0.48rc0).
And because label-studio-converter (0.0.48rc0) depends on label-studio-tools (0.0.1), label-studio (>=1.7.0,<2.0.0) requires label-studio-tools (0.0.1).
And because label-studio-ml (1.0.8) depends on label-studio-tools (0.0.0.dev11)
 and no versions of label-studio-ml match >1.0.8,<2.0.0, label-studio (>=1.7.0,<2.0.0) is incompatible with label-studio-ml (>=1.0.8,<2.0.0).
So, because <my module> depends on both label-studio-ml (^1.0.8) and label-studio (^1.7.0), version solving failed.

I don't want to make things more complex than they need to be by managing two environments for the same service. Do you know a version combination that does not run into a conflict?

(Also, this is a bad look on label-studio's side, if any LS dev is reading. Does not make me inclined to look into the enterprise option.)


问:
Tabulator: Is it possible to set the cell edited property programmatically?
When setting up my Tabulator Table, I am using the cellEdited event to update the column value in all of the selected rows using cell.setValue(). The value is being updated, but cell.isEdited() returns false.

I understand this is by design, but I am wondering if there is any way that I can modify the cell edited property programmatically (specifically set it to true) so that after updating these values I can call table.getEditedCells() and use the returned cells to create a list of rows that have had values modified.

I am just wondering if I missed something in the documentation or if this is not currently supported?


问:
Google apps script "exception: cannot retrieve the next object" when trying to run user-defined function
I put together an add-on to automate some processes in Google Sheets and published it internally to my domain. Users occasionally get the below error when trying to run the add-on; when I try to rerun on the same files, I get the same error.

exception: cannot retrieve the next object: iterator has reached the end

Looking at the logs, the line that triggers the error is the one marked below:

```<code>function setupFilePrepVars() {
  // some setup stuff for subsequent work/function calls. built with the idea that this is the first function executed in a given step
  let filePrepSS = SpreadsheetApp.getActiveSpreadsheet();
  checkSheetNames(filePrepSS, fptExpectedNames);  <<<< offending line
  ...
</code>```

fptExpectedNames is an array of strings. Also, as noted in the comment, setupFilePrepVars is called in the first line of the script.

The logs don't actually specify a line within this function, so I think the problem is with one of the inputs, but in case it's relevant, here's the definition:

```<code>function checkSheetNames(ss, expectedNames) {
  let sheets = ss.getSheets();
  let names = [];
  for (let sheet of sheets) {
    names.push(sheet.getName());
  };
  // add check of expectedNames
  for (let expected of expectedNames) {
    if (names.indexOf(expected) === -1) {
      throw `Missing sheet "${expected}" in "${ss.getName()}" spreadsheet`;
    };
  };
};
</code>```

I've searched around and haven't been able to identify the root cause, but I've been able to hackily resolve the error when it comes up by making a copy of the spreadsheet and rerunning the script there.

Body:
I put together an add-on to automate some processes in Google Sheets and published it internally to my domain. Users occasionally get the below error when trying to run the add-on; when I try to rerun on the same files, I get the same error.

exception: cannot retrieve the next object: iterator has reached the end

Looking at the logs, the line that triggers the error is the one marked below:

function setupFilePrepVars() {
  // some setup stuff for subsequent work/function calls. built with the idea that this is the first function executed in a given step
  let filePrepSS = SpreadsheetApp.getActiveSpreadsheet();
  checkSheetNames(filePrepSS, fptExpectedNames);  <<<< offending line
  ...

fptExpectedNames is an array of strings. Also, as noted in the comment, setupFilePrepVars is called in the first line of the script.

The logs don't actually specify a line within this function, so I think the problem is with one of the inputs, but in case it's relevant, here's the definition:

function checkSheetNames(ss, expectedNames) {
  let sheets = ss.getSheets();
  let names = [];
  for (let sheet of sheets) {
    names.push(sheet.getName());
  };
  // add check of expectedNames
  for (let expected of expectedNames) {
    if (names.indexOf(expected) === -1) {
      throw `Missing sheet "${expected}" in "${ss.getName()}" spreadsheet`;
    };
  };
};

I've searched around and haven't been able to identify the root cause, but I've been able to hackily resolve the error when it comes up by making a copy of the spreadsheet and rerunning the script there.


问:
Autotools: How to add a shared library .so?
I tried to add my Fortran modules and a shared library (.so) into an extensive library. The code does not complain about the modules. It knows where to find .mod files. However, I do not know what option should be put in configure.ac to make it consider the shared library .so.

By far, I tried the following commands separately in configure.ac but no success:

Option 1)

```<code>medys_LDADD = -L/PathToDirectory -lnamelib
</code>```

Option 2)

```<code>LDADD=PathToDirectory/namelib.so
</code>```

Option 3)

```<code>AM_LDADD = PathToDirectory/namelib.so
</code>```

Body:
I tried to add my Fortran modules and a shared library (.so) into an extensive library. The code does not complain about the modules. It knows where to find .mod files. However, I do not know what option should be put in configure.ac to make it consider the shared library .so.

By far, I tried the following commands separately in configure.ac but no success:

Option 1)

medys_LDADD = -L/PathToDirectory -lnamelib

Option 2)

LDADD=PathToDirectory/namelib.so

Option 3)

AM_LDADD = PathToDirectory/namelib.so


问:
Connection to Availability Group Listener gives a 'Transport Level' Error in SSMS when I shut down Primary
I have a Node1\INST1 SQL Server instance which is the Primary and a Node2\Inst2 which is the Secondary in the High Availability Group. Both shows 'Synchronized' as the status, and both show 'No Data Loss'. I have also configured the Failover correctly.

Both are up and I have my SSMS open with a connection to the Listener,1496. I fire a query against this one test table and it returns the correct results.

Next, I stop the SQL Service on the Primary (to test the Failover). The 'Automatic Failover' happens correctly and I can see now the Node2\Inst2 is Primary.

But my query on the listener connection window gives that typical:

A transport level occurred

error if I fire that query again. Shouldn't that query work seamlessly? Like tomorrow, If I have a .NET app with the connection string pointing to the listener, what kind of issues will I face when the Primary goes down?

Please let me know If I am testing it wrong or if I need to do something else.

Thanks


问:
Preserve COMMIT_EDITMSG between `git commit` runs when using pre-commit hooks
My team is using Git pre-commit hooks to validate commit messages for formatting rule compliance. This means whenever I go and run git commit, then fill in COMMIT_EDITMSG and save and close the file, a script will run that will check its contents against a set of rules and put out a respective exit code which either fails the commit creation process or allows it to pass.

I tend to need multiple passes at making my Git commit messages comply with all of the rules as the rule checking is non-interactive so I only learn whether my commit message is compliant after I've saved and closed COMMIT_EDITMSG.

I also tend to write expansive commit message bodies with multiple paragraphs of context which greatly increases the likelihood of running afoul of the lint rules as well as the time required to author a commit in case I am not able to preserve the commit message draft in between git commit invocations and need to rewrite the commit message each time or craft it in a temporary file until git commit passes and I can discard the temporary file.

I am hoping to find a solution to preserving the commit message without having to use a temporary file between the multiple git commit invocations only the last of which results in the commit being created.

I have found a related questions concerning Vim here: Git: Recover failed commit's message. However, the solutions there are either to use submodules (we aren't) or to configure Vim to keep the backup file.

I am using VS Code as the configured Git editor for authoring commit messages so I am hoping to find a VS Code-compatible solution. I have set it up like so:

git config --global core.editor "code --wait"

When I go and run git commit from the VS Code integrated terminal, a new tab will open with the COMMIT_EDITMSG file and when I close that tab, Git will take notice and run the pre-commit hooks for me. I don't have to close VS Code as a whole for this even though it is not a separate instance of VS Code.

Is there a way to make Git preserve COMMIT_EDITMSG whenever the commit creation fails due to a hook returning a non-zero exit code?

Alternatively, is there a way to make VS Code preserve contents of a file at a path I saved and closed and that got deleted externally later?

There are a few VS Code settings which feel in the ballpark, like workbench.action.keepEditor, but nothing like what I need.

Is my only hope adjusting the pre-commit hook such that it stores the commit message draft in a separate file not known to Git before exiting and then recovers the message the next time around I go to run git commit? Can you even pre-fill a suggested commit message from a hook when git commit is ran?


问:
How to scrap Airbnb properly
I'm trying to scrap Airbnb, indeed only three simples informations: description, city and price of each apartment in a country. However it is not working. All the time it apears the  AttributeError: "ResultSet object has no attribute 'get_text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?"

How can I scrap these data properly?
Here is my code:

```<code>headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
    'Accept-Language':'en-GB, en; q=0.5',
    'Referer':'https://google.com',
    'DNT':'1'}
url = 'https://www.airbnb.com.br/s/Italia/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_lengths%5B%5D=one_week&price_filter_input_type=0&price_filter_num_nights=5&query=Italia&place_id=ChIJA9KNRIL-1BIRb15jJFz1LOI&date_picker_type=calendar&checkin=2023-03-09&checkout=2023-04-09&adults=1&source=structured_search_input_header&search_type=autocomplete_click'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')

features_dict = {}
descp = soup.find_all("div", {"class": "t1jojoys dir dir-ltr"}).get_text()
city = soup.find_all("div", {"class": "nquyp1l s1cjsi4j dir dir-ltr"}).get_text()
price = soup.find_all("div", {"class": "phbjkf1 dir dir-ltr"}).get_text()

features_dict['descrição'] = descp
features_dict['cidade'] = city
features_dict['preço'] = price
</code>```

Well, I erased the ".get_text()" and the above error did not apper anymore, however all my lists of html elements are empty. When I to a brief check to see whether all html classes are there, I discover that the classes which I'm interested they don't appear.

```<code>class_list = set()
tags = {tag.name for tag in soup.find_all()}
for tag in tags:
    for i in soup.find_all(tag):
        if i.has_attr("class"):
            if len(i['class']) != 0:
                class_list.add(" ".join(i['class']))
classes = list(class_list)
</code>```

What am I doing wrong?

Title: How to scrap Airbnb properly

Body:
I'm trying to scrap Airbnb, indeed only three simples informations: description, city and price of each apartment in a country. However it is not working. All the time it apears the  AttributeError: "ResultSet object has no attribute 'get_text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?"

How can I scrap these data properly?
Here is my code:

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
    'Accept-Language':'en-GB, en; q=0.5',
    'Referer':'https://google.com',
    'DNT':'1'}
url = 'https://www.airbnb.com.br/s/Italia/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_lengths%5B%5D=one_week&price_filter_input_type=0&price_filter_num_nights=5&query=Italia&place_id=ChIJA9KNRIL-1BIRb15jJFz1LOI&date_picker_type=calendar&checkin=2023-03-09&checkout=2023-04-09&adults=1&source=structured_search_input_header&search_type=autocomplete_click'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')

features_dict = {}
descp = soup.find_all("div", {"class": "t1jojoys dir dir-ltr"}).get_text()
city = soup.find_all("div", {"class": "nquyp1l s1cjsi4j dir dir-ltr"}).get_text()
price = soup.find_all("div", {"class": "phbjkf1 dir dir-ltr"}).get_text()

features_dict['descrição'] = descp
features_dict['cidade'] = city
features_dict['preço'] = price

Well, I erased the ".get_text()" and the above error did not apper anymore, however all my lists of html elements are empty. When I to a brief check to see whether all html classes are there, I discover that the classes which I'm interested they don't appear.

class_list = set()
tags = {tag.name for tag in soup.find_all()}
for tag in tags:
    for i in soup.find_all(tag):
        if i.has_attr("class"):
            if len(i['class']) != 0:
                class_list.add(" ".join(i['class']))
classes = list(class_list)

What am I doing wrong?


问:
getting error importing spacy in my jupiter notebook
i have pip installed spacy it's already there, but when I import it I get error

Here is a screenshot for details


问:
How to copy an existing nested array into a new array in state
I am receiving a value from a previous screen that I want to use to retrieve a nested array from another file and set the nested array as a new array in state. So for example in the code below I am receiving the value of "Monday" and would like to set dayValues to {value1: 1, value2: 2, value3: 3}.

```<code>const days = [
    {
        Monday: {
            value1: 1,
            value2: 2,
            value3: 3
        },
        Tuesday: {
            value4: 4,
            value5: 5,
            value6: 6
        }
    }
]

const [ dayValues, setDayValues ] = useState({});

</code>```

I understand how to use map to return individual values but haven't been able to find a way to create an entirely new array. Any help would be appreciated

Body:
I am receiving a value from a previous screen that I want to use to retrieve a nested array from another file and set the nested array as a new array in state. So for example in the code below I am receiving the value of "Monday" and would like to set dayValues to {value1: 1, value2: 2, value3: 3}.

const days = [
    {
        Monday: {
            value1: 1,
            value2: 2,
            value3: 3
        },
        Tuesday: {
            value4: 4,
            value5: 5,
            value6: 6
        }
    }
]

const [ dayValues, setDayValues ] = useState({});

I understand how to use map to return individual values but haven't been able to find a way to create an entirely new array. Any help would be appreciated


问:
Creating react app with npx, npm install returns warnings
I just started making my first react/firebase app and ran the command npx create-react-app test-app. Once I cd into my folder I ran npm i --save firebase. However, this created '10 high severity vulnerabilities'. I ran npm audit fix --force as it suggested to me, but surprisingly that threw a lot of deprication warnings and gave more vulnerabilities.

```<code>npm WARN using --force Recommended protections disabled.
npm WARN audit Updating react-scripts to 4.0.3, which is a SemVer major change.
npm WARN deprecated @npmcli/move-file@1.1.2: This functionality has been moved to @npmcli/fs
npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
npm WARN deprecated flatten@1.0.3: flatten is deprecated in favor of utility frameworks such as lodash.
npm WARN deprecated @hapi/topo@3.1.6: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/bourne@1.3.2: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated rollup-plugin-terser@5.3.1: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-terser
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
npm WARN deprecated querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated sane@4.1.0: some dependency vulnerabilities fixed, support for node < 10 dropped, and newer ECMAScript syntax/features added
npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies
npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies
npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.
npm WARN deprecated @hapi/address@2.1.4: Moved to 'npm install @sideway/address'
npm WARN deprecated rollup-plugin-babel@4.4.0: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-babel.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/joi@15.1.1: Switch to 'npm install joi'
npm WARN deprecated core-js@2.6.12: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js.
</code>```

I'm out of ideas how to fix this. I managed to find this earlier post. But after attempting those answers, I did not get any different result.

package.json

```<code>{
  "name": "test-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "firebase": "^9.15.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "^4.0.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

</code>```

I did nothing to the files itselfs, just those 3 command lines I showed at the top.

Body:
I just started making my first react/firebase app and ran the command npx create-react-app test-app. Once I cd into my folder I ran npm i --save firebase. However, this created '10 high severity vulnerabilities'. I ran npm audit fix --force as it suggested to me, but surprisingly that threw a lot of deprication warnings and gave more vulnerabilities.

npm WARN using --force Recommended protections disabled.
npm WARN audit Updating react-scripts to 4.0.3, which is a SemVer major change.
npm WARN deprecated @npmcli/move-file@1.1.2: This functionality has been moved to @npmcli/fs
npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
npm WARN deprecated flatten@1.0.3: flatten is deprecated in favor of utility frameworks such as lodash.
npm WARN deprecated @hapi/topo@3.1.6: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/bourne@1.3.2: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated rollup-plugin-terser@5.3.1: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-terser
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
npm WARN deprecated querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated sane@4.1.0: some dependency vulnerabilities fixed, support for node < 10 dropped, and newer ECMAScript syntax/features added
npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies
npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies
npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.
npm WARN deprecated @hapi/address@2.1.4: Moved to 'npm install @sideway/address'
npm WARN deprecated rollup-plugin-babel@4.4.0: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-babel.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/joi@15.1.1: Switch to 'npm install joi'
npm WARN deprecated core-js@2.6.12: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js.

I'm out of ideas how to fix this. I managed to find this earlier post. But after attempting those answers, I did not get any different result.

package.json

{
  "name": "test-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "firebase": "^9.15.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "^4.0.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I did nothing to the files itselfs, just those 3 command lines I showed at the top.


问:
Tensor conversion requested dtype int64 for Tensor with dtype float32 when creating CNN model
I tried to create a CNN but I got an error. Could you figure out what I did wrong?

C1, C2 = tf.constant(70, dtype='float32'), tf.constant(1000, dtype="float32")

def score(y_true, y_pred):
    tf.dtypes.cast(y_true, tf.float32)
    tf.dtypes.cast(y_pred, tf.float32)
    sigma = y_pred[:, 2] - y_pred[:, 0]
    fvc_pred = y_pred[:, 1]

    # sigma_clip = sigma + C1
    sigma_clip = tf.maximum(sigma, C1)
    delta = tf.abs(y_true[:, 0] - fvc_pred)
    delta = tf.minimum(delta, C2)
    sq2 = tf.sqrt(tf.dtypes.cast(2, dtype=tf.float32))
    metric = (delta / sigma_clip) * sq2 + tf.math.log(sigma_clip * sq2)

    return K.mean(metric)
```
<pre class="lang-py prettyprint-override"><code>def mloss(_lambda):
    def loss(y_true, y_pred):
        return _lambda * qloss(y_true, y_pred) + (1 - _lambda) * score(y_true, y_pred)

    return loss
</code>```

def make_model():
    z = L.Input((9,), name="Patient")
    x = L.Dense(100, activation="relu", name="d1")(z)
    x = L.Dense(100, activation="relu", name="d2")(x)

    p1 = L.Dense(3, activation="linear", name="p1")(x)
    p2 = L.Dense(3, activation="relu", name="p2")(x)
    preds = L.Lambda(lambda x: x[0] + tf.cumsum(x[1], axis=1), name="preds")([p1, p2])

    model = M.Model(z, preds, name="CNN")

    model.compile(loss=mloss(0.8), optimizer="adam", metrics=[score])
    return model
```
<pre class="lang-py prettyprint-override"><code>net = make_model()

net.fit(z[tr_idx], y[tr_idx], batch_size=200, epochs=1000,
        validation_data=(z[val_idx], y[val_idx]), verbose=0)
</code>```

Error here: ValueError: Tensor conversion requested dtype int64 for
Tensor with dtype float32: <tf.Tensor 'CNN/preds/add:0' shape=(None,
3) dtype=float32>

type cast but didn't solve the problem

Body:
I tried to create a CNN but I got an error. Could you figure out what I did wrong?

C1, C2 = tf.constant(70, dtype='float32'), tf.constant(1000, dtype="float32")

def score(y_true, y_pred):
    tf.dtypes.cast(y_true, tf.float32)
    tf.dtypes.cast(y_pred, tf.float32)
    sigma = y_pred[:, 2] - y_pred[:, 0]
    fvc_pred = y_pred[:, 1]

    # sigma_clip = sigma + C1
    sigma_clip = tf.maximum(sigma, C1)
    delta = tf.abs(y_true[:, 0] - fvc_pred)
    delta = tf.minimum(delta, C2)
    sq2 = tf.sqrt(tf.dtypes.cast(2, dtype=tf.float32))
    metric = (delta / sigma_clip) * sq2 + tf.math.log(sigma_clip * sq2)

    return K.mean(metric)

def mloss(_lambda):
    def loss(y_true, y_pred):
        return _lambda * qloss(y_true, y_pred) + (1 - _lambda) * score(y_true, y_pred)

    return loss

def make_model():
    z = L.Input((9,), name="Patient")
    x = L.Dense(100, activation="relu", name="d1")(z)
    x = L.Dense(100, activation="relu", name="d2")(x)

    p1 = L.Dense(3, activation="linear", name="p1")(x)
    p2 = L.Dense(3, activation="relu", name="p2")(x)
    preds = L.Lambda(lambda x: x[0] + tf.cumsum(x[1], axis=1), name="preds")([p1, p2])

    model = M.Model(z, preds, name="CNN")

    model.compile(loss=mloss(0.8), optimizer="adam", metrics=[score])
    return model

net = make_model()

net.fit(z[tr_idx], y[tr_idx], batch_size=200, epochs=1000,
        validation_data=(z[val_idx], y[val_idx]), verbose=0)

Error here: ValueError: Tensor conversion requested dtype int64 for
Tensor with dtype float32: <tf.Tensor 'CNN/preds/add:0' shape=(None,
3) dtype=float32>

type cast but didn't solve the problem


问:
What's the right way to use CoreData in an AppIntent?
I have an AppIntent (introduced in iOS 16.0) that utilizes my Core Data store. If I enable CoreData's concurrency debugging (add this argument to scheme -com.apple.CoreData.ConcurrencyDebug 1), I get errors while my app is running.

I've begun using background contexts from my container in conjunction with context.performAndWait and am able to avoid the concurrency error.

Is this the right way to use CoreData within an AppIntent, or is there a different pattern I should be leveraging?


问:
how to use server paginated tables using igGrid and ajax (server written in python, pages written in html and javascript)
Trying to migrate from DataTables.js to igGrid but we need to control the details in the pagination and queries made in the server.
Is there a way to do it in idGrid? (bearing in mind that we will expect the ajax call to send all the information in terms of columns, data, etc...)

Didn't try. Only exploring to see if igGrid is our decission.


问:
Pygame Text Not Displaying
Just trying to get some basic text displaying on my pygame application, however, I have no text showing up, nor do I have any sort of error. Here is my code:

Just the variable here, I believe there is nothing wrong with it.

```<code>textfont = pygame.font.SysFont("monospace", 50)
</code>```

These lines of code are in my main loop which keeps the display updating...

```<code>textTBD = textfont.render("Hello woild", 1,(255, 255, 255))
win.blit(textTBD, (10, 10))
</code>```

Sorry if its stupidly obvious, I'm new to python and coding in general haha

Title: Pygame Text Not Displaying

Body:
Just trying to get some basic text displaying on my pygame application, however, I have no text showing up, nor do I have any sort of error. Here is my code:

Just the variable here, I believe there is nothing wrong with it.

textfont = pygame.font.SysFont("monospace", 50)

These lines of code are in my main loop which keeps the display updating...

textTBD = textfont.render("Hello woild", 1,(255, 255, 255))
win.blit(textTBD, (10, 10))

Sorry if its stupidly obvious, I'm new to python and coding in general haha