问:
Flutter: PlatformException(Exception encountered, deleteAll, java.lang.IllegalArgumentException: bad base-64
I use the secure storage package to store data relevant to my app usage.

Recently I created some new features not related to that package and everything works perfectly on development environment. But after deploying the app on the google play store, I get an error when trying to use secure storage.

After clicking on the login button, I try to clean the secure storage using the clear function from the code below.

When I do that, I get an error:

```<code>PlatformException(Exception encountered, deleteAll, java.lang.IllegalArgumentException: bad base-64  at
u4.e.c(Unknown Source:37)  at
u4.e.b(Unknown Source:2)  at
u4.e.a(Unknown Source:6)  at
androidx.security.crypto.a.c(Unknown Source:3)  at
androidx.security.crypto.a.getAll(Unknown Source:49)  at
androidx.security.crypto.a$b.a(Unknown Source:11)  at
androidx.security.crypto.a$b.apply(Unknown Source:0)  at
s6.a.e(Unknown Source:23)  at s6.e$b.run(Unknown Source:135)  at
android.os.Handler.handleCallback(Handler.java:942)  at
android.os.Handler.dispatchMessage(Handler.java:99)  at
android.os.Looper.loopOnce(Looper.java:240)  at
android.os.Looper.loop(Looper.java:351)  at
android.os.HandlerThread.run(HandlerThread.java:67) , null)
</code>```

On the moment that the error triggers the storage has 2 values in it that would be cleaned. An email and a JWT token.

So far the error only happens on my own smartphone (OnePlus 8 Pro + Oxygen OS 13) and on this new version installed from the play store. Other people haven't been able to reproduce the error I get. Also, the code that now gives me this error exists, implemented exactly as in this version, on the app since the first version (I already updated the app a few times) and i never had that error before.

My secure storage implementation

```<code>class SecureStorageService {
  static final SecureStorageService _instance =
      SecureStorageService._internal();
  late FlutterSecureStorage flutterSecureStorage;

  SecureStorageService._internal() {
    flutterSecureStorage = const FlutterSecureStorage(
        aOptions: AndroidOptions(
      encryptedSharedPreferences: true,
    ));
  }

  static SecureStorageService get getInstance => _instance;

  Future<bool> set({required String key, required String value}) async {
    await flutterSecureStorage.write(
      key: key,
      value: value,
    );
    return true;
  }

  Future<String?> get({required String key}) async {
    return flutterSecureStorage.read(key: key);
  }

  Future<bool> clear() async {
      await flutterSecureStorage.deleteAll(
          aOptions: const AndroidOptions(encryptedSharedPreferences: true));
    return true;
  }
}
</code>```

Things I already tried based on some research:

adding aOptions: const AndroidOptions(encryptedSharedPreferences:
true)

update flutter to its latest version 3.3.10

update storage package to its latest version 7.0.1

tried to play with android:allowBackup and android:fullBackupContent

Another thing I noticed is that if I clear the app data on the android, the error does not happen. But if I uninstall and install the app again, the error comes back until I clear the app data again

Considering the fact that cleaning the app's data from android "solves the problem", I tried to do that programmatically with things like:

```<code>await DefaultCacheManager().emptyCache();

Future<void> _deleteCacheDir() async {
  final cacheDir = await getTemporaryDirectory();
  if (cacheDir.existsSync()) {
    cacheDir.deleteSync(recursive: true);
  }
}

Future<void> _deleteAppDir() async {
  final appDir = await getApplicationSupportDirectory();
  if (appDir.existsSync()) {
    appDir.deleteSync(recursive: true);
  }
}
</code>```

But it didn't work. I think that what I'm doing through code is probably not equivalent to what android does.

Body:
I use the secure storage package to store data relevant to my app usage.

Recently I created some new features not related to that package and everything works perfectly on development environment. But after deploying the app on the google play store, I get an error when trying to use secure storage.

After clicking on the login button, I try to clean the secure storage using the clear function from the code below.

When I do that, I get an error:

PlatformException(Exception encountered, deleteAll, java.lang.IllegalArgumentException: bad base-64  at
u4.e.c(Unknown Source:37)  at
u4.e.b(Unknown Source:2)  at
u4.e.a(Unknown Source:6)  at
androidx.security.crypto.a.c(Unknown Source:3)  at
androidx.security.crypto.a.getAll(Unknown Source:49)  at
androidx.security.crypto.a$b.a(Unknown Source:11)  at
androidx.security.crypto.a$b.apply(Unknown Source:0)  at
s6.a.e(Unknown Source:23)  at s6.e$b.run(Unknown Source:135)  at
android.os.Handler.handleCallback(Handler.java:942)  at
android.os.Handler.dispatchMessage(Handler.java:99)  at
android.os.Looper.loopOnce(Looper.java:240)  at
android.os.Looper.loop(Looper.java:351)  at
android.os.HandlerThread.run(HandlerThread.java:67) , null)

On the moment that the error triggers the storage has 2 values in it that would be cleaned. An email and a JWT token.

So far the error only happens on my own smartphone (OnePlus 8 Pro + Oxygen OS 13) and on this new version installed from the play store. Other people haven't been able to reproduce the error I get. Also, the code that now gives me this error exists, implemented exactly as in this version, on the app since the first version (I already updated the app a few times) and i never had that error before.

My secure storage implementation

class SecureStorageService {
  static final SecureStorageService _instance =
      SecureStorageService._internal();
  late FlutterSecureStorage flutterSecureStorage;

  SecureStorageService._internal() {
    flutterSecureStorage = const FlutterSecureStorage(
        aOptions: AndroidOptions(
      encryptedSharedPreferences: true,
    ));
  }

  static SecureStorageService get getInstance => _instance;

  Future<bool> set({required String key, required String value}) async {
    await flutterSecureStorage.write(
      key: key,
      value: value,
    );
    return true;
  }

  Future<String?> get({required String key}) async {
    return flutterSecureStorage.read(key: key);
  }

  Future<bool> clear() async {
      await flutterSecureStorage.deleteAll(
          aOptions: const AndroidOptions(encryptedSharedPreferences: true));
    return true;
  }
}

Things I already tried based on some research:

adding aOptions: const AndroidOptions(encryptedSharedPreferences:
true)

update flutter to its latest version 3.3.10

update storage package to its latest version 7.0.1

tried to play with android:allowBackup and android:fullBackupContent

Another thing I noticed is that if I clear the app data on the android, the error does not happen. But if I uninstall and install the app again, the error comes back until I clear the app data again

Considering the fact that cleaning the app's data from android "solves the problem", I tried to do that programmatically with things like:

await DefaultCacheManager().emptyCache();

Future<void> _deleteCacheDir() async {
  final cacheDir = await getTemporaryDirectory();
  if (cacheDir.existsSync()) {
    cacheDir.deleteSync(recursive: true);
  }
}

Future<void> _deleteAppDir() async {
  final appDir = await getApplicationSupportDirectory();
  if (appDir.existsSync()) {
    appDir.deleteSync(recursive: true);
  }
}

But it didn't work. I think that what I'm doing through code is probably not equivalent to what android does.


来源: stackexchange

问:
Radio Buttons are not showing text description one safari for iPhone
I have a number of radio buttons and all work fine on some iPhones' safari and not properly showing descriptions on some of Iphone's as shown below see attached screenshot.

I have inspected the elements and attached a screenshot of inspected code.

ContentLicense: CC BY-SA 4.0


问:
Getting controls from a panel for copying to another panel without removal from the first Panel in winform
I have a following piece of code in which I am dynamically adding controls to the panelDetection and using an if condition I am copying some controls to the temporary panel.

```<code> MessageBox.Show(panelDetection.Controls.Count.ToString());
        Panel tempPanel = new Panel();

        for(int i=0;i< panelDetection.Controls.Count;i++)
        {

            if (panelDetection.Controls[i] is ImageControl)
            {
                ImageControl imageControl = (ImageControl)panelDetection.Controls[i];

                tempPanel.Controls.Add(imageControl);

            }

        }

            }

            MessageBox.Show(panelDetection.Controls.Count.ToString());
</code>```

Although some of the controls(Not all) do get copied to the tempPanel But strangely , the controls from the source panel , that is panelDetection get removed , whereas, nowhere in the code I am extracting or removing the control from the panelDetection .
Is there a way that I could copy the controls from the panelDetection to the tempPanel without affecting the panelDetection.

Panels before the code

Panels After the code

Regards

Body:
I have a following piece of code in which I am dynamically adding controls to the panelDetection and using an if condition I am copying some controls to the temporary panel.

 MessageBox.Show(panelDetection.Controls.Count.ToString());
        Panel tempPanel = new Panel();

        for(int i=0;i< panelDetection.Controls.Count;i++)
        {

            if (panelDetection.Controls[i] is ImageControl)
            {
                ImageControl imageControl = (ImageControl)panelDetection.Controls[i];

                tempPanel.Controls.Add(imageControl);

            }

        }

            }

            MessageBox.Show(panelDetection.Controls.Count.ToString());

Although some of the controls(Not all) do get copied to the tempPanel But strangely , the controls from the source panel , that is panelDetection get removed , whereas, nowhere in the code I am extracting or removing the control from the panelDetection .
Is there a way that I could copy the controls from the panelDetection to the tempPanel without affecting the panelDetection.

Panels before the code

Panels After the code

Regards


问:
How can I resolve ImportError: cannot import name 'SpacyDocReader' from 'pke.readers'?
This is my first time posting on Stackoverflow. I'm having this Import Error when trying to execute this code snippet in my jupyter notebook:

```<code>import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
import string
import pke
import traceback

def get_nouns_multipartite(content):
    out=[]
    try:
        extractor = pke.unsupervised.MultipartiteRank()
        extractor.load_document(input=content)
        #    not contain punctuation marks or stopwords as candidates.
        pos = {'PROPN','NOUN'}
        #pos = {'PROPN','NOUN'}
        stoplist = list(string.punctuation)
        stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-']
        stoplist += stopwords.words('english')
        extractor.candidate_selection(pos=pos, stoplist=stoplist)
        # 4. build the Multipartite graph and rank candidates using random walk,
        #    alpha controls the weight adjustment mechanism, see TopicRank for
        #    threshold/method parameters.
        extractor.candidate_weighting(alpha=1.1,
                                      threshold=0.75,
                                      method='average')
        keyphrases = extractor.get_n_best(n=15)

        for val in keyphrases:
            out.append(val[0])
    except:
        out = []
        traceback.print_exc()

    return out
</code>```

And I got the error: ImportError: cannot import name 'SpacyDocReader' from 'pke.readers'

I tried downgrading the version of pke (to 1.8.1) but then there was KeyError 'hinglish'.

```<code>---> 29 get_alpha_2 = lambda l: LANGUAGE_CODE_BY_NAME[l]
     30
     31 lang_stopwords = {get_alpha_2(l): l for l in stopwords._fileids}

KeyError: 'hinglish'
</code>```

I have never used the pke library before so I'm very confused. I would appreciate all the support! Thank you so much!

Body:
This is my first time posting on Stackoverflow. I'm having this Import Error when trying to execute this code snippet in my jupyter notebook:

import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
import string
import pke
import traceback

def get_nouns_multipartite(content):
    out=[]
    try:
        extractor = pke.unsupervised.MultipartiteRank()
        extractor.load_document(input=content)
        #    not contain punctuation marks or stopwords as candidates.
        pos = {'PROPN','NOUN'}
        #pos = {'PROPN','NOUN'}
        stoplist = list(string.punctuation)
        stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-']
        stoplist += stopwords.words('english')
        extractor.candidate_selection(pos=pos, stoplist=stoplist)
        # 4. build the Multipartite graph and rank candidates using random walk,
        #    alpha controls the weight adjustment mechanism, see TopicRank for
        #    threshold/method parameters.
        extractor.candidate_weighting(alpha=1.1,
                                      threshold=0.75,
                                      method='average')
        keyphrases = extractor.get_n_best(n=15)

        for val in keyphrases:
            out.append(val[0])
    except:
        out = []
        traceback.print_exc()

    return out

And I got the error: ImportError: cannot import name 'SpacyDocReader' from 'pke.readers'

I tried downgrading the version of pke (to 1.8.1) but then there was KeyError 'hinglish'.

---> 29 get_alpha_2 = lambda l: LANGUAGE_CODE_BY_NAME[l]
     30
     31 lang_stopwords = {get_alpha_2(l): l for l in stopwords._fileids}

KeyError: 'hinglish'

I have never used the pke library before so I'm very confused. I would appreciate all the support! Thank you so much!


问:
FastAPI console log with request + response body
I am running fastAPI with the logging proposed here: How do I get my FastAPI application's console log in JSON format with a different structure and different fields?

And tried to add another log: response + request payload/body like this (in get_extra_info()):

```<code>response_body = b""
for chunk in response.body_iterator:
   response_body += chunk
</code>```

But when running getting error:

```<code>--- Logging error ---
Traceback (most recent call last):
  File "/usr/lib/python3.10/logging/__init__.py", line 1100, in emit
    msg = self.format(record)
  File "/usr/lib/python3.10/logging/__init__.py", line 943, in format
    return fmt.format(record)
  File "/home/mgarcarz/scripts/fastapi/./utils/app_logger_formatter.py", line 41, in format
    return json.dumps(get_access_log(record), indent=2)
  File "/home/mgarcarz/scripts/fastapi/./utils/app_logger_formatter.py", line 25, in get_access_log
    'req': record.extra_info['req'],
TypeError: 'coroutine' object is not subscriptable
</code>```

When i tried this example: How to log raw HTTP request/response in Python FastAPI

Request body is logged correctly, but for response body i got error:

```<code>File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/starlette/responses.py", line 269, in wrap
    await func()
  File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/starlette/responses.py", line 263, in stream_response
    await send({"type": "http.response.body", "body": b"", "more_body": False})
  File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/starlette/middleware/errors.py", line 159, in _send
    await send(message)
  File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/uvicorn/protocols/http/httptools_impl.py", line 561, in send
    raise RuntimeError("Response content shorter than Content-Length")
RuntimeError: Response content shorter than Content-Length
</code>```

Any ideas how to get it fixed ?

Thanks,

Body:
I am running fastAPI with the logging proposed here: How do I get my FastAPI application's console log in JSON format with a different structure and different fields?

And tried to add another log: response + request payload/body like this (in get_extra_info()):

response_body = b""
for chunk in response.body_iterator:
   response_body += chunk

But when running getting error:

--- Logging error ---
Traceback (most recent call last):
  File "/usr/lib/python3.10/logging/__init__.py", line 1100, in emit
    msg = self.format(record)
  File "/usr/lib/python3.10/logging/__init__.py", line 943, in format
    return fmt.format(record)
  File "/home/mgarcarz/scripts/fastapi/./utils/app_logger_formatter.py", line 41, in format
    return json.dumps(get_access_log(record), indent=2)
  File "/home/mgarcarz/scripts/fastapi/./utils/app_logger_formatter.py", line 25, in get_access_log
    'req': record.extra_info['req'],
TypeError: 'coroutine' object is not subscriptable

When i tried this example: How to log raw HTTP request/response in Python FastAPI

Request body is logged correctly, but for response body i got error:

File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/starlette/responses.py", line 269, in wrap
    await func()
  File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/starlette/responses.py", line 263, in stream_response
    await send({"type": "http.response.body", "body": b"", "more_body": False})
  File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/starlette/middleware/errors.py", line 159, in _send
    await send(message)
  File "/home/xxx/.local/share/virtualenvs/fastapi-0fqfDXdY/lib/python3.10/site-packages/uvicorn/protocols/http/httptools_impl.py", line 561, in send
    raise RuntimeError("Response content shorter than Content-Length")
RuntimeError: Response content shorter than Content-Length

Any ideas how to get it fixed ?

Thanks,


问:
My selenium in Python is popping up with a bunch of errors, and the send keys and find element is not working
I am using Python. I got the lastest chrome download and the lastest selenium download, and I installed chromedriver.exe properly. Please help!

This is my code:
`

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import random
import string
import time
PATH = "C:\Program Files (x86)\chromedriver.exe"

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(PATH)
driver=webdriver.Chrome()
driver.get('https://mail.protonmail.com/create/new?language=en')
usrnm = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
passwd = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
time.sleep(5)
emailad = driver.find_element(By.ID, 'email')
emailad.send_keys(usrnm)

time.sleep(5)

driver.quit

</code>```

`

This is the error code I am getting:
`

```<code>PS C:\Users\nuunu\OneDrive\Documents\pyscripts> & C:/Users/nuunu/AppData/Local/Programs/Python/Python310/python.exe c:/Users/nuunu/OneDrive/Documents/pyscripts/tester.py
c:\Users\nuunu\OneDrive\Documents\pyscripts\tester.py:12: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(PATH)

DevTools listening on ws://127.0.0.1:62286/devtools/browser/f06dc289-e1ab-482e-b8bb-9d838cc235a3

DevTools listening on ws://127.0.0.1:62296/devtools/browser/53203e50-b842-4cbe-95b6-9410751b9463
[17180:13148:1226/111315.478:ERROR:device_event_log_impl.cc(215)] [11:13:15.478] USB: usb_device_handle_win.cc:1045 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
Traceback (most recent call last):
  File "c:\Users\nuunu\OneDrive\Documents\pyscripts\tester.py", line 19, in <module>
    emailad.send_keys(usrnm)
  File "C:\Users\nuunu\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webelement.py", line 233, in send_keys
    self._execute(
  File "C:\Users\nuunu\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webelement.py", line 410, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\nuunu\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 444, in execute
    self.error_handler.check_response(response)
  File "C:\Users\nuunu\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 249, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
  (Session info: chrome=108.0.5359.125)
Stacktrace:
Backtrace:
        (No symbol) [0x00EEF243]
        (No symbol) [0x00E77FD1]
        (No symbol) [0x00D6CF10]
        (No symbol) [0x00D9795E]
        (No symbol) [0x00D970E5]
        (No symbol) [0x00DB858C]
        (No symbol) [0x00D92BFF]
        (No symbol) [0x00DB8804]
        (No symbol) [0x00DCC9EB]
        (No symbol) [0x00DB8386]
        (No symbol) [0x00D9163C]
        (No symbol) [0x00D9269D]
        GetHandleVerifier [0x01189A22+2655074]
        GetHandleVerifier [0x0117CA24+2601828]
        GetHandleVerifier [0x00F98C0A+619850]
        GetHandleVerifier [0x00F97830+614768]
        (No symbol) [0x00E805FC]
        (No symbol) [0x00E85968]
        (No symbol) [0x00E85A55]
        (No symbol) [0x00E9051B]
        BaseThreadInitThunk [0x774700F9+25]
        RtlGetAppContainerNamedObjectPath [0x77997BBE+286]
        RtlGetAppContainerNamedObjectPath [0x77997B8E+238]
</code>```

`

For educational purposes, I was trying to make a bot to make an account for proton email, but it kept coming up with errors and I deleted a lot of code, and everything is working up untill the "emailad = driver.find_element(By.ID, 'email')
emailad.send_keys(usrnm)"T

Body:
I am using Python. I got the lastest chrome download and the lastest selenium download, and I installed chromedriver.exe properly. Please help!

This is my code:
`

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import random
import string
import time
PATH = "C:\Program Files (x86)\chromedriver.exe"

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(PATH)
driver=webdriver.Chrome()
driver.get('https://mail.protonmail.com/create/new?language=en')
usrnm = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
passwd = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
time.sleep(5)
emailad = driver.find_element(By.ID, 'email')
emailad.send_keys(usrnm)

time.sleep(5)

driver.quit

`

This is the error code I am getting:
`

PS C:\Users\nuunu\OneDrive\Documents\pyscripts> & C:/Users/nuunu/AppData/Local/Programs/Python/Python310/python.exe c:/Users/nuunu/OneDrive/Documents/pyscripts/tester.py
c:\Users\nuunu\OneDrive\Documents\pyscripts\tester.py:12: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(PATH)

DevTools listening on ws://127.0.0.1:62286/devtools/browser/f06dc289-e1ab-482e-b8bb-9d838cc235a3

DevTools listening on ws://127.0.0.1:62296/devtools/browser/53203e50-b842-4cbe-95b6-9410751b9463
[17180:13148:1226/111315.478:ERROR:device_event_log_impl.cc(215)] [11:13:15.478] USB: usb_device_handle_win.cc:1045 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
Traceback (most recent call last):
  File "c:\Users\nuunu\OneDrive\Documents\pyscripts\tester.py", line 19, in <module>
    emailad.send_keys(usrnm)
  File "C:\Users\nuunu\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webelement.py", line 233, in send_keys
    self._execute(
  File "C:\Users\nuunu\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webelement.py", line 410, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\nuunu\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 444, in execute
    self.error_handler.check_response(response)
  File "C:\Users\nuunu\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 249, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
  (Session info: chrome=108.0.5359.125)
Stacktrace:
Backtrace:
        (No symbol) [0x00EEF243]
        (No symbol) [0x00E77FD1]
        (No symbol) [0x00D6CF10]
        (No symbol) [0x00D9795E]
        (No symbol) [0x00D970E5]
        (No symbol) [0x00DB858C]
        (No symbol) [0x00D92BFF]
        (No symbol) [0x00DB8804]
        (No symbol) [0x00DCC9EB]
        (No symbol) [0x00DB8386]
        (No symbol) [0x00D9163C]
        (No symbol) [0x00D9269D]
        GetHandleVerifier [0x01189A22+2655074]
        GetHandleVerifier [0x0117CA24+2601828]
        GetHandleVerifier [0x00F98C0A+619850]
        GetHandleVerifier [0x00F97830+614768]
        (No symbol) [0x00E805FC]
        (No symbol) [0x00E85968]
        (No symbol) [0x00E85A55]
        (No symbol) [0x00E9051B]
        BaseThreadInitThunk [0x774700F9+25]
        RtlGetAppContainerNamedObjectPath [0x77997BBE+286]
        RtlGetAppContainerNamedObjectPath [0x77997B8E+238]

`

For educational purposes, I was trying to make a bot to make an account for proton email, but it kept coming up with errors and I deleted a lot of code, and everything is working up untill the "emailad = driver.find_element(By.ID, 'email')
emailad.send_keys(usrnm)"T


问:
Deploy Django project in railway
I try to move my project from HEROKU to RAILWAY, but i got this error

When try to start a new project i get the same error

Using Nixpacks

context: 0fc4691a3fee078c9c01afe01d008723
Nixpacks build failed

Error: Error reading runtime.txt

Caused by:
stream did not contain valid UTF-8

I tried to redo the project from the beginning, but nothings change

Title: Deploy Django project in railway


问:
How to use DPLYR functions to get information from external database applying filters correctly?
I have this information:

"table_information"

num
date_inf

1
2022/01/01

2
2022/02/01

3
2022/03/01

4
2022/04/01

5
2022/05/01

Using this connection and code i can filter without problem:

```<code>con <- dbConnect(odbc::odbc(), Driver = "{MariaDB ODBC 3.1 Driver}",
             Server = "{host}", database = "db", UID = "userid",
             PWD = "pwd",
             Port = 1234)
</code>```

I can filter without problem with this:

```<code>temp<-tbl(con,sql("select * from table_information where num=3")) #or the next sentence
temp<-tbl(con,sql("select * from table_information where date_inf>'2022-03-01'"))
</code>```

Then i can convert it and work with it:

```<code>temp<-temp%>%as_tibble()
</code>```

But when i try to do with filter using dplyr i get error:

```<code>temp<-tbl(con,"table_information")
temp%>%filter(num==3) #or the next sentence
temp%>%filter(date_inf >'2022-03-01')
</code>```

I get this error for both columns, (date_inf and num):

```<code>Error in storage.mode(x) <- "double" :
  'list' object cannot be coerced to type 'double'
</code>```

not even adding

```<code>%>% collect() or as_tibble()
</code>```

num is int - str(table_information$num) and date_inf is date - str(table_information$date_inf)

I see the result of tbl like a list, but i don't know if is necessary to apply unlist() or what i'm doing wrong? i thought filters could apply directly. I want to use dplyr only, not SQL code.

Edit:
however the objects seem to have loaded fine, it seems a problem with filter

```<code> tbl(con,"table_information")

  |num   |date_inf  |
  |------|----------|
  |<int> |<date>    |
  |   1  |2022-01-01|
  |  2   |2022-02-01|
  |  3   |2022-03-01|
  | 4    |2022-04-01|
  | 5    |2022-05-01|
</code>```

Body:
I have this information:

"table_information"

num
date_inf

1
2022/01/01

2
2022/02/01

3
2022/03/01

4
2022/04/01

5
2022/05/01

Using this connection and code i can filter without problem:

con <- dbConnect(odbc::odbc(), Driver = "{MariaDB ODBC 3.1 Driver}",
             Server = "{host}", database = "db", UID = "userid",
             PWD = "pwd",
             Port = 1234)

I can filter without problem with this:

temp<-tbl(con,sql("select * from table_information where num=3")) #or the next sentence
temp<-tbl(con,sql("select * from table_information where date_inf>'2022-03-01'"))

Then i can convert it and work with it:

temp<-temp%>%as_tibble()

But when i try to do with filter using dplyr i get error:

temp<-tbl(con,"table_information")
temp%>%filter(num==3) #or the next sentence
temp%>%filter(date_inf >'2022-03-01')

I get this error for both columns, (date_inf and num):

Error in storage.mode(x) <- "double" :
  'list' object cannot be coerced to type 'double'

not even adding

%>% collect() or as_tibble()

num is int - str(table_information$num) and date_inf is date - str(table_information$date_inf)

I see the result of tbl like a list, but i don't know if is necessary to apply unlist() or what i'm doing wrong? i thought filters could apply directly. I want to use dplyr only, not SQL code.

Edit:
however the objects seem to have loaded fine, it seems a problem with filter

 tbl(con,"table_information")

  |num   |date_inf  |
  |------|----------|
  |<int> |<date>    |
  |   1  |2022-01-01|
  |  2   |2022-02-01|
  |  3   |2022-03-01|
  | 4    |2022-04-01|
  | 5    |2022-05-01|


问:
Activiti DelegateTask java class with setVaraiable function , is it doing overwrite?
I have a task variable that exists in multiple tasks with the same Id in my process instance ..
but when I use task.setVariable("variableName","value") as an instance from DelegateTask java class in TaskCompletionListener, it does not overwrite the value created before from the previous task, it creates multiple forms of the same variable Id !
what task.setVarable() actually do ?

I expected this function to overwrite the value so that it will be only one value of this variable because they all have the same Id


问:
Python library import fails when executed with 'pOpen' sub process from another Python script
I have a Python service that needs to run another Python script (in a completely different folder path) using "pOpen". That file needs to import multiple classes in different folders. 'pOpen' fails to run the script with an error message that import fails as follows :

```<code>Traceback (most recent call last):
File "C:\basic_detection\creatorop.py", line 2, in <module> from detection_Inference import * File "C:\basic_detection\detection_Inference.py",
line 13, in <module> from notebook_utils import segmentation_map_to_image, to_rgb ModuleNotFoundError: No module named 'notebook_utils'. Try again.
</code>```

I am calling the script to run with the following statement :

process = Popen(command_arg_list, shell=True, stdout=PIPE, stderr=PIPE)

The file I am calling is

creatorop.py

The header of the file is as follows :

```<code>import argparse
from detection_Inference import *
#import mytracker as m
sys.path.append(".")
sys.path.append("../utils")
sys.path.append("./utils")
from notebook_utils import segmentation_map_to_image, to_rgb

parser = argparse.ArgumentParser()
</code>```

Important : Each folder in this source path includes empty init.py files.

The folder structure where creatorop.py resides is as follows :

```<code>C:\basic_detection
> creatorop.py
> detection_inference.py
> __initi__py
<utils>
---> notebook_utils.py
---> __init__.py
</code>```

I appended all possible paths, including the 'utils' folder, but the system did not see it.

When I run the creatorop.py in its folder, it runs without any issues. This only happens when I run it from 'pOpen' from another application.

Any help ?

Body:
I have a Python service that needs to run another Python script (in a completely different folder path) using "pOpen". That file needs to import multiple classes in different folders. 'pOpen' fails to run the script with an error message that import fails as follows :

Traceback (most recent call last):
File "C:\basic_detection\creatorop.py", line 2, in <module> from detection_Inference import * File "C:\basic_detection\detection_Inference.py",
line 13, in <module> from notebook_utils import segmentation_map_to_image, to_rgb ModuleNotFoundError: No module named 'notebook_utils'. Try again.

I am calling the script to run with the following statement :

process = Popen(command_arg_list, shell=True, stdout=PIPE, stderr=PIPE)

The file I am calling is

creatorop.py

The header of the file is as follows :

import argparse
from detection_Inference import *
#import mytracker as m
sys.path.append(".")
sys.path.append("../utils")
sys.path.append("./utils")
from notebook_utils import segmentation_map_to_image, to_rgb

parser = argparse.ArgumentParser()

Important : Each folder in this source path includes empty init.py files.

The folder structure where creatorop.py resides is as follows :

C:\basic_detection
> creatorop.py
> detection_inference.py
> __initi__py
<utils>
---> notebook_utils.py
---> __init__.py

I appended all possible paths, including the 'utils' folder, but the system did not see it.

When I run the creatorop.py in its folder, it runs without any issues. This only happens when I run it from 'pOpen' from another application.

Any help ?


问:
TypeError: QTableWidget.setModel() is a private method
good evening

im trying to show an .sqlite db [Table] from SqliteStudio in my app. but i cant get it to run
i had changed the ui filed to py before but got told that thats a no go. so i loaded the ui files.
its running so far. but when i press on emloyes im just getting the following error

```<code>TypeError: QTableWidget.setModel() is a private method
</code>```
```<code>class MitarbeiterWindow(QMainWindow):
    def __init__(self):
        super(MitarbeiterWindow, self).__init__()
        loadUi("ui/MitarbeiterWindow.ui", self)
        QtWidgets.QMainWindow.__init__(self)
        print("----Mitarbeiterverwaltung geöffnet")
        self.load_mitarbeiter()
        self.mod_mitarbieter = QtSql.QSqlRelationalTableModel()
        self.mod_mitarbieter.setTable("Mitarbeiter")
        self.mod_mitarbieter.select()
        self.table_mitabeiter.setModel(self.mod_mitarbieter)
</code>```

database is open in main part here

```<code>database = QtSql.QSqlDatabase.addDatabase("QSQLITE")
database.setDatabaseName("data/database.sqlite")
database.open()
query = QtSql.QSqlQuery()
app = QApplication(sys.argv)
login_window = LoginWindow()
widget = QtWidgets.QStackedWidget()
widget.addWidget(login_window)
widget.setFixedHeight(110)
widget.setFixedWidth(430)
widget.show()
app.exec()
</code>```

showing the table employes [Mitarbeiter] in table_mitarbeiter placed in ui which has loaded from the ui

Body:
good evening

im trying to show an .sqlite db [Table] from SqliteStudio in my app. but i cant get it to run
i had changed the ui filed to py before but got told that thats a no go. so i loaded the ui files.
its running so far. but when i press on emloyes im just getting the following error

TypeError: QTableWidget.setModel() is a private method

class MitarbeiterWindow(QMainWindow):
    def __init__(self):
        super(MitarbeiterWindow, self).__init__()
        loadUi("ui/MitarbeiterWindow.ui", self)
        QtWidgets.QMainWindow.__init__(self)
        print("----Mitarbeiterverwaltung geöffnet")
        self.load_mitarbeiter()
        self.mod_mitarbieter = QtSql.QSqlRelationalTableModel()
        self.mod_mitarbieter.setTable("Mitarbeiter")
        self.mod_mitarbieter.select()
        self.table_mitabeiter.setModel(self.mod_mitarbieter)

database is open in main part here

database = QtSql.QSqlDatabase.addDatabase("QSQLITE")
database.setDatabaseName("data/database.sqlite")
database.open()
query = QtSql.QSqlQuery()
app = QApplication(sys.argv)
login_window = LoginWindow()
widget = QtWidgets.QStackedWidget()
widget.addWidget(login_window)
widget.setFixedHeight(110)
widget.setFixedWidth(430)
widget.show()
app.exec()

showing the table employes [Mitarbeiter] in table_mitarbeiter placed in ui which has loaded from the ui


问:
Why this login form sometimes fails?
I have login form that usually works but sometimes it fails. When it fails, it doesnt redirect to good page after entering successful credentials. It redirect to /undefined URL.

I am not able to find the cause but would be great if someone can assist me. I am adding whole code.

html part

```<code> <div class="container-login100">
    <div class="wrap-login100 p-6">
            <form id="frmLogin" action="/api/v1/login" method="POST">
            <span class="login100-form-title pb-5">
                Login
            </span>
            <div class="panel panel-primary">

                <div class="panel-body tabs-menu-body p-0 pt-5">
                    <div class="tab-content">
                        <div class="tab-pane active" id="tab5">
                            <div class="wrap-input100 validate-input input-group" data-bs-validate="Valid email is required: ex@abc.xyz">
                                <a  class="input-group-text bg-white text-muted">
                                    <i class="zmdi zmdi-email text-muted" aria-hidden="true"></i>
                                </a>
                                <input class="input100 border-start-0 form-control ms-0" id="username" name="username" placeholder="Username">
                            </div>
                            <div class="wrap-input100 validate-input input-group" id="Password-toggle">
                                <a href="javascript:void(0)" class="input-group-text bg-white text-muted">
                                    <i class="zmdi zmdi-eye text-muted" aria-hidden="true"></i>
                                </a>
                                <input class="input100 border-start-0 form-control ms-0" type="password" id="password" name="password" placeholder="Password">
                            </div>
                            <div class="container-login100-form-btn">
                                <button type="submit" class="login100-form-btn btn-primary" style="cursor: pointer">
                                        Login
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

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

Here is API login call ( I am using SLIM framework)

```<code>$app->post('/login', function() use ($app) {
    // check for required params
    verifyRequiredParams(array('username', 'password'));

    // reading post params
    $username = $app->request()->post('username');
    $password = $app->request()->post('password');
    $response = array();
    $db = new DbHandler();

    $password = md5($password);
    $user = $db->getUserByUsername($username, $password);

    if ($user != NULL) {
        $response["error"] = false;
        $response["firstName"] = $user['firstName'];
        if(empty($response["firstName"])){
            $response["error"] = true;
            $response["message"] = "User doesnt exist";
            //exit() ;
        }
        else{
            $response["firstName"] = $user['firstName'];
            $response["lastName"] = $user['lastName'];
            $response["apikey"] = $user["api_key"];
            $response["userId"] = $user["userId"];
            $response["jobTitle"] = $user["jobTitle"];
            $response["address"] = $user["address"];
        }

    } else {
        // unknown error occurred
        $response["error"] = true;
        $response["message"] = "An error occurred. Please try again";
    }

    echoRespnse(200, $response);
});
</code>```

Here is JS

```<code> <script>
    $(document).on('submit','#frmLogin',function(e){
        e.preventDefault();
        var data = $(this).serialize();

        $.post($(this).attr('action'),data,function(response,status) {
            odg = JSON.stringify(response);
            odg = JSON.parse(odg);
            err = odg.error;
            if(err === false){
                success('Success!');
                setSession(response);
            }
            else{
                error('Incorrect username or password. Please try again!');
            }

        });
    });

    function setSession(data)
    {
        $.post('storeSessionVariables.php',data,function(response,status){
            window.location.href = '/dashboard/pages/index.php';
        });
    }
</script>
</code>```

This is storeSessionVariables.php file:

```<code><?php
@session_start();
$_SESSION['apikey'] = $_POST['apikey'];
$_SESSION['userID'] = $_POST['userId'];
$_SESSION['jobPosition'] = $_POST['jobTitle'];
$_SESSION['fName'] = $_POST['firstName'];
$_SESSION['lName'] = $_POST['lastName'];
$_SESSION['address'] = $_POST['address'];
echo 1;
</code>```

As I stated at the beginning, it works but sometimes got stuck and redirect in /undefined
I have no clue why is that happening. Any idea, what can I improve here?

Title: Why this login form sometimes fails?

Body:
I have login form that usually works but sometimes it fails. When it fails, it doesnt redirect to good page after entering successful credentials. It redirect to /undefined URL.

I am not able to find the cause but would be great if someone can assist me. I am adding whole code.

html part

            <form id="frmLogin" action="/api/v1/login" method="POST">

                Login

                                <input class="input100 border-start-0 form-control ms-0" id="username" name="username" placeholder="Username">

                                <input class="input100 border-start-0 form-control ms-0" type="password" id="password" name="password" placeholder="Password">

                                <button type="submit" class="login100-form-btn btn-primary" style="cursor: pointer">
                                        Login
                                </button>

        </form>

Here is API login call ( I am using SLIM framework)

$app->post('/login', function() use ($app) {
    // check for required params
    verifyRequiredParams(array('username', 'password'));

    // reading post params
    $username = $app->request()->post('username');
    $password = $app->request()->post('password');
    $response = array();
    $db = new DbHandler();

    $password = md5($password);
    $user = $db->getUserByUsername($username, $password);

    if ($user != NULL) {
        $response["error"] = false;
        $response["firstName"] = $user['firstName'];
        if(empty($response["firstName"])){
            $response["error"] = true;
            $response["message"] = "User doesnt exist";
            //exit() ;
        }
        else{
            $response["firstName"] = $user['firstName'];
            $response["lastName"] = $user['lastName'];
            $response["apikey"] = $user["api_key"];
            $response["userId"] = $user["userId"];
            $response["jobTitle"] = $user["jobTitle"];
            $response["address"] = $user["address"];
        }

    } else {
        // unknown error occurred
        $response["error"] = true;
        $response["message"] = "An error occurred. Please try again";
    }

    echoRespnse(200, $response);
});

Here is JS

This is storeSessionVariables.php file:

<?php
@session_start();
$_SESSION['apikey'] = $_POST['apikey'];
$_SESSION['userID'] = $_POST['userId'];
$_SESSION['jobPosition'] = $_POST['jobTitle'];
$_SESSION['fName'] = $_POST['firstName'];
$_SESSION['lName'] = $_POST['lastName'];
$_SESSION['address'] = $_POST['address'];
echo 1;

As I stated at the beginning, it works but sometimes got stuck and redirect in /undefined
I have no clue why is that happening. Any idea, what can I improve here?


问:
How to properly write a file with Uri permission?
I got access to Android/data (the folder itself, not the app specific one) and now I need to write a file in this folder, but I have no idea how I can do this. I used the following code to check if I could write:

```<code>String path = "content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3AAndroid%2Fdata";

Uri uriPath = Uri.parse(path);
DocumentFile df = DocumentFile.fromSingleUri(activity.getApplicationContext(), uriPath);
System.out.println("1. canWrite? " + df.canWrite());

downloadedFile = new File(df.getUri().getPath(), product + ".zip");
System.out.println(downloadedFile.getAbsolutePath());
System.out.println("2. canWrite? " + downloadedFile.canWrite());
</code>```

This gave me the following output:

```<code>I/System.out: 1. canWrite? true
I/System.out: /tree/primary:Android/data/document/primary:Android/data/product1.zip
I/System.out: 2. canWrite? false
</code>```

So basically, when using DocumentFile with my application context I can write but when using a File object I can't. How can I overcome this?

Body:
I got access to Android/data (the folder itself, not the app specific one) and now I need to write a file in this folder, but I have no idea how I can do this. I used the following code to check if I could write:

String path = "content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3AAndroid%2Fdata";

Uri uriPath = Uri.parse(path);
DocumentFile df = DocumentFile.fromSingleUri(activity.getApplicationContext(), uriPath);
System.out.println("1. canWrite? " + df.canWrite());

downloadedFile = new File(df.getUri().getPath(), product + ".zip");
System.out.println(downloadedFile.getAbsolutePath());
System.out.println("2. canWrite? " + downloadedFile.canWrite());

This gave me the following output:

I/System.out: 1. canWrite? true
I/System.out: /tree/primary:Android/data/document/primary:Android/data/product1.zip
I/System.out: 2. canWrite? false

So basically, when using DocumentFile with my application context I can write but when using a File object I can't. How can I overcome this?


问:
Web Scraping VBA + Selenium Error: Element not found
Hy my friends,i am trying to build a code with vba + selenium to extract a table in a web.
When executing the macro I get the following error "Element Not Found for Class=tablaHistoricoPrecio". I don't understand, because according to the structure of the web code the table has that definition. Any help would be appreciated. Greetings.

This is my code

```<code>Private driver As New WebDriver
Sub repsol2022()
Dim GIGYA As Object
Set driver = New EdgeDriver
Dim rowc, cc, columnC As Integer
rowc = 2
With driver
.Start "edge"
.Get "https://repsol.force.com/portalGestorEESS/s/consultaPrecios"

 With .FindElementByClass("gigya-login-form")

       .FindElementByClass("gigya-input-text").SendKeys "xxx"
        .FindElementByClass("gigya-input-password").SendKeys "xxx"
         .FindElementByClass("gigya-input-submit").submit

      End With
 Application.Wait Now + TimeSerial(0, 0, 5)

For Each tr In driver.FindElementByClass("tablaHistoricoPrecio").FindElementByTag("tbody").FindElementsByClass("precioDetalle")
columnC = 1
For Each th In tr.FindElementsByClass("precioDetalle")
Data.Cells(rowc, columnC).Value = th.Text
columnC = columnC + 1
Next th
rowc = rowc + 1
Next tr

End With
Exit Sub

End Sub
</code>```

Web code image

Screenshot web table

Body:
Hy my friends,i am trying to build a code with vba + selenium to extract a table in a web.
When executing the macro I get the following error "Element Not Found for Class=tablaHistoricoPrecio". I don't understand, because according to the structure of the web code the table has that definition. Any help would be appreciated. Greetings.

This is my code

Private driver As New WebDriver
Sub repsol2022()
Dim GIGYA As Object
Set driver = New EdgeDriver
Dim rowc, cc, columnC As Integer
rowc = 2
With driver
.Start "edge"
.Get "https://repsol.force.com/portalGestorEESS/s/consultaPrecios"

 With .FindElementByClass("gigya-login-form")

       .FindElementByClass("gigya-input-text").SendKeys "xxx"
        .FindElementByClass("gigya-input-password").SendKeys "xxx"
         .FindElementByClass("gigya-input-submit").submit

      End With
 Application.Wait Now + TimeSerial(0, 0, 5)

For Each tr In driver.FindElementByClass("tablaHistoricoPrecio").FindElementByTag("tbody").FindElementsByClass("precioDetalle")
columnC = 1
For Each th In tr.FindElementsByClass("precioDetalle")
Data.Cells(rowc, columnC).Value = th.Text
columnC = columnC + 1
Next th
rowc = rowc + 1
Next tr

End With
Exit Sub

End Sub

Web code image

Screenshot web table


问:
Firebase and PHP - Select table by a field
I'm trying to select a firestore database table by the "client_name" field. But I can only select it by the "documentId" field. When I go to try errors appear, like:"Uncaught Error: Call to undefined function" are occurring.

To select the table by id use:

```<code>public function getServiceOrder(): array {

       return $this->firestore->collection(name: "service_orders")
        ->document(documentId: $_GET["id"])->snapshot()->data();

}
</code>```

Currently, to try to select by name, I do this:

```<code>public function getServiceOrderName(): array {

        return $this->firestore->collection('material_detail'). where('name_client=') . $_GET["name"];
}
</code>```

I already tried these ways (all inside the public function):

```<code>return $this->firestore->collection("os_detalhe_material")->document(documentId: "SELECT * FROM os_detalhe_material WHERE name_cliente= '" . $_GET['name'] . "'") -> snapshot()->data();
</code>```

AND

```<code>$searchDetalhe = $db->getReference('os_detalhe_material/name_client/adrian')->getSnapshot()->getValue();
</code>```

How do I select the table?

Body:
I'm trying to select a firestore database table by the "client_name" field. But I can only select it by the "documentId" field. When I go to try errors appear, like:"Uncaught Error: Call to undefined function" are occurring.

To select the table by id use:

public function getServiceOrder(): array {

       return $this->firestore->collection(name: "service_orders")
        ->document(documentId: $_GET["id"])->snapshot()->data();

}

Currently, to try to select by name, I do this:

public function getServiceOrderName(): array {

        return $this->firestore->collection('material_detail'). where('name_client=') . $_GET["name"];
}

I already tried these ways (all inside the public function):

return $this->firestore->collection("os_detalhe_material")->document(documentId: "SELECT * FROM os_detalhe_material WHERE name_cliente= '" . $_GET['name'] . "'") -> snapshot()->data();

AND

$searchDetalhe = $db->getReference('os_detalhe_material/name_client/adrian')->getSnapshot()->getValue();

How do I select the table?


问:
Runtime communication Fortran - Python
I am currently using a multi-physics solver written in Fortran. Now, I would like to substitute a module of it with a Python counterpart, thus requesting to this Python script some parameters which are then passed to Fortran to continue the requested computations.

Can you help me? Or maybe point me towards a "simpler" solution?

As a first trial, I am messing around with ForPy. I ran successfully some sample scripts in which I am passing arguments from Fortran to Python and the other way around successfully. However, when it comes to couple it with the master code I am working with, I struggle to add the necessary information in the Cmake file when I recompile it to include this modification.

Many thanks,

Title: Runtime communication Fortran - Python


问:
'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.' using Parallel.For and a WritableBitmap
I'm facing something I don't understand, and maybe someone can give me an understandable answer to this. I'm doing something wrong, but I can't see it.

I'm trying to load a Bitmap and set an Array of all pixels in it to process a blur method on it. I get an exception after calling this same method on different Bitmap multiple times.

To be clear, I have a combobox with items and following the items the background change with the same method. If I select all the items one by one, after a short time it throws the exception.

Here is the code:

private readonly ParallelOptions _pOptions = new ParallelOptions { MaxDegreeOfParallelism = 16 };

        public void CreateFrom(string filePath)
        {
            throw new NotImplementedException();
        }

        public unsafe void CreateFrom(IBitmap bitmap)
        {
            using (var memoryStream = new MemoryStream())
            {
                bitmap.Save(memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);
                var writeableBitmap = WriteableBitmap.Decode(memoryStream);
                using var lockedBitmap = writeableBitmap.Lock();

                int* bmpPtr = (int*)lockedBitmap.Address;
                _width = writeableBitmap.PixelSize.Width;
                _height = writeableBitmap.PixelSize.Height;
                _dpi = writeableBitmap.Dpi;

                _alpha = new int[_width * _height];
                _red = new int[_width * _height];
                _green = new int[_width * _height];
                _blue = new int[_width * _height];

                Parallel.For(0, _width * _height, _pOptions, (i, parallelLoopState) =>
                {
                    _alpha[i] = (int)((*(bmpPtr + i) & 0xff000000) >> 24);
                    _red[i] = (*(bmpPtr + i) & 0xff0000) >> 16;
                    _green[i] = (*(bmpPtr + i) & 0x00ff00) >> 8;
                    _blue[i] = *(bmpPtr + i) & 0x0000ff;
                });
            }
        }
```
<p>After a few selection, it throws this exception at that line <code>_alpha[i] = (int)((*(bmpPtr + i) & 0xff000000) >> 24);</code></p>
<p>If anyone can see why, that will be great ! TIA</p>
<p>Edit: Here is a short testing video, it's clearer than a thousand words lol
Short demo</p>
<p>Edit more: Here is the full class I made, thanks to all of them for this, it's really fast.</p>
<pre class="lang-cs prettyprint-override"><code>using Avalonia;
using Avalonia.Controls.Shapes;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using Ready2Play.BitmapFilters.GaussianBlur.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Tmds.DBus;

namespace Ready2Play.BitmapFilters.GaussianBlur
{
    /// <summary>
    /// Ported To Avalonia Bitmap by me.
    ///
    /// Original source:
    /// https://github.com/mdymel/superfastblur
    /// Based on an article of Ivan Kuckir:
    /// http://blog.ivank.net/fastest-gaussian-blur.html
    /// </summary>
    public class BitmapFilterGaussianBlur : IBitmapFilterGaussianBlur
    {
        private int[] _alpha;
        private int[] _red;
        private int[] _green;
        private int[] _blue;

        private int _width;
        private int _height;

        private Vector _dpi;

        private readonly ParallelOptions _pOptions = new ParallelOptions { MaxDegreeOfParallelism = 16 };

        public void CreateFrom(string filePath)
        {
            // TODO
            throw new NotImplementedException();
        }

        public unsafe void CreateFrom(IBitmap bitmap)
        {
            using (var memoryStream = new MemoryStream())
            {
                bitmap.Save(memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);
                var writeableBitmap = WriteableBitmap.Decode(memoryStream);
                using var lockedBitmap = writeableBitmap.Lock();

                int* bmpPtr = (int*)lockedBitmap.Address;
                _width = writeableBitmap.PixelSize.Width;
                _height = writeableBitmap.PixelSize.Height;
                _dpi = writeableBitmap.Dpi;

                _alpha = new int[_width * _height];
                _red = new int[_width * _height];
                _green = new int[_width * _height];
                _blue = new int[_width * _height];

                Parallel.For(0, _width * _height, _pOptions, (i, parallelLoopState) =>
                {
                    _alpha[i] = (int)((*(bmpPtr + i) & 0xff000000) >> 24);
                    _red[i] = (*(bmpPtr + i) & 0xff0000) >> 16;
                    _green[i] = (*(bmpPtr + i) & 0x00ff00) >> 8;
                    _blue[i] = *(bmpPtr + i) & 0x0000ff;
                });
            }
        }

        public IBitmap Process(IBitmapFilterGaussianBlurParameter parameter)
        {
            var newAlpha = new int[_width * _height];
            var newRed = new int[_width * _height];
            var newGreen = new int[_width * _height];
            var newBlue = new int[_width * _height];
            var dest = new int[_width * _height];

            Parallel.Invoke(
                () => gaussBlur_4(_alpha, newAlpha, parameter.Radius),
                () => gaussBlur_4(_red, newRed, parameter.Radius),
                () => gaussBlur_4(_green, newGreen, parameter.Radius),
                () => gaussBlur_4(_blue, newBlue, parameter.Radius));

            Parallel.For(0, dest.Length, _pOptions, i =>
            {
                //Math.Max(Math.Min(value, 255), 0)
                if (newAlpha[i] > 255) newAlpha[i] = 255;
                if (newRed[i] > 255) newRed[i] = 255;
                if (newGreen[i] > 255) newGreen[i] = 255;
                if (newBlue[i] > 255) newBlue[i] = 255;

                if (newAlpha[i] < 0) newAlpha[i] = 0;
                if (newRed[i] < 0) newRed[i] = 0;
                if (newGreen[i] < 0) newGreen[i] = 0;
                if (newBlue[i] < 0) newBlue[i] = 0;

                dest[i] = (int)((uint)(newAlpha[i] << 24) | (uint)(newRed[i] << 16) | (uint)(newGreen[i] << 8) | (uint)newBlue[i]);
            });

            var size = new PixelSize(_width, _height);
            var writeableBitmap = new WriteableBitmap(size, _dpi);
            using var lockedBitmap = writeableBitmap.Lock();
            Marshal.Copy(dest, 0, lockedBitmap.Address, dest.Length);
            return writeableBitmap;
        }

        private void gaussBlur_4(int[] source, int[] dest, int r)
        {
            var bxs = boxesForGauss(r, 3);
            boxBlur_4(source, dest, _width, _height, (bxs[0] - 1) / 2);
            boxBlur_4(dest, source, _width, _height, (bxs[1] - 1) / 2);
            boxBlur_4(source, dest, _width, _height, (bxs[2] - 1) / 2);
        }

        private int[] boxesForGauss(int sigma, int n)
        {
            var wIdeal = Math.Sqrt(12 * sigma * sigma / n + 1);
            var wl = (int)Math.Floor(wIdeal);
            if (wl % 2 == 0) wl--;
            var wu = wl + 2;

            var mIdeal = (double)(12 * sigma * sigma - n * wl * wl - 4 * n * wl - 3 * n) / (-4 * wl - 4);
            var m = Math.Round(mIdeal);

            var sizes = new List<int>();
            for (var i = 0; i < n; i++) sizes.Add(i < m ? wl : wu);
            return sizes.ToArray();
        }

        private void boxBlur_4(int[] source, int[] dest, int w, int h, int r)
        {
            for (var i = 0; i < source.Length; i++) dest[i] = source[i];
            boxBlurH_4(dest, source, w, h, r);
            boxBlurT_4(source, dest, w, h, r);
        }

        private void boxBlurH_4(int[] source, int[] dest, int w, int h, int r)
        {
            var iar = (double)1 / (r + r + 1);
            Parallel.For(0, h, _pOptions, i =>
            {
                var ti = i * w;
                var li = ti;
                var ri = ti + r;
                var fv = source[ti];
                var lv = source[ti + w - 1];
                var val = (r + 1) * fv;
                for (var j = 0; j < r; j++) val += source[ti + j];
                for (var j = 0; j <= r; j++)
                {
                    val += source[ri++] - fv;
                    dest[ti++] = (int)Math.Round(val * iar);
                }
                for (var j = r + 1; j < w - r; j++)
                {
                    val += source[ri++] - dest[li++];
                    dest[ti++] = (int)Math.Round(val * iar);
                }
                for (var j = w - r; j < w; j++)
                {
                    val += lv - source[li++];
                    dest[ti++] = (int)Math.Round(val * iar);
                }
            });
        }

        private void boxBlurT_4(int[] source, int[] dest, int w, int h, int r)
        {
            var iar = (double)1 / (r + r + 1);
            Parallel.For(0, w, _pOptions, i =>
            {
                var ti = i;
                var li = ti;
                var ri = ti + r * w;
                var fv = source[ti];
                var lv = source[ti + w * (h - 1)];
                var val = (r + 1) * fv;
                for (var j = 0; j < r; j++) val += source[ti + j * w];
                for (var j = 0; j <= r; j++)
                {
                    val += source[ri] - fv;
                    dest[ti] = (int)Math.Round(val * iar);
                    ri += w;
                    ti += w;
                }
                for (var j = r + 1; j < h - r; j++)
                {
                    val += source[ri] - source[li];
                    dest[ti] = (int)Math.Round(val * iar);
                    li += w;
                    ri += w;
                    ti += w;
                }
                for (var j = h - r; j < h; j++)
                {
                    val += lv - source[li];
                    dest[ti] = (int)Math.Round(val * iar);
                    li += w;
                    ti += w;
                }
            });
        }
    }
}
</code>```

More:

// TODO TEST UpdateLines in parallel - Is it OK ?
/*var bench = SimpleBench.Start();*/
//      System.NullReferenceException
//HResult = 0x80004003
//Message = Object reference not set to an instance of an object.
//Source = Avalonia.Base
//Arborescence des appels de procédure:
//      à Avalonia.Utilities.WeakHashList`1.GetAlive(Func`1 factory)
// à Avalonia.Utilities.WeakEvent`2.Subscription.OnEvent(Object sender, TEventArgs eventArgs)
// à Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcherLineDetails.set_IsRunning(Boolean value) dans E:\Devel\Ready2Play.NET6\Ready2Play\Ready2PlayGamesLibrary\CommunityToolkit.Mvvm.SourceGenerators\CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator\Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcherLineDetails.g.cs :ligne 140
//        System.AggregateException
//        HResult = 0x80131500
//  Message = One or more errors occurred. (Object reference not set to an instance of an object.) (Object reference not set to an instance of an object.) (Entry point was not found.) (Entry point was not found.) (Entry point was not found.) (Entry point was not found.) (Object reference not set to an instance of an object.) (Entry point was not found.) (Object reference not set to an instance of an object.) (Entry point was not found.) (Entry point was not found.) (Entry point was not found.) (Entry point was not found.) (Entry point was not found.) (Object reference not set to an instance of an object.) (Object reference not set to an instance of an object.)
//  Source = System.Threading.Tasks.Parallel
//  Arborescence des appels de procédure:
//        à System.Threading.Tasks.TaskReplicator.Run[TState](ReplicatableUserAction`1 action, ParallelOptions options, Boolean stopOnFirstFailure)
//   à System.Threading.Tasks.Parallel.PartitionerForEachWorker[TSource, TLocal](Partitioner`1 source, ParallelOptions parallelOptions, Action`1 simpleBody, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
//-- - Fin de la trace de la pile à partir de l'emplacement précédent ---
//   à System.Threading.Tasks.Parallel.ThrowSingleCancellationExceptionOrOtherException(ICollection exceptions, CancellationToken cancelToken, Exception otherException)
//   à System.Threading.Tasks.Parallel.PartitionerForEachWorker[TSource, TLocal](Partitioner`1 source, ParallelOptions parallelOptions, Action`1 simpleBody, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
//   à System.Threading.Tasks.Parallel.ForEachWorker[TSource, TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
//   à System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body)
//   à Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcher.RefreshLoadedLines() dans E:\Devel\Ready2Play.NET6\Ready2Play\Ready2PlayGamesLibrary\ProcessWatcher\ProcessWatcher.cs :ligne 286
//   à Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcher.<> c__DisplayClass18_0.< RefreshLoadedLines > b__3(Object stateInfo) dans E:\Devel\Ready2Play.NET6\Ready2Play\Ready2PlayGamesLibrary\ProcessWatcher\ProcessWatcher.cs :ligne 283
//   à System.Threading.TimerQueueTimer.<> c.<.cctor > b__27_0(Object state)
//   à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)

//  Cette exception a été levée à l'origine dans cette pile des appels :
//    [Code externe]
//    Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcherLineDetails.IsRunning.set(bool) dans Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcherLineDetails.g.cs
//    Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcher.RefreshLoadedLines.AnonymousMethod__2(Ready2PlayGamesLibrary.ProcessWatcher.Interfaces.IProcessWatcherLineDetails) dans ProcessWatcher.cs
//    [Code externe]

//Exception interne 1 :
//NullReferenceException: Object reference not set to an instance of an object.

//Parallel.ForEach<IProcessWatcherLineDetails>(AllLinesDetails, _pOptions, (ld) =>
//        {
//            // Check if we know a process by this name
//             ld.IsRunning = false;

//            // In this case EnsureIsRightProcess can be stripped down to gain performance
//            var p = correspondingProcesses.FirstOrDefault(p => EnsureIsRightProcess(p, lineDetailsExecutableList, ld.ExecutableFullName));
//            if (p is not null)
//            {
//                ld.Process = p;
//                ld.IsRunning = !ld.HasExited || ld.Responding;
//            }

//            // Manage game state
//            if (ld.Parent.Parent is IGame game)
//{
//    var oldState = game.State;

//    // Killing an application makes this state prioritized as it's being controlled in the lineDetail itself
//    var newState = GameState.Killing;
//    if (!ld.Parent.IsOneKilling)
//        newState = ld.Parent.IsOneRunning ? GameState.Running : (!ld.IsRunning && oldState != GameState.Loading) ? GameState.Available : oldState;

//    if (oldState != newState)
//    {
//        ((IWritableGameState)game).WriteState = newState;
//    }
//}
//        });
```

Ok, I have commented those lines in my code to check later. But that the same thing. Am I misunderstanding Parallel.For ? Because if I replace it by a simple for each it works nice.

Body:
I'm facing something I don't understand, and maybe someone can give me an understandable answer to this. I'm doing something wrong, but I can't see it.

I'm trying to load a Bitmap and set an Array of all pixels in it to process a blur method on it. I get an exception after calling this same method on different Bitmap multiple times.

To be clear, I have a combobox with items and following the items the background change with the same method. If I select all the items one by one, after a short time it throws the exception.

Here is the code:

private readonly ParallelOptions _pOptions = new ParallelOptions { MaxDegreeOfParallelism = 16 };

        public void CreateFrom(string filePath)
        {
            throw new NotImplementedException();
        }

        public unsafe void CreateFrom(IBitmap bitmap)
        {
            using (var memoryStream = new MemoryStream())
            {
                bitmap.Save(memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);
                var writeableBitmap = WriteableBitmap.Decode(memoryStream);
                using var lockedBitmap = writeableBitmap.Lock();

                int* bmpPtr = (int*)lockedBitmap.Address;
                _width = writeableBitmap.PixelSize.Width;
                _height = writeableBitmap.PixelSize.Height;
                _dpi = writeableBitmap.Dpi;

                _alpha = new int[_width * _height];
                _red = new int[_width * _height];
                _green = new int[_width * _height];
                _blue = new int[_width * _height];

                Parallel.For(0, _width * _height, _pOptions, (i, parallelLoopState) =>
                {
                    _alpha[i] = (int)((*(bmpPtr + i) & 0xff000000) >> 24);
                    _red[i] = (*(bmpPtr + i) & 0xff0000) >> 16;
                    _green[i] = (*(bmpPtr + i) & 0x00ff00) >> 8;
                    _blue[i] = *(bmpPtr + i) & 0x0000ff;
                });
            }
        }

After a few selection, it throws this exception at that line _alpha[i] = (int)((*(bmpPtr + i) & 0xff000000) >> 24);

If anyone can see why, that will be great ! TIA

Edit: Here is a short testing video, it's clearer than a thousand words lol
Short demo

Edit more: Here is the full class I made, thanks to all of them for this, it's really fast.

using Avalonia;
using Avalonia.Controls.Shapes;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using Ready2Play.BitmapFilters.GaussianBlur.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Tmds.DBus;

namespace Ready2Play.BitmapFilters.GaussianBlur
{
    ///
    /// Ported To Avalonia Bitmap by me.
    ///
    /// Original source:
    /// https://github.com/mdymel/superfastblur
    /// Based on an article of Ivan Kuckir:
    /// http://blog.ivank.net/fastest-gaussian-blur.html
    ///
    public class BitmapFilterGaussianBlur : IBitmapFilterGaussianBlur
    {
        private int[] _alpha;
        private int[] _red;
        private int[] _green;
        private int[] _blue;

        private int _width;
        private int _height;

        private Vector _dpi;

        private readonly ParallelOptions _pOptions = new ParallelOptions { MaxDegreeOfParallelism = 16 };

        public void CreateFrom(string filePath)
        {
            // TODO
            throw new NotImplementedException();
        }

        public unsafe void CreateFrom(IBitmap bitmap)
        {
            using (var memoryStream = new MemoryStream())
            {
                bitmap.Save(memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);
                var writeableBitmap = WriteableBitmap.Decode(memoryStream);
                using var lockedBitmap = writeableBitmap.Lock();

                int* bmpPtr = (int*)lockedBitmap.Address;
                _width = writeableBitmap.PixelSize.Width;
                _height = writeableBitmap.PixelSize.Height;
                _dpi = writeableBitmap.Dpi;

                _alpha = new int[_width * _height];
                _red = new int[_width * _height];
                _green = new int[_width * _height];
                _blue = new int[_width * _height];

                Parallel.For(0, _width * _height, _pOptions, (i, parallelLoopState) =>
                {
                    _alpha[i] = (int)((*(bmpPtr + i) & 0xff000000) >> 24);
                    _red[i] = (*(bmpPtr + i) & 0xff0000) >> 16;
                    _green[i] = (*(bmpPtr + i) & 0x00ff00) >> 8;
                    _blue[i] = *(bmpPtr + i) & 0x0000ff;
                });
            }
        }

        public IBitmap Process(IBitmapFilterGaussianBlurParameter parameter)
        {
            var newAlpha = new int[_width * _height];
            var newRed = new int[_width * _height];
            var newGreen = new int[_width * _height];
            var newBlue = new int[_width * _height];
            var dest = new int[_width * _height];

            Parallel.Invoke(
                () => gaussBlur_4(_alpha, newAlpha, parameter.Radius),
                () => gaussBlur_4(_red, newRed, parameter.Radius),
                () => gaussBlur_4(_green, newGreen, parameter.Radius),
                () => gaussBlur_4(_blue, newBlue, parameter.Radius));

            Parallel.For(0, dest.Length, _pOptions, i =>
            {
                //Math.Max(Math.Min(value, 255), 0)
                if (newAlpha[i] > 255) newAlpha[i] = 255;
                if (newRed[i] > 255) newRed[i] = 255;
                if (newGreen[i] > 255) newGreen[i] = 255;
                if (newBlue[i] > 255) newBlue[i] = 255;

                if (newAlpha[i] < 0) newAlpha[i] = 0;
                if (newRed[i] < 0) newRed[i] = 0;
                if (newGreen[i] < 0) newGreen[i] = 0;
                if (newBlue[i] < 0) newBlue[i] = 0;

                dest[i] = (int)((uint)(newAlpha[i] << 24) | (uint)(newRed[i] << 16) | (uint)(newGreen[i] << 8) | (uint)newBlue[i]);
            });

            var size = new PixelSize(_width, _height);
            var writeableBitmap = new WriteableBitmap(size, _dpi);
            using var lockedBitmap = writeableBitmap.Lock();
            Marshal.Copy(dest, 0, lockedBitmap.Address, dest.Length);
            return writeableBitmap;
        }

        private void gaussBlur_4(int[] source, int[] dest, int r)
        {
            var bxs = boxesForGauss(r, 3);
            boxBlur_4(source, dest, _width, _height, (bxs[0] - 1) / 2);
            boxBlur_4(dest, source, _width, _height, (bxs[1] - 1) / 2);
            boxBlur_4(source, dest, _width, _height, (bxs[2] - 1) / 2);
        }

        private int[] boxesForGauss(int sigma, int n)
        {
            var wIdeal = Math.Sqrt(12 * sigma * sigma / n + 1);
            var wl = (int)Math.Floor(wIdeal);
            if (wl % 2 == 0) wl--;
            var wu = wl + 2;

            var mIdeal = (double)(12 * sigma * sigma - n * wl * wl - 4 * n * wl - 3 * n) / (-4 * wl - 4);
            var m = Math.Round(mIdeal);

            var sizes = new List<int>();
            for (var i = 0; i < n; i++) sizes.Add(i < m ? wl : wu);
            return sizes.ToArray();
        }

        private void boxBlur_4(int[] source, int[] dest, int w, int h, int r)
        {
            for (var i = 0; i < source.Length; i++) dest[i] = source[i];
            boxBlurH_4(dest, source, w, h, r);
            boxBlurT_4(source, dest, w, h, r);
        }

        private void boxBlurH_4(int[] source, int[] dest, int w, int h, int r)
        {
            var iar = (double)1 / (r + r + 1);
            Parallel.For(0, h, _pOptions, i =>
            {
                var ti = i * w;
                var li = ti;
                var ri = ti + r;
                var fv = source[ti];
                var lv = source[ti + w - 1];
                var val = (r + 1) * fv;
                for (var j = 0; j < r; j++) val += source[ti + j];
                for (var j = 0; j <= r; j++)
                {
                    val += source[ri++] - fv;
                    dest[ti++] = (int)Math.Round(val * iar);
                }
                for (var j = r + 1; j < w - r; j++)
                {
                    val += source[ri++] - dest[li++];
                    dest[ti++] = (int)Math.Round(val * iar);
                }
                for (var j = w - r; j < w; j++)
                {
                    val += lv - source[li++];
                    dest[ti++] = (int)Math.Round(val * iar);
                }
            });
        }

        private void boxBlurT_4(int[] source, int[] dest, int w, int h, int r)
        {
            var iar = (double)1 / (r + r + 1);
            Parallel.For(0, w, _pOptions, i =>
            {
                var ti = i;
                var li = ti;
                var ri = ti + r * w;
                var fv = source[ti];
                var lv = source[ti + w * (h - 1)];
                var val = (r + 1) * fv;
                for (var j = 0; j < r; j++) val += source[ti + j * w];
                for (var j = 0; j <= r; j++)
                {
                    val += source[ri] - fv;
                    dest[ti] = (int)Math.Round(val * iar);
                    ri += w;
                    ti += w;
                }
                for (var j = r + 1; j < h - r; j++)
                {
                    val += source[ri] - source[li];
                    dest[ti] = (int)Math.Round(val * iar);
                    li += w;
                    ri += w;
                    ti += w;
                }
                for (var j = h - r; j < h; j++)
                {
                    val += lv - source[li];
                    dest[ti] = (int)Math.Round(val * iar);
                    li += w;
                    ti += w;
                }
            });
        }
    }
}

More:

// TODO TEST UpdateLines in parallel - Is it OK ?
/*var bench = SimpleBench.Start();*/
//      System.NullReferenceException
//HResult = 0x80004003
//Message = Object reference not set to an instance of an object.
//Source = Avalonia.Base
//Arborescence des appels de procédure:
//      à Avalonia.Utilities.WeakHashList`1.GetAlive(Func`1 factory)
// à Avalonia.Utilities.WeakEvent`2.Subscription.OnEvent(Object sender, TEventArgs eventArgs)
// à Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcherLineDetails.set_IsRunning(Boolean value) dans E:\Devel\Ready2Play.NET6\Ready2Play\Ready2PlayGamesLibrary\CommunityToolkit.Mvvm.SourceGenerators\CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator\Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcherLineDetails.g.cs :ligne 140
//        System.AggregateException
//        HResult = 0x80131500
//  Message = One or more errors occurred. (Object reference not set to an instance of an object.) (Object reference not set to an instance of an object.) (Entry point was not found.) (Entry point was not found.) (Entry point was not found.) (Entry point was not found.) (Object reference not set to an instance of an object.) (Entry point was not found.) (Object reference not set to an instance of an object.) (Entry point was not found.) (Entry point was not found.) (Entry point was not found.) (Entry point was not found.) (Entry point was not found.) (Object reference not set to an instance of an object.) (Object reference not set to an instance of an object.)
//  Source = System.Threading.Tasks.Parallel
//  Arborescence des appels de procédure:
//        à System.Threading.Tasks.TaskReplicator.Run[TState](ReplicatableUserAction`1 action, ParallelOptions options, Boolean stopOnFirstFailure)
//   à System.Threading.Tasks.Parallel.PartitionerForEachWorker[TSource, TLocal](Partitioner`1 source, ParallelOptions parallelOptions, Action`1 simpleBody, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
//-- - Fin de la trace de la pile à partir de l'emplacement précédent ---
//   à System.Threading.Tasks.Parallel.ThrowSingleCancellationExceptionOrOtherException(ICollection exceptions, CancellationToken cancelToken, Exception otherException)
//   à System.Threading.Tasks.Parallel.PartitionerForEachWorker[TSource, TLocal](Partitioner`1 source, ParallelOptions parallelOptions, Action`1 simpleBody, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
//   à System.Threading.Tasks.Parallel.ForEachWorker[TSource, TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
//   à System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body)
//   à Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcher.RefreshLoadedLines() dans E:\Devel\Ready2Play.NET6\Ready2Play\Ready2PlayGamesLibrary\ProcessWatcher\ProcessWatcher.cs :ligne 286
//   à Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcher.<> c__DisplayClass18_0.< RefreshLoadedLines > b__3(Object stateInfo) dans E:\Devel\Ready2Play.NET6\Ready2Play\Ready2PlayGamesLibrary\ProcessWatcher\ProcessWatcher.cs :ligne 283
//   à System.Threading.TimerQueueTimer.<> c.<.cctor > b__27_0(Object state)
//   à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)

//  Cette exception a été levée à l'origine dans cette pile des appels :
//    [Code externe]
//    Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcherLineDetails.IsRunning.set(bool) dans Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcherLineDetails.g.cs
//    Ready2PlayGamesLibrary.ProcessWatcher.ProcessWatcher.RefreshLoadedLines.AnonymousMethod__2(Ready2PlayGamesLibrary.ProcessWatcher.Interfaces.IProcessWatcherLineDetails) dans ProcessWatcher.cs
//    [Code externe]

//Exception interne 1 :
//NullReferenceException: Object reference not set to an instance of an object.

//Parallel.ForEach<IProcessWatcherLineDetails>(AllLinesDetails, _pOptions, (ld) =>
//        {
//            // Check if we know a process by this name
//             ld.IsRunning = false;

//            // In this case EnsureIsRightProcess can be stripped down to gain performance
//            var p = correspondingProcesses.FirstOrDefault(p => EnsureIsRightProcess(p, lineDetailsExecutableList, ld.ExecutableFullName));
//            if (p is not null)
//            {
//                ld.Process = p;
//                ld.IsRunning = !ld.HasExited || ld.Responding;
//            }

//            // Manage game state
//            if (ld.Parent.Parent is IGame game)
//{
//    var oldState = game.State;

//    // Killing an application makes this state prioritized as it's being controlled in the lineDetail itself
//    var newState = GameState.Killing;
//    if (!ld.Parent.IsOneKilling)
//        newState = ld.Parent.IsOneRunning ? GameState.Running : (!ld.IsRunning && oldState != GameState.Loading) ? GameState.Available : oldState;

//    if (oldState != newState)
//    {
//        ((IWritableGameState)game).WriteState = newState;
//    }
//}
//        });

Ok, I have commented those lines in my code to check later. But that the same thing. Am I misunderstanding Parallel.For ? Because if I replace it by a simple for each it works nice.


问:
Display a local character set in CHotKeyCtrl
Is it possible to display all local characters in CHotKeyCtrl MFC control using local keyboard layout, e.g. Arabic or Cyrillic? Currently it displays only English characters when I press following keys.

I tried to handle EN_CHANGE event to replace displayed text, but I didn't find any method for this purpose.


问:
Is there a way to secure whole swashbuckle UI, not just call api?
I setup swashbuckle azure AD authentication and everything works (i.e. if I click authorise button, I can trigger Azure AD authentication and get token back to call the api).

I am wondering if there is a way to secure the whole page (i.e. as soon as the swagger UI page is loaded, it will automatically pick the selected scope and authenticate against azure AD)?

The idea is that only people that has a valid AD account can see the API definition and try thing out. With my swashbuckle implementation, seems everyone can see the API definition and only people passing authentication can try it.

This is my code so far:
Service config:

```<code>AddSwaggerGen(
                    c =>
                    {
                        c.ExampleFilters();

                        Dictionary<string, string> scopes = new Dictionary<string, string>
                        {
                            { "XXXX", "XXXX" }
                        };
                        c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                        {
                            Type = SecuritySchemeType.OAuth2,
                            Flows = new OpenApiOAuthFlows
                            {
                                Implicit = new OpenApiOAuthFlow
                                {
                                    AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{_appSettings.AzureActiveDirectoryTenant}/oauth2/v2.0/authorize"),
                                    TokenUrl = new Uri($"https://login.microsoftonline.com/{_appSettings.AzureActiveDirectoryTenant}/oauth2/v2.0/token"),
                                    Scopes = scopes

                                }
                            },
                            In = ParameterLocation.Header,
                            Name = "Authorization",
                             BearerFormat= "JWT",
                            Scheme = "bearer",
                        });
                        c.AddSecurityRequirement(new OpenApiSecurityRequirement
                        {
                            {
                                new OpenApiSecurityScheme
                                {
                                    Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
                                },
                                scopes.Keys.ToList()
                            }
                        });
                        c.OperationFilter<SecurityRequirementsOperationFilter>();

                    }
                )
</code>```

Then on UI:

```<code>app.UseSwagger();
app.UseSwaggerUI(
     c => {
          c.OAuthClientId(_appSettings.ThunderClientId);
          c.OAuthUsePkce();
          c.OAuthScopeSeparator(" ");
          }
        )
</code>```

Body:
I setup swashbuckle azure AD authentication and everything works (i.e. if I click authorise button, I can trigger Azure AD authentication and get token back to call the api).

I am wondering if there is a way to secure the whole page (i.e. as soon as the swagger UI page is loaded, it will automatically pick the selected scope and authenticate against azure AD)?

The idea is that only people that has a valid AD account can see the API definition and try thing out. With my swashbuckle implementation, seems everyone can see the API definition and only people passing authentication can try it.

This is my code so far:
Service config:

AddSwaggerGen(
                    c =>
                    {
                        c.ExampleFilters();

                        Dictionary<string, string> scopes = new Dictionary<string, string>
                        {
                            { "XXXX", "XXXX" }
                        };
                        c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                        {
                            Type = SecuritySchemeType.OAuth2,
                            Flows = new OpenApiOAuthFlows
                            {
                                Implicit = new OpenApiOAuthFlow
                                {
                                    AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{_appSettings.AzureActiveDirectoryTenant}/oauth2/v2.0/authorize"),
                                    TokenUrl = new Uri($"https://login.microsoftonline.com/{_appSettings.AzureActiveDirectoryTenant}/oauth2/v2.0/token"),
                                    Scopes = scopes

                                }
                            },
                            In = ParameterLocation.Header,
                            Name = "Authorization",
                             BearerFormat= "JWT",
                            Scheme = "bearer",
                        });
                        c.AddSecurityRequirement(new OpenApiSecurityRequirement
                        {
                            {
                                new OpenApiSecurityScheme
                                {
                                    Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
                                },
                                scopes.Keys.ToList()
                            }
                        });
                        c.OperationFilter<SecurityRequirementsOperationFilter>();

                    }
                )

Then on UI:

app.UseSwagger();
app.UseSwaggerUI(
     c => {
          c.OAuthClientId(_appSettings.ThunderClientId);
          c.OAuthUsePkce();
          c.OAuthScopeSeparator(" ");
          }
        )


问:
Next JS 13 progress indicator not working
I'm trying to implement progress loader to my next js app dir. but for some reason it's not working. is there a way that i can implement progress loader to my next JS app dir?

i'm using NextNProgress package and added the following to my / layout.

```<code>"use client";
import { ChakraProvider } from "@chakra-ui/react";
import "../styles/globals.css";
import NextNProgress from "nextjs-progressbar";
import { wrapper } from "../store";
import { Progress } from "@chakra-ui/react";

function RootLayout({ children }) {
  return (
    <html>
      <head />
      <body className="max-w-7xl mx-auto">
        <NextNProgress color="#06373a" />
        <ChakraProvider>{children}</ChakraProvider>
      </body>
    </html>
  );
}

export default wrapper.withRedux(RootLayout);
</code>```

please show me any kind of approach to make this happen.

Body:
I'm trying to implement progress loader to my next js app dir. but for some reason it's not working. is there a way that i can implement progress loader to my next JS app dir?

i'm using NextNProgress package and added the following to my / layout.

"use client";
import { ChakraProvider } from "@chakra-ui/react";
import "../styles/globals.css";
import NextNProgress from "nextjs-progressbar";
import { wrapper } from "../store";
import { Progress } from "@chakra-ui/react";

function RootLayout({ children }) {
  return (

        <NextNProgress color="#06373a" />
        <ChakraProvider>{children}</ChakraProvider>

  );
}

export default wrapper.withRedux(RootLayout);

please show me any kind of approach to make this happen.


问:
Pass Value from Binding to Converter in ElementStyle
I have a DataGrid where I'm setting the ElementStyle on multiple columns.  I would like the style to turn the Foreground of the text in the column to red if it is negative.  My converter work when I set it on each column and specify the Value, in the example below, 'Imbalance' has the numeric value that is sent to the converter to change it to red if it's negative.  Of course every column I use this style on has a different Binding property (Imbalance, Supply, Scheduled).

How do I use a style in my resources to accomplish this vs. specifying the converter with the property name on every column?

```<code>ElementStyle="{StaticResource NomVolumeStyle}"

<Style x:Key="NomVolumeStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="TextAlignment" Value="Right" />
        <Setter Property="Foreground" Value="{Binding Imbalance, Converter={StaticResource NegativeNumberColorConverter}}" />
    </Style>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a DataGrid where I'm setting the ElementStyle on multiple columns.  I would like the style to turn the Foreground of the text in the column to red if it is negative.  My converter work when I set it on each column and specify the Value, in the example below, 'Imbalance' has the numeric value that is sent to the converter to change it to red if it's negative.  Of course every column I use this style on has a different Binding property (Imbalance, Supply, Scheduled).

How do I use a style in my resources to accomplish this vs. specifying the converter with the property name on every column?

ElementStyle="{StaticResource NomVolumeStyle}"


问:
Wrong position click on model AR.js
When I show a model with the marker and try to click on it from the mobile, it detects the click in an incorrect position. I've tried everything but it doesn't work.
Here's a code example:</p>
```<code>AFRAME.registerComponent('modelo', {
        init: function () {
          var el = this.el;
          var model = document.querySelector("#bowser-model");
          model.addEventListener('click', (e) => {
            console.log("clickk");
          });
        }
      });

<body style='margin : 0px; overflow: hidden; font-family: Monospace;'>
    <div id="footer"></div>
    <a-scene id="esc" embedded arjs='debugUIEnabled: false; sourceType: webcam' vr-mode-ui='enabled: false' gesture-detector color-randomizer >
        <a-assets timeout="30000">
            <a-asset-item id="spinosaurus" src="../assets/Bueno Posicion.glb" ></a-asset-item>
            <a-asset-item id="cobalto" src="../assets/Cobalto.glb" ></a-asset-item>
            <a-asset-item id="Hierro" src="../assets/Hierro.glb" ></a-asset-item>
            <a-asset-item id="azufre" src="../assets/Azufre.glb" ></a-asset-item>
            <a-asset-item id="niquel" src="../assets/Niquel.glb" ></a-asset-item>
            <a-asset-item id="bowser" src="https://cdn.glitch.com/06bd98b4-97ee-4c07-a546-fe39ca205034%2Fbowser.glb"></a-asset-item>
              <!-- Esto es un comentario  position="-1 0 1"-->
        </a-assets>
    <!--    <a-entity cursor="rayOrigin: mouse" raycaster="objects: .intersectable; useWorldCoordinates: true;"></a-entity>-->

    <a-marker
        type='pattern' url='../assets/pattern-Willamette.patt'
        raycaster="objects: .clickable"
        emitevents="true"
        cursor="fuse: false; rayOrigin: mouse;"
        id="markerA" >
        <a-entity
            id="bowser-model"
            gltf-model="#spinosaurus"
            position="0 -1 0"
            scale="2 2 2"
            class="clickable"
            rotation="0 90 90" >
        </a-entity>
</a-marker>
<a-entity camera></a-entity>
    </a-scene>
</body>

</code>```

Title: Wrong position click on model AR.js

Body:
When I show a model with the marker and try to click on it from the mobile, it detects the click in an incorrect position. I've tried everything but it doesn't work.
Here's a code example:

AFRAME.registerComponent('modelo', {
        init: function () {
          var el = this.el;
          var model = document.querySelector("#bowser-model");
          model.addEventListener('click', (e) => {
            console.log("clickk");
          });
        }
      });


问:
Get raw request body in CakePHP request
In CakePHP 4 you can access the array of JSON POST data in $this->getRequest()->getData(). This is fine to access the data. However, we need to verify a signature that is also based on the POST data. The getData() array is already processed data and therefore does not match the signature based on the original string data of the request. How can I access the orginal string body that was used in an HTTP POST request to verify a signature?

```<code>$data = file_get_contents('php://input');
</code>```

This is wat we need. But the $data variable is empty in unit tests.

A workaround could be to recreate the json:

```<code>$json = json_encode($this->getRequest()->getData(), true)
</code>```

But if the original string data contains new lines, spaces, ... this will not match the orignal body.

Title: Get raw request body in CakePHP request

Body:
In CakePHP 4 you can access the array of JSON POST data in $this->getRequest()->getData(). This is fine to access the data. However, we need to verify a signature that is also based on the POST data. The getData() array is already processed data and therefore does not match the signature based on the original string data of the request. How can I access the orginal string body that was used in an HTTP POST request to verify a signature?

$data = file_get_contents('php://input');

This is wat we need. But the $data variable is empty in unit tests.

A workaround could be to recreate the json:

$json = json_encode($this->getRequest()->getData(), true)

But if the original string data contains new lines, spaces, ... this will not match the orignal body.


问:
Get resource usage of more than one SQL instance on a machine
On my machine, I have two SQL instances (Instance A and Instance B).
If i had only one SQL instance, I could get the resource usage like CPU for example by using the process name
i.e

```<code>var cpu = new PerformanceCounter("Process", "% Processor Time", myProccessName, true);
</code>```

However, in case of two SQL instances, although they have two different process ID, the process name for both of them is the same 'sqlserver'

Finding the process ID is easy, how can I use the PerformanceCounter to return the cpu/ram value based on the process ID?

Any other way I can use to get the CPU/RAM usage of all SQL instances installed on the same machine?

Body:
On my machine, I have two SQL instances (Instance A and Instance B).
If i had only one SQL instance, I could get the resource usage like CPU for example by using the process name
i.e

var cpu = new PerformanceCounter("Process", "% Processor Time", myProccessName, true);

However, in case of two SQL instances, although they have two different process ID, the process name for both of them is the same 'sqlserver'

Finding the process ID is easy, how can I use the PerformanceCounter to return the cpu/ram value based on the process ID?

Any other way I can use to get the CPU/RAM usage of all SQL instances installed on the same machine?