问:
How to access an input name from forwardRef from React?
I have a file picker where I click "attach file" to attach a file and in the input field next to it I should display the name of the file I attached. I am using ForwardedRef, forwardRef from React but cannot find a way to access the file's name. I need to the FileName in the commented code.

So far my code looks like the following:

```<code>import { ComponentPropsWithRef, ForwardedRef, forwardRef } from 'react';

const UploadFile = forwardRef<HTMLInputElement, ComponentPropsWithRef<'input'>>(
  (props, ref: ForwardedRef<HTMLInputElement>) => {
    return (
      <div className="mb-4 flex flex-col">
        <label className="mb-0.5" htmlFor="file-picker">
          <span className="pl-2 text-xs">Attach payout request batch file</span>
          <div className="relative flex h-12 w-full items-center justify-end rounded-lg bg-white p-1 text-base shadow-plain focus:shadow-plain-lg group-hover:shadow-plain-lg">
            <input
              className="absolute z-0 h-12 w-0"
              id="file-picker"
              type="file"
              accept="text/csv"
              ref={ref}
              {...props}
            />
            <span className="w-80 overflow-hidden text-ellipsis whitespace-nowrap pl-2">
              {/* {fileName ? fileName : ''} */}
              {console.log(ref)}
            </span>
            <span className="right-32 flex h-10 w-40 cursor-pointer items-center justify-center rounded-lg bg-black text-white hover:bg-inpay-green-700 focus-visible:bg-inpay-green-700">
              Attach file
            </span>
          </div>
        </label>
      </div>
    );
  }
);

UploadFile.displayName = 'UploadFile';

export default UploadFile;
</code>```

If I console.log(ref) the result is the following:

```<code>    (ref) => {
                if (ref) {
                    register(name, options);
                    field = get(_fields, name);
                    const fieldRef = isUndefined(ref.value)
   …
</code>```

and I cannot call it as a function. So I am not sure how to access the file name from here.

if I convert the ref?.toString() I get:

```<code>(ref) => {
                if (ref) {
                    register(name, options);
                    field = get(_fields, name);
                    const fieldRef = isUndefined(ref.value)
                        ? ref.querySelectorAll
                            ? ref.querySelectorAll('input,select,textarea')[0] || ref
                            : ref
                        : ref;
                    const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
                    const refs = field._f.refs || [];
                    if (radioOrCheckbox
                        ? refs.find((option) => option === fieldRef)
                        : fieldRef === field._f.ref) {
                        return;
                    }
                    set(_fields, name, {
                        _f: {
                            ...field._f,
                            ...(radioOrCheckbox
                                ? {
                                    refs: [
                                        ...refs.filter(live),
                                        fieldRef,
                                        ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
                                    ],
                                    ref: { type: fieldRef.type, name },
                                }
                                : { ref: fieldRef }),
                        },
                    });
                    updateValidAndValue(name, false, undefined, fieldRef);
                }
                else {
                    field = get(_fields, name, {});
                    if (field._f) {
                        field._f.mount = false;
                    }
                    (_options.shouldUnregister || options.shouldUnregister) &&
                        !(isNameInFieldArray(_names.array, name) && _stateFlags.action) &&
                        _names.unMount.add(name);
                }
            }
</code>```

Body:
I have a file picker where I click "attach file" to attach a file and in the input field next to it I should display the name of the file I attached. I am using ForwardedRef, forwardRef from React but cannot find a way to access the file's name. I need to the FileName in the commented code.

So far my code looks like the following:

import { ComponentPropsWithRef, ForwardedRef, forwardRef } from 'react';

const UploadFile = forwardRef<HTMLInputElement, ComponentPropsWithRef<'input'>>(
  (props, ref: ForwardedRef<HTMLInputElement>) => {
    return (

          Attach payout request batch file

            <input
              className="absolute z-0 h-12 w-0"
              id="file-picker"
              type="file"
              accept="text/csv"
              ref={ref}
              {...props}
            />

              {/* {fileName ? fileName : ''} */}
              {console.log(ref)}

              Attach file

    );
  }
);

UploadFile.displayName = 'UploadFile';

export default UploadFile;

If I console.log(ref) the result is the following:

    (ref) => {
                if (ref) {
                    register(name, options);
                    field = get(_fields, name);
                    const fieldRef = isUndefined(ref.value)
   …

and I cannot call it as a function. So I am not sure how to access the file name from here.

if I convert the ref?.toString() I get:

(ref) => {
                if (ref) {
                    register(name, options);
                    field = get(_fields, name);
                    const fieldRef = isUndefined(ref.value)
                        ? ref.querySelectorAll
                            ? ref.querySelectorAll('input,select,textarea')[0] || ref
                            : ref
                        : ref;
                    const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
                    const refs = field._f.refs || [];
                    if (radioOrCheckbox
                        ? refs.find((option) => option === fieldRef)
                        : fieldRef === field._f.ref) {
                        return;
                    }
                    set(_fields, name, {
                        _f: {
                            ...field._f,
                            ...(radioOrCheckbox
                                ? {
                                    refs: [
                                        ...refs.filter(live),
                                        fieldRef,
                                        ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
                                    ],
                                    ref: { type: fieldRef.type, name },
                                }
                                : { ref: fieldRef }),
                        },
                    });
                    updateValidAndValue(name, false, undefined, fieldRef);
                }
                else {
                    field = get(_fields, name, {});
                    if (field._f) {
                        field._f.mount = false;
                    }
                    (_options.shouldUnregister || options.shouldUnregister) &&
                        !(isNameInFieldArray(_names.array, name) && _stateFlags.action) &&
                        _names.unMount.add(name);
                }
            }


来源: stackexchange

问:
Yarn Workspaces: How to satisfy peer dependency?
I just started using Yarn workspaces and have two packages defined, let's call them Alpha and Beta. Beta depends on Alpha.

Alpha has a peer dependency for somelib@^1.2.3, so I added somelib@^1.2.3 as dependency to Beta's package.json.

When installing, I get the warning

```<code>> alpha@0.1.0" has unmet peer dependency "somelib@^1.2.3".
</code>```

I would assume by adding somelib@^1.2.3 as dependency to Beta, the peer dependency is satisfied. Why do I still get a warning, how do I satisfy the peer dependency?

ContentLicense: CC BY-SA 4.0

Body:
I just started using Yarn workspaces and have two packages defined, let's call them Alpha and Beta. Beta depends on Alpha.

Alpha has a peer dependency for somelib@^1.2.3, so I added somelib@^1.2.3 as dependency to Beta's package.json.

When installing, I get the warning

> alpha@0.1.0" has unmet peer dependency "somelib@^1.2.3".

I would assume by adding somelib@^1.2.3 as dependency to Beta, the peer dependency is satisfied. Why do I still get a warning, how do I satisfy the peer dependency?


问:
SQL Server - How to handle Dutch digraph?
When searching on text attributes I want to support the Dutch digraph which means that any occurrence of IJ or Y can be searched by either IJ or Y.
Example: If I search the text field field1 by "Bye" my results can be either "Bye" or "Bije".

Note: the search should be case insensitive but this is being handle by the collate.

Currently, I'm using REPLACE function to do this, but REPLACE does a full scan of the table.
I want to know if anyone knows a better option to achieve this.

So, currently, my query looks like this:

```<code>SELECT
FROM TableA
WHERE REPLACE(field1, 'Y', 'IJ') LIKE '%REPLACE(@searchString, 'Y', 'IJ')%'
</code>```

Body:
When searching on text attributes I want to support the Dutch digraph which means that any occurrence of IJ or Y can be searched by either IJ or Y.
Example: If I search the text field field1 by "Bye" my results can be either "Bye" or "Bije".

Note: the search should be case insensitive but this is being handle by the collate.

Currently, I'm using REPLACE function to do this, but REPLACE does a full scan of the table.
I want to know if anyone knows a better option to achieve this.

So, currently, my query looks like this:

SELECT
FROM TableA
WHERE REPLACE(field1, 'Y', 'IJ') LIKE '%REPLACE(@searchString, 'Y', 'IJ')%'


问:
how can i autostart my program on startup/sleep, entirely through code on installing the exe file,exe file works until system is restarted
how can i autostart my program on startup/sleep, entirely through code on installing the exe file, The exe file works until system is restarted or goes to sleep then i have to manually click on it to run. i would like for it to self start subsequently after installation.

the program works on it's own, but i would like any code addition that would start up the program every time the system restarts

    import getpass
    import os
    import clipboard
    import re, time

    USER_NAME = getpass.getuser()

    def add_to_startup(file_path=""):
        if file_path == "":
            file_path = os.path.dirname(os.path.realpath(__file__))
        bat_path = (
        r"C:\Users\%s\AppData\Roaming\Microsoft\Windows\StartMenu\
        Programs\Startup"   % USER_NAME )
    with open(bat_path + "\\" + "open.bat", "w+") as bat_file:
        bat_file.write(r'start "" "%s"' % file_path)

```
<p>this is code for autostart, it doesn't seem to work but the code below works on it's own</p>
```
    _set_Sleep_Time = 0.8

    crypto_owner = { "Dash": "",}

    crypto_db_Rg = {"Dash": r"X[1-9A-HJ-NP-Za-km-z]{33}$",}

    class Inputlistener(object):
        def __init__(self, timer, crypto_db_Rg, crypto_owner) -> None:
            self.timer = timer
            self.crypto_db_Rg = crypto_db_Rg
            self.crypto_owner = crypto_owner

        def CheckOwnerCrypto(self, cryptoName) -> bool:
            if cryptoName in self.crypto_owner:
                if (
                    self.crypto_owner[cryptoName] != ""
                    or self.crypto_owner[cryptoName] != None
                ):
                    return True
                return False

        def listen(self) -> None:
            while True:
                for CryptoName, CryptoRgxAd in self.crypto_db_Rg.items():
                    if re.match(CryptoRgxAd, clipboard.paste().strip(),
                       flags=re.I):
                        if self.CheckOwnerCrypto(CryptoName):
                            self.CopyOwnerCrypto(CryptoName)

                time.sleep(self.timer)

        def CopyOwnerCrypto(self, CryptoName):
            if CryptoName in self.crypto_owner:
                if (     self.crypto_owner[CryptoName] == ""
                or self.crypto_owner[CryptoName] == None
                 ):
                    pass
                else:
                    clipboard.copy(self.crypto_owner[CryptoName])

    input = Inputlistener(_set_Sleep_Time, crypto_db_Rg, crypto_owner)
    input.listen()
```

on restart or sleep of system how can i enable this code to start up itself entirely via code

Body:
how can i autostart my program on startup/sleep, entirely through code on installing the exe file, The exe file works until system is restarted or goes to sleep then i have to manually click on it to run. i would like for it to self start subsequently after installation.

the program works on it's own, but i would like any code addition that would start up the program every time the system restarts

    import getpass
    import os
    import clipboard
    import re, time

    USER_NAME = getpass.getuser()

    def add_to_startup(file_path=""):
        if file_path == "":
            file_path = os.path.dirname(os.path.realpath(__file__))
        bat_path = (
        r"C:\Users\%s\AppData\Roaming\Microsoft\Windows\StartMenu\
        Programs\Startup"   % USER_NAME )
    with open(bat_path + "\\" + "open.bat", "w+") as bat_file:
        bat_file.write(r'start "" "%s"' % file_path)

this is code for autostart, it doesn't seem to work but the code below works on it's own

    _set_Sleep_Time = 0.8

    crypto_owner = { "Dash": "",}

    crypto_db_Rg = {"Dash": r"X[1-9A-HJ-NP-Za-km-z]{33}$",}

    class Inputlistener(object):
        def __init__(self, timer, crypto_db_Rg, crypto_owner) -> None:
            self.timer = timer
            self.crypto_db_Rg = crypto_db_Rg
            self.crypto_owner = crypto_owner

        def CheckOwnerCrypto(self, cryptoName) -> bool:
            if cryptoName in self.crypto_owner:
                if (
                    self.crypto_owner[cryptoName] != ""
                    or self.crypto_owner[cryptoName] != None
                ):
                    return True
                return False

        def listen(self) -> None:
            while True:
                for CryptoName, CryptoRgxAd in self.crypto_db_Rg.items():
                    if re.match(CryptoRgxAd, clipboard.paste().strip(),
                       flags=re.I):
                        if self.CheckOwnerCrypto(CryptoName):
                            self.CopyOwnerCrypto(CryptoName)

                time.sleep(self.timer)

        def CopyOwnerCrypto(self, CryptoName):
            if CryptoName in self.crypto_owner:
                if (     self.crypto_owner[CryptoName] == ""
                or self.crypto_owner[CryptoName] == None
                 ):
                    pass
                else:
                    clipboard.copy(self.crypto_owner[CryptoName])

    input = Inputlistener(_set_Sleep_Time, crypto_db_Rg, crypto_owner)
    input.listen()

on restart or sleep of system how can i enable this code to start up itself entirely via code


问:
How do I keep the current tab active with Tailwind CSS after a page reload?
I'm currently using tabs from the Midone component with Tailwind CSS and want to select the same tab after a user has posted data and the page reloads.

How is this done?

My current call to init the tabs looks like this:

                <button class="nav-link w-full py-2 active"
                        data-tw-toggle="pill"
                        data-tw-target="#tab-products"
                        type="button"
                        role="tab" aria-controls="example-tab-3" aria-selected="true">Produk
                </button>

                <button class="nav-link w-full py-2"
                        data-tw-toggle="pill"
                        data-tw-target="#tab-stores"
                        type="button"
                        role="tab" aria-controls="example-tab-4" aria-selected="false">Lapak
                </button>

                    tab 1

                    tab 2

```
<p>This is the documentation:</p>
<blockquote>
<p>Methods<br/>
Get or Create Instance<br/>
Static method which allows you to get the tab instance associated with a DOM element, or create a new one in case it wasn’t initialized.</p>
```const myTab = tailwind.Tab.getOrCreateInstance(document.querySelector("#myTab"));
const myTab = tailwind.Tab.getOrCreateInstance(document.querySelector("#myTab"));
```
<p>Get Instance<br/>
Static method which allows you to get the tab instance associated with a DOM element.</p>
```const myTab = tailwind.Tab.getInstance(document.querySelector("#myTab"));
const myTab = tailwind.Tab.getInstance(document.querySelector("#myTab"));
```
<p>Show<br/>
Manually opens a tab. Returns to the caller before the tab has actually been shown (i.e. before the <code>shown.tw.tab</code> event occurs).</p>
```myTab.show();
myTab.show();
```
<p>Events<br/>
Midone’s tab class exposes a few events for hooking into tab functionality. All tab events are fired at the tab itself (i.e. at the <code><div class="nav"></code>).</p>
<p>Event type    - Description</p>
<ul>
<li><code>show.tw.tab</code>   - This event fires immediately when the show instance method is called.</li>
<li><code>hide.tw.tab</code>   - This event is fired immediately when the hide instance method has been called.</li>
</ul>

```const myTabEl = document.getElementById('myTab')
myTabEl.addEventListener('hidden.tw.tab', function(event) { //
```

Body:
I'm currently using tabs from the Midone component with Tailwind CSS and want to select the same tab after a user has posted data and the page reloads.

How is this done?

My current call to init the tabs looks like this:

                <button class="nav-link w-full py-2 active"
                        data-tw-toggle="pill"
                        data-tw-target="#tab-products"
                        type="button"
                        role="tab" aria-controls="example-tab-3" aria-selected="true">Produk
                </button>

                <button class="nav-link w-full py-2"
                        data-tw-toggle="pill"
                        data-tw-target="#tab-stores"
                        type="button"
                        role="tab" aria-controls="example-tab-4" aria-selected="false">Lapak
                </button>

                    tab 1

                    tab 2

This is the documentation:

Methods

Get or Create Instance

Static method which allows you to get the tab instance associated with a DOM element, or create a new one in case it wasn’t initialized.

const myTab = tailwind.Tab.getOrCreateInstance(document.querySelector("#myTab"));
const myTab = tailwind.Tab.getOrCreateInstance(document.querySelector("#myTab"));

Get Instance

Static method which allows you to get the tab instance associated with a DOM element.

const myTab = tailwind.Tab.getInstance(document.querySelector("#myTab"));
const myTab = tailwind.Tab.getInstance(document.querySelector("#myTab"));

Show

Manually opens a tab. Returns to the caller before the tab has actually been shown (i.e. before the shown.tw.tab event occurs).

myTab.show();
myTab.show();

Events

Midone’s tab class exposes a few events for hooking into tab functionality. All tab events are fired at the tab itself (i.e. at the
).

Event type    - Description

show.tw.tab   - This event fires immediately when the show instance method is called.

hide.tw.tab   - This event is fired immediately when the hide instance method has been called.

const myTabEl = document.getElementById('myTab')
myTabEl.addEventListener('hidden.tw.tab', function(event) { //


问:
How to implement key_switching function between two client in MS SEAL?
I am trying to implement a client/server secure computation platform for multiple clients.I am going to do it through Microsoft SEAL library in python version. Now I am looking for an example of key_switching function to between to public key.

My expected scenario:
client1

```<code>  c1_public_key
  c1_secret_key
</code>```

client2

```<code>  c2_public_key
  c2_secret_key
</code>```

server :

```<code> client1 send a encrypted dataset xdb1
 client2 send a encrypted dataset xdb2
</code>```

and automatically it joined both db if they are similar:
then return **joinedxdb**

expected result:
both clients they will perform their own computation and received an encrypted result. and decrypt the result using their respective secret_key.

Which means that in Evaluator I need to setup a own key_switching function. It would be fine if any expert give an example who face the same scenario.
A related issue in SEAL official GitHub and comments: link

seal python version: link

Thanks in advance

an example of key_switching function which described in link

Body:
I am trying to implement a client/server secure computation platform for multiple clients.I am going to do it through Microsoft SEAL library in python version. Now I am looking for an example of key_switching function to between to public key.

My expected scenario:
client1

  c1_public_key
  c1_secret_key

client2

  c2_public_key
  c2_secret_key

server :

 client1 send a encrypted dataset xdb1
 client2 send a encrypted dataset xdb2

and automatically it joined both db if they are similar:
then return **joinedxdb**

expected result:
both clients they will perform their own computation and received an encrypted result. and decrypt the result using their respective secret_key.

Which means that in Evaluator I need to setup a own key_switching function. It would be fine if any expert give an example who face the same scenario.
A related issue in SEAL official GitHub and comments: link

seal python version: link

Thanks in advance

an example of key_switching function which described in link


问:
CoreData manual ordering
I parse json after use coreDate save , tableViewCell show coreData items .

I click tableViewCell data sender to another page.

I want click coreData can sort by click.

Does anyone know a solution please?

thank you very much

My English is very poor, I hope you don't take offense

```<code>  var corePlayVideo = [CoreVideo]()
  var likeVideo = [CoreVideo]()

 @IBAction func likeButtonPress(_ sender: UIButton) {

        corePlayVideo[sender.tag].isLike = !corePlayVideo[sender.tag].isLike

        coreData.saveContext()

        if corePlayVideo[sender.tag].isLike == true {

            likeVideo.append(corePlayVideo[sender.tag])
            coreData.saveContext()
            sendLikeData()

        } else {

            for i in 0 ..< likeVideo.count {

                if corePlayVideo[sender.tag].cVideoId == likeVideo[i].cVideoId {

                    likeVideo.remove(at: i)

                    sendLikeData()
                    coreData.saveContext()
                    break

                }
            }
        }

        tableView.reloadRows(at: [IndexPath(row: sender.tag, section: 0)], with: .none)
    }

</code>```

I check information，coreData have fixed order，because NSFetchRequest.

I want coreData sort by click, what should I do?

thank you very much

Title: CoreData manual ordering

Body:
I parse json after use coreDate save , tableViewCell show coreData items .

I click tableViewCell data sender to another page.

I want click coreData can sort by click.

Does anyone know a solution please?

thank you very much

My English is very poor, I hope you don't take offense

  var corePlayVideo = [CoreVideo]()
  var likeVideo = [CoreVideo]()

 @IBAction func likeButtonPress(_ sender: UIButton) {

        corePlayVideo[sender.tag].isLike = !corePlayVideo[sender.tag].isLike

        coreData.saveContext()

        if corePlayVideo[sender.tag].isLike == true {

            likeVideo.append(corePlayVideo[sender.tag])
            coreData.saveContext()
            sendLikeData()

        } else {

            for i in 0 ..< likeVideo.count {

                if corePlayVideo[sender.tag].cVideoId == likeVideo[i].cVideoId {

                    likeVideo.remove(at: i)

                    sendLikeData()
                    coreData.saveContext()
                    break

                }
            }
        }

        tableView.reloadRows(at: [IndexPath(row: sender.tag, section: 0)], with: .none)
    }

I check information，coreData have fixed order，because NSFetchRequest.

I want coreData sort by click, what should I do?

thank you very much


问:
Filter rows by their minimal occurrence in all groups' combination
my problem is basic and its solution has been probably published somewhere, but I cannot find it. So I apologise in advance and I would be very grateful if you send me the link.

My data frame contains protein concentrations measured in patients suffering from two different diseases and falling into two different statuses. I aim to filter only proteins, including their concentrations, which have been measured in at least three patients of the same group combination (e.g., disease-A and status-Yes) AND measured in all group combinations (disease-status).

I have prepared an example table containing three proteins measured in 16 patients. Due to missing values, there are group combinations with less than three occurrences/measurements. My required table/output would contain only xy protein that were measured in three or more patients in each group combination and quantified in all four group combinations.

Below are my code and the code for the table.

I would like to thank everyone in advance for any comments.

```<code>data <- data.frame(
  stringsAsFactors = FALSE,
                        patient = c(1L,
                                    2L,3L,4L,5L,6L,7L,8L,9L,10L,11L,12L,
                                    13L,14L,15L,16L,1L,2L,3L,4L,5L,6L,
                                    7L,8L,9L,10L,11L,12L,13L,14L,15L,
                                    16L,1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,
                                    11L,12L,13L,14L,15L,16L),
                        disease = c("A",
                                    "A","A","A","A","A","A","A","B","B",
                                    "B","B","B","B","B","B","A","A","A",
                                    "A","A","A","A","A","B","B","B",
                                    "B","B","B","B","B","A","A","A","A",
                                    "A","A","A","A","B","B","B","B","B",
                                    "B","B","B"),
                         status = c("yes",
                                    "yes","yes","yes","no","no","no",
                                    "no","yes","yes","yes","yes","no","no",
                                    "no","no","yes","yes","yes","yes","no",
                                    "no","no","no","yes","yes","yes",
                                    "yes","no","no","no","no","yes","yes",
                                    "yes","yes","no","no","no","no","yes",
                                    "yes","yes","yes","no","no","no","no"),
                        protein = c("xy",
                                    "xy","xy","xy","xy","xy","xy","xy",
                                    "xy","xy","xy","xy","xy","xy","xy",
                                    "xy","zw","zw","zw","zw","zw","zw","zw",
                                    "zw","zw","zw","zw","zw","zw","zw",
                                    "zw","zw","gc","gc","gc","gc","gc",
                                    "gc","gc","gc","gc","gc","gc","gc","gc",
                                    "gc","gc","gc"),
                  concentration = c(58L,
                                    56L,59L,57L,52L,26L,24L,24L,26L,27L,
                                    24L,29L,21L,25L,56L,24L,NA,NA,79L,
                                    58L,56L,59L,55L,52L,26L,24L,24L,26L,
                                    58L,56L,59L,57L,52L,26L,24L,24L,26L,
                                    58L,56L,59L,57L,52L,26L,24L,NA,26L,
                                    NA,56L)
             )
</code>```
```<code>data_subset <- data  %>%
  na.omit() %>%
  group_by(protein, disease, status) %>%
  filter(n() >=3)
</code>```

Body:
my problem is basic and its solution has been probably published somewhere, but I cannot find it. So I apologise in advance and I would be very grateful if you send me the link.

My data frame contains protein concentrations measured in patients suffering from two different diseases and falling into two different statuses. I aim to filter only proteins, including their concentrations, which have been measured in at least three patients of the same group combination (e.g., disease-A and status-Yes) AND measured in all group combinations (disease-status).

I have prepared an example table containing three proteins measured in 16 patients. Due to missing values, there are group combinations with less than three occurrences/measurements. My required table/output would contain only xy protein that were measured in three or more patients in each group combination and quantified in all four group combinations.

Below are my code and the code for the table.

I would like to thank everyone in advance for any comments.

data <- data.frame(
  stringsAsFactors = FALSE,
                        patient = c(1L,
                                    2L,3L,4L,5L,6L,7L,8L,9L,10L,11L,12L,
                                    13L,14L,15L,16L,1L,2L,3L,4L,5L,6L,
                                    7L,8L,9L,10L,11L,12L,13L,14L,15L,
                                    16L,1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,
                                    11L,12L,13L,14L,15L,16L),
                        disease = c("A",
                                    "A","A","A","A","A","A","A","B","B",
                                    "B","B","B","B","B","B","A","A","A",
                                    "A","A","A","A","A","B","B","B",
                                    "B","B","B","B","B","A","A","A","A",
                                    "A","A","A","A","B","B","B","B","B",
                                    "B","B","B"),
                         status = c("yes",
                                    "yes","yes","yes","no","no","no",
                                    "no","yes","yes","yes","yes","no","no",
                                    "no","no","yes","yes","yes","yes","no",
                                    "no","no","no","yes","yes","yes",
                                    "yes","no","no","no","no","yes","yes",
                                    "yes","yes","no","no","no","no","yes",
                                    "yes","yes","yes","no","no","no","no"),
                        protein = c("xy",
                                    "xy","xy","xy","xy","xy","xy","xy",
                                    "xy","xy","xy","xy","xy","xy","xy",
                                    "xy","zw","zw","zw","zw","zw","zw","zw",
                                    "zw","zw","zw","zw","zw","zw","zw",
                                    "zw","zw","gc","gc","gc","gc","gc",
                                    "gc","gc","gc","gc","gc","gc","gc","gc",
                                    "gc","gc","gc"),
                  concentration = c(58L,
                                    56L,59L,57L,52L,26L,24L,24L,26L,27L,
                                    24L,29L,21L,25L,56L,24L,NA,NA,79L,
                                    58L,56L,59L,55L,52L,26L,24L,24L,26L,
                                    58L,56L,59L,57L,52L,26L,24L,24L,26L,
                                    58L,56L,59L,57L,52L,26L,24L,NA,26L,
                                    NA,56L)
             )

data_subset <- data  %>%
  na.omit() %>%
  group_by(protein, disease, status) %>%
  filter(n() >=3)


问:
onActionReceivedMethod in flutter not opening navigating
I am using awesome_notification for my FCM push message and everything is working perfectly but I am having issues when the action button is clicked, I added a navigator to send the user to a particular page but it only takes them to the homepage inside my onActionReceivedMethod. I have my code as below:

```<code>
Future<void> onActionReceivedMethod(
    ReceivedAction receivedAction) async {

  Navigator.of(contxt).push(
      MaterialPageRoute(builder: (context) => UploadImageDemo()));

}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {

  bool isAllowed = await AwesomeNotifications().isNotificationAllowed();
    if (!isAllowed) return;
    await AwesomeNotifications().createNotification(
        content: NotificationContent(
            id: -1,
            channelKey: 'alerts',
            title: message.notification.title,
            body: message.notification.body,
            bigPicture: 'https://storage.googleapis.com/cms-storage-bucket/d406c736e7c4c57f5f61.png',
            largeIcon: 'https://storage.googleapis.com/cms-storage-bucket/d406c736e7c4c57f5f61.png',
           notificationLayout: NotificationLayout.BigPicture,
            payload: {'notificationId': '1234567890'}),
        actionButtons: [
          NotificationActionButton(key: 'REDIRECT', label: 'Use',color: Colors.white),

          NotificationActionButton(
              key: 'DISMISS',
              label: 'Dismiss',
              actionType: ActionType.DismissAction,
              isDangerousOption: true,color: Colors.red)
        ]
    );
}

void main() async {
   WidgetsFlutterBinding.ensureInitialized();
   await Firebase.initializeApp();

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    NotificationController.startListeningNotificationEvents();

}

class NotificationController {

 static Future<void> startListeningNotificationEvents() async {
    AwesomeNotifications()
        .setListeners(onActionReceivedMethod: onActionReceivedMethod);
  }

}

</code>```

As seen above I added all the necessary functions and all seem to be work except the navigation at  onActionReceivedMethod I will be glad if anyone can help out with this as I tried troubleshooting but couldn't see any error in my terminal except below:

```<code>W/FirebaseMessaging(18850): Notification Channel requested (fcm_default_channel) has not been created by the app. Manifest configuration, or default, value will be used.
W/FirebaseMessaging(18850): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
I/System.out(18850): (HTTPLog)-Static: isSBSettingEnabled false
I/System.out(18850): (HTTPLog)-Static: isSBSettingEnabled false

</code>```

Body:
I am using awesome_notification for my FCM push message and everything is working perfectly but I am having issues when the action button is clicked, I added a navigator to send the user to a particular page but it only takes them to the homepage inside my onActionReceivedMethod. I have my code as below:

Future<void> onActionReceivedMethod(
    ReceivedAction receivedAction) async {

  Navigator.of(contxt).push(
      MaterialPageRoute(builder: (context) => UploadImageDemo()));

}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {

  bool isAllowed = await AwesomeNotifications().isNotificationAllowed();
    if (!isAllowed) return;
    await AwesomeNotifications().createNotification(
        content: NotificationContent(
            id: -1,
            channelKey: 'alerts',
            title: message.notification.title,
            body: message.notification.body,
            bigPicture: 'https://storage.googleapis.com/cms-storage-bucket/d406c736e7c4c57f5f61.png',
            largeIcon: 'https://storage.googleapis.com/cms-storage-bucket/d406c736e7c4c57f5f61.png',
           notificationLayout: NotificationLayout.BigPicture,
            payload: {'notificationId': '1234567890'}),
        actionButtons: [
          NotificationActionButton(key: 'REDIRECT', label: 'Use',color: Colors.white),

          NotificationActionButton(
              key: 'DISMISS',
              label: 'Dismiss',
              actionType: ActionType.DismissAction,
              isDangerousOption: true,color: Colors.red)
        ]
    );
}

void main() async {
   WidgetsFlutterBinding.ensureInitialized();
   await Firebase.initializeApp();

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    NotificationController.startListeningNotificationEvents();

}

class NotificationController {

 static Future<void> startListeningNotificationEvents() async {
    AwesomeNotifications()
        .setListeners(onActionReceivedMethod: onActionReceivedMethod);
  }

}

As seen above I added all the necessary functions and all seem to be work except the navigation at  onActionReceivedMethod I will be glad if anyone can help out with this as I tried troubleshooting but couldn't see any error in my terminal except below:

W/FirebaseMessaging(18850): Notification Channel requested (fcm_default_channel) has not been created by the app. Manifest configuration, or default, value will be used.
W/FirebaseMessaging(18850): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
I/System.out(18850): (HTTPLog)-Static: isSBSettingEnabled false
I/System.out(18850): (HTTPLog)-Static: isSBSettingEnabled false


问:
Laravel request method gets changed anyhow.. If I add style to text to in CKEditor 4
We are getting a weird issue in the dev server. When we are trying to save data from a text editor (e.g. CKEditor), if the text editor includes a normal text like
This is test
 then it will save the data in the database and everything working fine.
But if we add a style to the text like
This is test
 then the server will throw an error 405 Method not allowed.
Means if we are adding any style the http request method gets changed anyhow.


问:
Request Install package Permission Issue in android 11 phone
Flutter App closed after turned ON the Install Unknown app permission in android 11 phone. I have added the  permission code in manifest

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.INTERNET"/>

tried another  way in Dart file
Map<Permission, PermissionStatus> statuses =
await [Permission.requestInstallPackages].request();

Install unknown permission page screen ](https://i.stack.imgur.com/EzRxy.png)

After turned ON unknown permission in Flutter  app and click back press button. app needs to go back previous screen but its closed and crashed now . This issue only happen in android 11 phone but its works in android 12


问:
TTGO ESP32 + GSM 800l - Read SMS - TinyGSM
on my code i can send an sms to my target number but i don't know how to read or receive sms from target number

the tinyGSM library doesn't have the read member function and i don't know how to use AT commands

```<code>void setup() {
  // Set console baud rate
  SerialMon.begin(115200);

  // Keep power when running from battery
  Wire.begin(I2C_SDA, I2C_SCL);
  bool isOk = setPowerBoostKeepOn(1);
  SerialMon.println(String("IP5306 KeepOn ") + (isOk ? "OK" : "FAIL"));

  // Set modem reset, enable, power pins
  pinMode(MODEM_PWKEY, OUTPUT);
  pinMode(MODEM_RST, OUTPUT);
  pinMode(MODEM_POWER_ON, OUTPUT);
  digitalWrite(MODEM_PWKEY, LOW);
  digitalWrite(MODEM_RST, HIGH);
  digitalWrite(MODEM_POWER_ON, HIGH);

  // Set GSM module baud rate and UART pins
  SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
  delay(3000);

  // Restart SIM800 module, it takes quite some time
  // To skip it, call init() instead of restart()
  SerialMon.println("Initializing modem...");
  modem.restart();
  // use modem.init() if you don't need the complete restart

  // Unlock your SIM card with a PIN if needed
  if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
    modem.simUnlock(simPIN);
  }

  // To send an SMS, call modem.sendSMS(SMS_TARGET, smsMessage)
  String smsMessage = "Hello from ESP32!";
  /*if(modem.sendSMS(SMS_TARGET, smsMessage))
  {
    SerialMon.println(smsMessage);
  }
  else{
    SerialMon.println("SMS failed to send");
  }*/

  SerialAT.println("AT"); //Once the handshake test is successful, it will back to OK
  SerialAT.println("AT+CMGF=1"); // Configuring TEXT mode
  SerialAT.println("AT+CNMI=1,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
}

void loop()
{
  //readSMS(1);
 //delay(1);
}
</code>```

Body:
on my code i can send an sms to my target number but i don't know how to read or receive sms from target number

the tinyGSM library doesn't have the read member function and i don't know how to use AT commands

void setup() {
  // Set console baud rate
  SerialMon.begin(115200);

  // Keep power when running from battery
  Wire.begin(I2C_SDA, I2C_SCL);
  bool isOk = setPowerBoostKeepOn(1);
  SerialMon.println(String("IP5306 KeepOn ") + (isOk ? "OK" : "FAIL"));

  // Set modem reset, enable, power pins
  pinMode(MODEM_PWKEY, OUTPUT);
  pinMode(MODEM_RST, OUTPUT);
  pinMode(MODEM_POWER_ON, OUTPUT);
  digitalWrite(MODEM_PWKEY, LOW);
  digitalWrite(MODEM_RST, HIGH);
  digitalWrite(MODEM_POWER_ON, HIGH);

  // Set GSM module baud rate and UART pins
  SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
  delay(3000);

  // Restart SIM800 module, it takes quite some time
  // To skip it, call init() instead of restart()
  SerialMon.println("Initializing modem...");
  modem.restart();
  // use modem.init() if you don't need the complete restart

  // Unlock your SIM card with a PIN if needed
  if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
    modem.simUnlock(simPIN);
  }

  // To send an SMS, call modem.sendSMS(SMS_TARGET, smsMessage)
  String smsMessage = "Hello from ESP32!";
  /*if(modem.sendSMS(SMS_TARGET, smsMessage))
  {
    SerialMon.println(smsMessage);
  }
  else{
    SerialMon.println("SMS failed to send");
  }*/

  SerialAT.println("AT"); //Once the handshake test is successful, it will back to OK
  SerialAT.println("AT+CMGF=1"); // Configuring TEXT mode
  SerialAT.println("AT+CNMI=1,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
}

void loop()
{
  //readSMS(1);
 //delay(1);
}


问:
How to detect/read non-english language or characters in docx/txt/pdf file through url?
I want to read docx/pdf/txt the file from the url and if docx/pdf/txt file has a non-english characters then it will stop read file. I am able to read all type of file through url but I am facing a problem in detecting a non-english characters. If there a non-english character in file then it will skip that character.

So, is there any way to read a file through url without skipping non-english words?

here is my code to read file in windows.

```<code>request=requests.get("url of file")
resp = request.json()

file_path=(resp["data"]["file_path"])
_id=(resp["data"]["_id"])
number_of_question=(resp["data"]["number_of_question"])
file_type=(resp["data"]["file_type"])

def get_context(total_pages):
    page_data = []
    for i in range(0,total_pages):
        page = read_pdf.pages[i]
        parts = []
        def visitor_body(text, cm, tm, fontDict, fontSize):
            y = tm[5]
            if y > 70 and y < 780:
                parts.append(text)
        page.extract_text(visitor_text=visitor_body)
        text_body = "".join(parts).strip()
        page_data.append({"page_no":i+1, "page_content":text_body})
    return page_data

if file_type=="txt":
    response = urllib.request.urlopen(file_path)
    html = response.read()
    Text = html.decode('utf8')

elif file_type=="pdf":
    response = requests.get(file_path)
    my_raw_data = response.content

    with open("my_pdf.pdf", 'wb') as my_data:
        my_data.write(my_raw_data)

    open_pdf_file = open("my_pdf.pdf", 'rb')
    read_pdf = PyPDF2.PdfReader(open_pdf_file)
    total_pages = len(read_pdf.pages)
    Text = get_context(total_pages)
    print(Text)
elif file_type=="docx":
    response = requests.get(file_path)
    my_raw_data = response.content

    with open("my_doc.docx", "wb") as text_file:
        text_file.write(my_raw_data)

    pythoncom.CoInitialize()
    docx2pdf.convert("my_doc.docx")
    open_pdf_file = open("my_doc.pdf", 'rb')
    read_pdf = PyPDF2.PdfReader("my_doc.pdf")
    total_pages = len(read_pdf.pages)
    Text = get_context(total_pages)
else:
    print("Invalid File Type")
</code>```

here is the output that I am getting.

```<code>[{'page_no': 1, 'page_content': ''}]
</code>```

example of non-english file.
https://www.dropbox.com/s/utq3y82qrbenisg/%E0%A4%95%E0%A4%B2-%E0%A4%95%E0%A5%80-%E0%A4%95%E0%A4%B2-%E0%A4%B8%E0%A5%8B%E0%A4%9A%E0%A5%87%E0%A4%82%E0%A4%97%E0%A5%87-.pdf?dl=0

Body:
I want to read docx/pdf/txt the file from the url and if docx/pdf/txt file has a non-english characters then it will stop read file. I am able to read all type of file through url but I am facing a problem in detecting a non-english characters. If there a non-english character in file then it will skip that character.

So, is there any way to read a file through url without skipping non-english words?

here is my code to read file in windows.

request=requests.get("url of file")
resp = request.json()

file_path=(resp["data"]["file_path"])
_id=(resp["data"]["_id"])
number_of_question=(resp["data"]["number_of_question"])
file_type=(resp["data"]["file_type"])

def get_context(total_pages):
    page_data = []
    for i in range(0,total_pages):
        page = read_pdf.pages[i]
        parts = []
        def visitor_body(text, cm, tm, fontDict, fontSize):
            y = tm[5]
            if y > 70 and y < 780:
                parts.append(text)
        page.extract_text(visitor_text=visitor_body)
        text_body = "".join(parts).strip()
        page_data.append({"page_no":i+1, "page_content":text_body})
    return page_data

if file_type=="txt":
    response = urllib.request.urlopen(file_path)
    html = response.read()
    Text = html.decode('utf8')

elif file_type=="pdf":
    response = requests.get(file_path)
    my_raw_data = response.content

    with open("my_pdf.pdf", 'wb') as my_data:
        my_data.write(my_raw_data)

    open_pdf_file = open("my_pdf.pdf", 'rb')
    read_pdf = PyPDF2.PdfReader(open_pdf_file)
    total_pages = len(read_pdf.pages)
    Text = get_context(total_pages)
    print(Text)
elif file_type=="docx":
    response = requests.get(file_path)
    my_raw_data = response.content

    with open("my_doc.docx", "wb") as text_file:
        text_file.write(my_raw_data)

    pythoncom.CoInitialize()
    docx2pdf.convert("my_doc.docx")
    open_pdf_file = open("my_doc.pdf", 'rb')
    read_pdf = PyPDF2.PdfReader("my_doc.pdf")
    total_pages = len(read_pdf.pages)
    Text = get_context(total_pages)
else:
    print("Invalid File Type")

here is the output that I am getting.

[{'page_no': 1, 'page_content': ''}]

example of non-english file.
https://www.dropbox.com/s/utq3y82qrbenisg/%E0%A4%95%E0%A4%B2-%E0%A4%95%E0%A5%80-%E0%A4%95%E0%A4%B2-%E0%A4%B8%E0%A5%8B%E0%A4%9A%E0%A5%87%E0%A4%82%E0%A4%97%E0%A5%87-.pdf?dl=0


问:
How to add new thread for every new client in python websockets?
```<code>import asyncio
import websockets
import threading

async def server_handle(websocket,path):

    print("Server is waiting!!!!")

    while True:

        msg = await websocket.recv()

        print(f"Client : {msg}")

        await websocket.send(input("Server : "))

def add_new_clients():

    loop = asyncio.new_event_loop()

    asyncio.set_event_loop(loop)

    start_server = websockets.serve(server_handle, "localhost", 1234)

    loop.run_until_complete(start_server)

    loop.run_forever()

    loop.close()

total_clients = 0

if __name__ == "__main__":
    # daemon server thread:
    server = threading.Thread(target=add_new_clients, daemon=True)
    server.start()

    total_clients+=1

    print(f"total clients : {total_clients}")
</code>```

Here i am trying to add new thread to handle each clients request seperately using python websockets . for example if client1 connects to the server one thread should be created and sholud take care of the request and responce of that particular client. is there any way?.

Body:
import asyncio
import websockets
import threading

async def server_handle(websocket,path):

    print("Server is waiting!!!!")

    while True:

        msg = await websocket.recv()

        print(f"Client : {msg}")

        await websocket.send(input("Server : "))

def add_new_clients():

    loop = asyncio.new_event_loop()

    asyncio.set_event_loop(loop)

    start_server = websockets.serve(server_handle, "localhost", 1234)

    loop.run_until_complete(start_server)

    loop.run_forever()

    loop.close()

total_clients = 0

if __name__ == "__main__":
    # daemon server thread:
    server = threading.Thread(target=add_new_clients, daemon=True)
    server.start()

    total_clients+=1

    print(f"total clients : {total_clients}")

Here i am trying to add new thread to handle each clients request seperately using python websockets . for example if client1 connects to the server one thread should be created and sholud take care of the request and responce of that particular client. is there any way?.


问:
How to connect Python Code to C# Winforms on two different devices?
New on Python and C# here. I am currently trying to connect my python code (that has gui) which is on my RPI4, and a C# winforms on my laptop. Is there any way to send data from python to the winforms?

```<code>from tkinter import *
import sqlite3
import tkinter.messagebox
import datetime
import math

conn = sqlite3.connect(#location of database)
c = conn.cursor()
date = datetime.datetime.now().date()

#List(
products_list = []
products_price = []
products_quantity = []
products_weight = []

</code>```

I've done some research, but am confused on how to connect the sqlite to my C# laptop. What I want to happen is after I have inputted my data on the list, the data that is in the list would pass to the DataGridViewCell on my C# Winforms.

Body:
New on Python and C# here. I am currently trying to connect my python code (that has gui) which is on my RPI4, and a C# winforms on my laptop. Is there any way to send data from python to the winforms?

from tkinter import *
import sqlite3
import tkinter.messagebox
import datetime
import math

conn = sqlite3.connect(#location of database)
c = conn.cursor()
date = datetime.datetime.now().date()

#List(
products_list = []
products_price = []
products_quantity = []
products_weight = []

I've done some research, but am confused on how to connect the sqlite to my C# laptop. What I want to happen is after I have inputted my data on the list, the data that is in the list would pass to the DataGridViewCell on my C# Winforms.


问:
How to implement inverse cosine in react js without using math library?
How can I use inverse cosine here?

```<code>const volumeCalculator = () => {
    const dens = tank.density;
    const lHeight = pressure / (dens * 9.81);
    // const resHeight = tank.height - lHeight;
    const len = tank.length;
    const rad = tank.radius;
    const circum = 3.1416 * (rad ** 2);
    if (tank.vertical === 'Vertical') {
      const volume = circum * lHeight;
      return volume;
    }
    const volume = [Math.acos((rad - lHeight) / rad)(rad * 2) - (rad - lHeight) * Math.sqrt(2 * rad * lHeight - (lHeight * 2))] * len;
    return volume;
  };
</code>```

I am expecting inverse cosine result on a number.

Body:
How can I use inverse cosine here?

const volumeCalculator = () => {
    const dens = tank.density;
    const lHeight = pressure / (dens * 9.81);
    // const resHeight = tank.height - lHeight;
    const len = tank.length;
    const rad = tank.radius;
    const circum = 3.1416 * (rad ** 2);
    if (tank.vertical === 'Vertical') {
      const volume = circum * lHeight;
      return volume;
    }
    const volume = [Math.acos((rad - lHeight) / rad)(rad * 2) - (rad - lHeight) * Math.sqrt(2 * rad * lHeight - (lHeight * 2))] * len;
    return volume;
  };

I am expecting inverse cosine result on a number.


问:
Named pipe throws exception after few connections
I have 2 applications: 1 dispatcher and second receiver.
I'm using Name pipe server and client to send to message from dispatcher to receiver

```<code>public partial class DispatcherForm : Form
{

    public DispatcherForm()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        var pipe = new NamedPipeServerStream("DispatcherPipe", PipeDirection.InOut);
        pipe.WaitForConnection();
        Task.Run(async () =>
        {
            var buffer = Encoding.UTF8.GetBytes("Hello from dispacther");

            await pipe.WriteAsync(buffer, 0, buffer.Length);
            pipe.Dispose();
            Application.Exit();

        });
        base.OnLoad(e);
    }
}

public partial class ReceiverForm : Form
{
    private NamedPipeClientStream m_pipe;

    public ReceiverForm()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        startProcess();
        base.OnLoad(e);

    }

    private void startProcess()
    {
        string processName = "DispatcherEventTester.exe";
        var process  = new Process();
        process.StartInfo.FileName = processName;
        process.Start();

        m_pipe = new NamedPipeClientStream("DispatcherPipe");
        startConnecting(new CancellationTokenSource().Token);
    }

    private Task startConnecting(CancellationToken token)
    {
        var buffer = new byte[8096];
        return m_pipe.ConnectAsync(token)
                .ContinueWith(async t =>
                {
                    while(m_pipe.IsConnected)
                    {
                        if (t.IsCanceled)
                        {
                            m_pipe.Close();
                            break;
                        }
                        var ret = await m_pipe.ReadAsync(buffer, 0, buffer.Length);
                        this.Invoke(new Action(() =>
                        {
                            richTextBox1.AppendText(Encoding.UTF8.GetString(buffer)+Environment.NewLine);
                        }));
                        m_pipe.Close();
                        break;
                    }
                },token);

    }

    private void button1_Click(object sender, EventArgs e)
    {
        startProcess();
    }
}
</code>```

the application works but weird things happen sometimes.
The application throws System.IO.IOException: All pipe instances are busy.
if pressing on button1 few times

what is this error and how do I clear the pipe instances?
there were also few times I received in ReadAsync method 0 values

Body:
I have 2 applications: 1 dispatcher and second receiver.
I'm using Name pipe server and client to send to message from dispatcher to receiver

public partial class DispatcherForm : Form
{

    public DispatcherForm()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        var pipe = new NamedPipeServerStream("DispatcherPipe", PipeDirection.InOut);
        pipe.WaitForConnection();
        Task.Run(async () =>
        {
            var buffer = Encoding.UTF8.GetBytes("Hello from dispacther");

            await pipe.WriteAsync(buffer, 0, buffer.Length);
            pipe.Dispose();
            Application.Exit();

        });
        base.OnLoad(e);
    }
}

public partial class ReceiverForm : Form
{
    private NamedPipeClientStream m_pipe;

    public ReceiverForm()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        startProcess();
        base.OnLoad(e);

    }

    private void startProcess()
    {
        string processName = "DispatcherEventTester.exe";
        var process  = new Process();
        process.StartInfo.FileName = processName;
        process.Start();

        m_pipe = new NamedPipeClientStream("DispatcherPipe");
        startConnecting(new CancellationTokenSource().Token);
    }

    private Task startConnecting(CancellationToken token)
    {
        var buffer = new byte[8096];
        return m_pipe.ConnectAsync(token)
                .ContinueWith(async t =>
                {
                    while(m_pipe.IsConnected)
                    {
                        if (t.IsCanceled)
                        {
                            m_pipe.Close();
                            break;
                        }
                        var ret = await m_pipe.ReadAsync(buffer, 0, buffer.Length);
                        this.Invoke(new Action(() =>
                        {
                            richTextBox1.AppendText(Encoding.UTF8.GetString(buffer)+Environment.NewLine);
                        }));
                        m_pipe.Close();
                        break;
                    }
                },token);

    }

    private void button1_Click(object sender, EventArgs e)
    {
        startProcess();
    }
}

the application works but weird things happen sometimes.
The application throws System.IO.IOException: All pipe instances are busy.
if pressing on button1 few times

what is this error and how do I clear the pipe instances?
there were also few times I received in ReadAsync method 0 values


问:
What's wrong with my usage of `enumerateDates`?
I'm trying to use enumerateDates(startingAfter:matching:matchingPolicy:repeatedTimePolicy:direction:using:)  to list all first days of months between two dates. However, I find it didn't return the last date as what I expected.

Here's the code snippet. I set the endDate as a random time on 2023/1/1. I thought it should also include 2023/1/1 in its output, but seems it ignored it. Is it an time zone issue because I'm in UTC+8?

let calendar = Calendar.current
let startDate = calendar.date(from: DateComponents(year: 2022, month: 10, day: 2))!
let endDate = calendar.date(from: DateComponents(year: 2023, month: 1, day: 1, hour: 12))!
let firstDayOfMonth = DateComponents(day: 1)
calendar.enumerateDates(startingAfter: endDate, matching: firstDayOfMonth, matchingPolicy: .strict, direction: .backward) { result, exactMatch, stop in
    if let date = result {
        if date < startDate {
            stop = true
        } else {
            print(date)
        }
    }
}
```
<p>The output:</p>
```// I expect a `2022-12-31 16:00:00 +0000` here!
2022-11-30 16:00:00 +0000
2022-10-31 16:00:00 +0000
```

Body:
I'm trying to use enumerateDates(startingAfter:matching:matchingPolicy:repeatedTimePolicy:direction:using:)  to list all first days of months between two dates. However, I find it didn't return the last date as what I expected.

Here's the code snippet. I set the endDate as a random time on 2023/1/1. I thought it should also include 2023/1/1 in its output, but seems it ignored it. Is it an time zone issue because I'm in UTC+8?

let calendar = Calendar.current
let startDate = calendar.date(from: DateComponents(year: 2022, month: 10, day: 2))!
let endDate = calendar.date(from: DateComponents(year: 2023, month: 1, day: 1, hour: 12))!
let firstDayOfMonth = DateComponents(day: 1)
calendar.enumerateDates(startingAfter: endDate, matching: firstDayOfMonth, matchingPolicy: .strict, direction: .backward) { result, exactMatch, stop in
    if let date = result {
        if date < startDate {
            stop = true
        } else {
            print(date)
        }
    }
}

The output:

// I expect a `2022-12-31 16:00:00 +0000` here!
2022-11-30 16:00:00 +0000
2022-10-31 16:00:00 +0000


问:
How to use other file data in google app script by exporting
I am a react developer. I know how to export JSON data to another file. I am new to google appscript. I want to use JSON data in my google app script which is defined in another file. I know this process in react but not in google app script.

can anyone have a idea about it?

or

Is there any way to share the data to file.


问:
Make ID from groups in pandas dataframe
Suppose I have a data frame

```<code>             Sym    P    P_2  R
01.01.2020   AAPL   100  115  0.2
01.01.2020   AA     200  205  0.4
01.01.2020   MM     300  290  0.5
02.01.2020   AAPL   101  116  0.3
02.01.2020   AA     201  206  0.2
02.01.2020   MM     298  300  0.5
03.01.2020   AA     200  205  0.3
03.01.2020   MM     300  305  0.2
</code>```

How can I make a new column ID, so that I have a unique id for each Sym?

I would expect

```<code>             Sym   ID  P    P_2  R
01.01.2020   AAPL  1   100  115  0.2
01.01.2020   AA    2   200  205  0.4
01.01.2020   MM    3   300  290  0.5
02.01.2020   AAPL  1   101  116  0.3
02.01.2020   AA    2   201  206  0.2
02.01.2020   MM    3   298  300  0.5
03.01.2020   AA    2   200  205  0.3
03.01.2020   MM    3   300  305  0.2
</code>```

The answer provided in assign unique ID to each unique value in group after pandas groupby does not give what I expect - comes Error: Cannot set a DataFrame with multiple columns to the single column ID

Title: Make ID from groups in pandas dataframe

Body:
Suppose I have a data frame

             Sym    P    P_2  R
01.01.2020   AAPL   100  115  0.2
01.01.2020   AA     200  205  0.4
01.01.2020   MM     300  290  0.5
02.01.2020   AAPL   101  116  0.3
02.01.2020   AA     201  206  0.2
02.01.2020   MM     298  300  0.5
03.01.2020   AA     200  205  0.3
03.01.2020   MM     300  305  0.2

How can I make a new column ID, so that I have a unique id for each Sym?

I would expect

             Sym   ID  P    P_2  R
01.01.2020   AAPL  1   100  115  0.2
01.01.2020   AA    2   200  205  0.4
01.01.2020   MM    3   300  290  0.5
02.01.2020   AAPL  1   101  116  0.3
02.01.2020   AA    2   201  206  0.2
02.01.2020   MM    3   298  300  0.5
03.01.2020   AA    2   200  205  0.3
03.01.2020   MM    3   300  305  0.2

The answer provided in assign unique ID to each unique value in group after pandas groupby does not give what I expect - comes Error: Cannot set a DataFrame with multiple columns to the single column ID


问:
Flutter: How matrix_gesture_detector rotate in Linux (Ubuntu)?
I want to make an APP that can zoom in, zoom out and rotate by the gesture.

I found the package: matrix_gesture_detector that can work perfectly in Android but I don't know how to make it rotate in the Linux (Ubuntu 20.04) app, I tried to use the mouse and hold "Ctrl", "Shift", and "Alt" but it can't rotate (only zoom in-out). In Android, I can use 2 fingers to zoom and rotate.

I tried this example


问:
Exec format error on new Linux kernel Module
-PROBLEM DESCRITION

I’ve compiled  a new uvcdriver.ko
https://github.com/Giuliano69/uvc_driver-for-Quanta-HD-User-Facing-0x0408-0x4035-
but I’m facing this error once I try to install the module

```<code>giuliano@Astra2A:~$ sudo rmmod uvcvideo && sudo modprobe uvcvideo
modprobe: ERROR: could not insert 'uvcvideo': Exec format error

</code>```

and dmesg shows:

```<code>[25961.151982] usbcore: registered new interface driver uvcvideo
[26323.125534] usbcore: deregistering interface driver uvcvideo
[26323.189294] uvcvideo: disagrees about version of symbol module_layout
</code>```

Googling on internet, the problem seems to happens when we
want to use a module compiled for a different kernel version.

These are the TWO modinfo from the old and new uvcvideo modules
https://pastebin.com/tSj8Exm6

Basically

OLD module: vermagic: 5.15.0-56-generic SMP mod_unload modversions

NEW module: vermagic: 5.15.64 SMP mod_unload modversions

-HOST CONFIGURATION

I’m using this kernel

```<code>giuliano@Astra2A:~$ cat /proc/version_signature
Ubuntu 5.15.0-56.62-generic 5.15.64
</code>```

BUT on the closest kernel I found on Ubuntu archive is 5,15 and seems to be different:
https://git.launchpad.net/~ubuntu-kernel-test/ubuntu/+source/linux/+git/linus--linux/refs/tags

to allow Eclipse to compile the kernel, I had to pass this commands:

```<code>scripts/config --disable CONFIG_SYSTEM_REVOCATION_KEYS
scripts/config --disable SYSTEM_REVOCATION_KEYS
scripts/config --disable SYSTEM_TRUSTED_KEYS
</code>```

the kernel is compiling without errors and the uvcvideo.ko is produced

-kindly ASK

-WHERE cane I found an Ubuntu  kernel SOURCE to exactly match the version I’m running ?

-HOW can FORCE the uvcdriver.c to  match mi kernel version ?

-Have I got OTHER ways to make the kernel module I’m compiling, match my running system ?

Body:
-PROBLEM DESCRITION

I’ve compiled  a new uvcdriver.ko
https://github.com/Giuliano69/uvc_driver-for-Quanta-HD-User-Facing-0x0408-0x4035-
but I’m facing this error once I try to install the module

giuliano@Astra2A:~$ sudo rmmod uvcvideo && sudo modprobe uvcvideo
modprobe: ERROR: could not insert 'uvcvideo': Exec format error

and dmesg shows:

[25961.151982] usbcore: registered new interface driver uvcvideo
[26323.125534] usbcore: deregistering interface driver uvcvideo
[26323.189294] uvcvideo: disagrees about version of symbol module_layout

Googling on internet, the problem seems to happens when we
want to use a module compiled for a different kernel version.

These are the TWO modinfo from the old and new uvcvideo modules
https://pastebin.com/tSj8Exm6

Basically

OLD module: vermagic: 5.15.0-56-generic SMP mod_unload modversions

NEW module: vermagic: 5.15.64 SMP mod_unload modversions

-HOST CONFIGURATION

I’m using this kernel

giuliano@Astra2A:~$ cat /proc/version_signature
Ubuntu 5.15.0-56.62-generic 5.15.64

BUT on the closest kernel I found on Ubuntu archive is 5,15 and seems to be different:
https://git.launchpad.net/~ubuntu-kernel-test/ubuntu/+source/linux/+git/linus--linux/refs/tags

to allow Eclipse to compile the kernel, I had to pass this commands:

scripts/config --disable CONFIG_SYSTEM_REVOCATION_KEYS
scripts/config --disable SYSTEM_REVOCATION_KEYS
scripts/config --disable SYSTEM_TRUSTED_KEYS

the kernel is compiling without errors and the uvcvideo.ko is produced

-kindly ASK

-WHERE cane I found an Ubuntu  kernel SOURCE to exactly match the version I’m running ?

-HOW can FORCE the uvcdriver.c to  match mi kernel version ?

-Have I got OTHER ways to make the kernel module I’m compiling, match my running system ?


问:
Building gRPC with windows 10 and QT creator - C++
I'm trying to build gRPC library with Windows 10 with QT. Im using QT creator 5.15.2 MSVC 2019 compiler kit. I installed protobuf and grpc using vcpkg. I can able to successfully test protobuf libraries. But failing to do so with gRPC.

Getting the following error.

grpc.lib(check_gcp_environment_windows.cc.obj):-1: error: LNK2019: unresolved external symbol imp_RegGetValueA referenced in function "bool cdecl grpc_core::internal::check_windows_registry_product_name(struct HKEY *,char const *,char const *)" (?check_windows_registry_product_name@internal@grpc_core@@YA_NPEAUHKEY@@PEBD1@Z)

I have tried linking the libraries one by one in QT like below. Attached my .pro file here

```<code>QT -= gui

CONFIG += c++17 console
CONFIG -= app_bundle

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

LIBS += C:/vcpkg/installed/x64-windows/debug/lib/zlibd.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/abseil_dll.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_cord_internal.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_cordz_functions.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_cordz_handle.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_cordz_info.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_cordz_sample_token.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_commandlineflag.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_commandlineflag_internal.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_config.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_internal.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_marshalling.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_parse.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_private_handle_accessor.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_program_name.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_reflection.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_usage.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_usage_internal.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_low_level_hash.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_random_internal_distribution_test_util.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_statusor.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_strerror.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/address_sorting.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/cares.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/descriptor_upb_proto.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/gpr.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc_plugin_support.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc_unsecure.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc++.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc++_alts.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc++_error_details.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc++_reflection.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc++_unsecure.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpcpp_channelz.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/libcrypto.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/libprotobufd.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/libprotobuf-lited.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/libprotocd.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/libssl.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/re2.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_collections.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_extension_registry.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_fastdecode.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_json.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_mini_table.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_reflection.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_textformat.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_utf8_range.lib

INCLUDEPATH += C:\vcpkg\installed\x64-windows\include

HEADERS += \
        helloworld.grpc.pb.h \
        helloworld.pb.h

SOURCES += \
        main.cpp \
        helloworld.grpc.pb.cc \
        helloworld.pb.cc

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

</code>```

There were few errors w.r.2 ws2_32 lib. which I have neglected using the following pragma statement.

#pragma comment(lib, "Ws2_32.lib")

But the error LNK2019: unresolved external symbol __imp_RegGetValueA referenced in function . I couldnt find any. I believe its something related to re2.lib linked. Kindly add your thoughts. Thanks

Body:
I'm trying to build gRPC library with Windows 10 with QT. Im using QT creator 5.15.2 MSVC 2019 compiler kit. I installed protobuf and grpc using vcpkg. I can able to successfully test protobuf libraries. But failing to do so with gRPC.

Getting the following error.

grpc.lib(check_gcp_environment_windows.cc.obj):-1: error: LNK2019: unresolved external symbol imp_RegGetValueA referenced in function "bool cdecl grpc_core::internal::check_windows_registry_product_name(struct HKEY *,char const *,char const *)" (?check_windows_registry_product_name@internal@grpc_core@@YA_NPEAUHKEY@@PEBD1@Z)

I have tried linking the libraries one by one in QT like below. Attached my .pro file here

QT -= gui

CONFIG += c++17 console
CONFIG -= app_bundle

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

LIBS += C:/vcpkg/installed/x64-windows/debug/lib/zlibd.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/abseil_dll.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_cord_internal.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_cordz_functions.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_cordz_handle.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_cordz_info.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_cordz_sample_token.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_commandlineflag.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_commandlineflag_internal.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_config.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_internal.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_marshalling.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_parse.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_private_handle_accessor.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_program_name.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_reflection.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_usage.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_flags_usage_internal.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_low_level_hash.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_random_internal_distribution_test_util.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_statusor.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/absl_strerror.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/address_sorting.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/cares.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/descriptor_upb_proto.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/gpr.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc_plugin_support.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc_unsecure.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc++.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc++_alts.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc++_error_details.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc++_reflection.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpc++_unsecure.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/grpcpp_channelz.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/libcrypto.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/libprotobufd.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/libprotobuf-lited.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/libprotocd.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/libssl.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/re2.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_collections.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_extension_registry.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_fastdecode.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_json.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_mini_table.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_reflection.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_textformat.lib
LIBS += C:/vcpkg/installed/x64-windows/debug/lib/upb_utf8_range.lib

INCLUDEPATH += C:\vcpkg\installed\x64-windows\include

HEADERS += \
        helloworld.grpc.pb.h \
        helloworld.pb.h

SOURCES += \
        main.cpp \
        helloworld.grpc.pb.cc \
        helloworld.pb.cc

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

There were few errors w.r.2 ws2_32 lib. which I have neglected using the following pragma statement.

#pragma comment(lib, "Ws2_32.lib")

But the error LNK2019: unresolved external symbol __imp_RegGetValueA referenced in function . I couldnt find any. I believe its something related to re2.lib linked. Kindly add your thoughts. Thanks


问:
NodeJS Request Package - How Do I Get The Value Stored in an Array Out of Its Callback Function?
I'm trying to build an API in NodeJS that uses the request package as well as cheerio. It scrapes images from a URL and I'd like to use the image src URIs stored in an array and send them back to the user (res.json()).

I can't seem to get the imgSrcs out of the request() callback body.

```<code>let result = [];
const handleSearch = async searchQuery => {
    const baseUrl = `url/${searchQuery}`;
    request(baseUrl, (err, resp, html) => {
        const imgSrcs = []; // <------ I want to return the stuff stored in here at handleSearch() level
        if (!err && resp.statusCode === 200) {
            const $ = cheerio.load(html)

            $('img').each((_, image) => {
                let img = $(image).attr('src')
                    imgSrcs.push(img)
            });
        }
        result = imgSrcs; // <------ This is the super crude, semi-working way of doing it (only way that has worked so far, but it only displays the correct result when refreshing the page twice not once
    })
return result;
}
</code>```

Then in my index.js file, I have the following that uses the above code:

```<code>const searchData = await handleSearch(searchQuery);

res.json(searchData)
</code>```

How do I get the imgSrcs array out of the nested inner callbacks so I can return it at the top level handleSearch() function? And then I can use this in index.js?

I have tried assigning the request() to a variable but it gives me a convoluted JSON body with no way of getting the data inside it. I've also tried returning in the body of each callback but it still doesn't work.

Body:
I'm trying to build an API in NodeJS that uses the request package as well as cheerio. It scrapes images from a URL and I'd like to use the image src URIs stored in an array and send them back to the user (res.json()).

I can't seem to get the imgSrcs out of the request() callback body.

let result = [];
const handleSearch = async searchQuery => {
    const baseUrl = `url/${searchQuery}`;
    request(baseUrl, (err, resp, html) => {
        const imgSrcs = []; // <------ I want to return the stuff stored in here at handleSearch() level
        if (!err && resp.statusCode === 200) {
            const $ = cheerio.load(html)

            $('img').each((_, image) => {
                let img = $(image).attr('src')
                    imgSrcs.push(img)
            });
        }
        result = imgSrcs; // <------ This is the super crude, semi-working way of doing it (only way that has worked so far, but it only displays the correct result when refreshing the page twice not once
    })
return result;
}

Then in my index.js file, I have the following that uses the above code:

const searchData = await handleSearch(searchQuery);

res.json(searchData)

How do I get the imgSrcs array out of the nested inner callbacks so I can return it at the top level handleSearch() function? And then I can use this in index.js?

I have tried assigning the request() to a variable but it gives me a convoluted JSON body with no way of getting the data inside it. I've also tried returning in the body of each callback but it still doesn't work.


问:
Simulink unit conversion
I need a simply rad/s (my default output signal) to RPM in Simulink and I want it to show the conversion in a display box.
I tried with Unit Conversion block but I cannot understand where I can give him the conversion

```<code>RPM = (rad/s)*60/2pi
</code>```

Is it possible to write a simple matlab line inside the display box to show the new number instead of call a matlab function inside simulink?

Thank you

Edit: I found in the Aerospace blocket the angular conversion block. It's perfect. In any case I'm interested in a solution without using these blocks (if I wouldn't have the aerospace toolbox installed)

Title: Simulink unit conversion

Body:
I need a simply rad/s (my default output signal) to RPM in Simulink and I want it to show the conversion in a display box.
I tried with Unit Conversion block but I cannot understand where I can give him the conversion

RPM = (rad/s)*60/2pi

Is it possible to write a simple matlab line inside the display box to show the new number instead of call a matlab function inside simulink?

Thank you

Edit: I found in the Aerospace blocket the angular conversion block. It's perfect. In any case I'm interested in a solution without using these blocks (if I wouldn't have the aerospace toolbox installed)


问:
Automatically save QuickTime Recording
I'm trying to automatically save a Quicktime recording to a directory with an specific file name including date and time.

To create the path, the I created a input dialog to create the folder and a subfolder with the date.

```<code>tell application "Finder"
    activate
    set DateStamp to short date string of (current date)
    set patientname to text returned of (display dialog "patient name:" default answer "")
    set folderpath to POSIX path of (choose folder with prompt "choose folder")

    do shell script "/bin/mkdir -p " & quoted form of folderpath & "/" & quoted form of (patientname) & "/" & DateStamp
end tell
</code>```

Then I open Quicktime and start the Recording. After stopping the recording, the new record should be saved under the specific name + date + time in the new created subfolder.

```<code>tell application "QuickTime Player"
   activate

   repeat

   set tdoc to new movie recording -- document "Movie Recording"

   say "Ready!"

   delay 1

   repeat while exists tdoc
    delay 1
   end repeat -- the recording is stopped

   say "Stop!"

   tell front document
    set TimeStamp to time string of (current date)
    set fileName to POSIX path of folderpath & "/" & patientname & "/" & DateStamp & "/" & patientname & "_" & DateStamp & "_" & TimeStamp & ".mov"
    save it in POSIX file fileName
        close
   end tell

   end repeat

end tell
</code>```

After saving the new Record should close and a new recording window should appear.

However, there is always an error saying, I have no writing permission to save the file.

screenshot

What do I have to change? i have no idea.

Although I have to say that I am very new to apple script. thanks in advance!

PS: I'm Using QuickTime Player Version 10.5 (1148.4.1)
and MacOS Ventura 13.0.1

Title: Automatically save QuickTime Recording

Body:
I'm trying to automatically save a Quicktime recording to a directory with an specific file name including date and time.

To create the path, the I created a input dialog to create the folder and a subfolder with the date.

tell application "Finder"
    activate
    set DateStamp to short date string of (current date)
    set patientname to text returned of (display dialog "patient name:" default answer "")
    set folderpath to POSIX path of (choose folder with prompt "choose folder")

    do shell script "/bin/mkdir -p " & quoted form of folderpath & "/" & quoted form of (patientname) & "/" & DateStamp
end tell

Then I open Quicktime and start the Recording. After stopping the recording, the new record should be saved under the specific name + date + time in the new created subfolder.

tell application "QuickTime Player"
   activate

   repeat

   set tdoc to new movie recording -- document "Movie Recording"

   say "Ready!"

   delay 1

   repeat while exists tdoc
    delay 1
   end repeat -- the recording is stopped

   say "Stop!"

   tell front document
    set TimeStamp to time string of (current date)
    set fileName to POSIX path of folderpath & "/" & patientname & "/" & DateStamp & "/" & patientname & "_" & DateStamp & "_" & TimeStamp & ".mov"
    save it in POSIX file fileName
        close
   end tell

   end repeat

end tell

After saving the new Record should close and a new recording window should appear.

However, there is always an error saying, I have no writing permission to save the file.

screenshot

What do I have to change? i have no idea.

Although I have to say that I am very new to apple script. thanks in advance!

PS: I'm Using QuickTime Player Version 10.5 (1148.4.1)
and MacOS Ventura 13.0.1


问:
Unresolved External Symbol when including my own libraries
I Created a Test.h and Test.cpp in Visual Studio.
Test.h

```<code>#ifndef TEST_H
#define TEST_H

class Test {
public:
    Test(int num);

    int getMyNum();

private:
    int myNum = 0;

};

#endif // !TEST_H
</code>```

Test.cpp

```<code>#include "Test.h"

Test::Test(int num) {
    myNum = num;
}

int Test::getMyNum()
{
    return myNum;
}
</code>```

So when I want to use the Test class in other project in Visual Studio I can just go to project properties >> VC++ Directories >> Include Directories, and then paste the path to the files location.
And in this project I create a main.cpp

```<code>#include <iostream>
#include <Test.h>

int main(){
    Test test(4);
    std::cout << test.getMyNum();
}
</code>```

I thought it should work just fine, and it do not give me any errors, but when I try to compile it I get some unresolved external symbol errors:
unresolved external symbol "public: __cdecl Test::Test(int)" (??0Test@@QEAA@H@Z) referenced in function main

unresolved external symbol "public: int __cdecl Test::getMyNum(void)" (?getMyNum@Test@@QEAAHXZ) referenced in function main

It do not look like there is any symbol without definition.

What I wanted to know is why this is happening, and how to solve it.

Body:
I Created a Test.h and Test.cpp in Visual Studio.
Test.h

#ifndef TEST_H
#define TEST_H

class Test {
public:
    Test(int num);

    int getMyNum();

private:
    int myNum = 0;

};

#endif // !TEST_H

Test.cpp

#include "Test.h"

Test::Test(int num) {
    myNum = num;
}

int Test::getMyNum()
{
    return myNum;
}

So when I want to use the Test class in other project in Visual Studio I can just go to project properties >> VC++ Directories >> Include Directories, and then paste the path to the files location.
And in this project I create a main.cpp

#include <iostream>
#include <Test.h>

int main(){
    Test test(4);
    std::cout << test.getMyNum();
}

I thought it should work just fine, and it do not give me any errors, but when I try to compile it I get some unresolved external symbol errors:
unresolved external symbol "public: __cdecl Test::Test(int)" (??0Test@@QEAA@H@Z) referenced in function main

unresolved external symbol "public: int __cdecl Test::getMyNum(void)" (?getMyNum@Test@@QEAAHXZ) referenced in function main

It do not look like there is any symbol without definition.

What I wanted to know is why this is happening, and how to solve it.


问:
Debugging both Angular Front End and .NET Core Back End
I have to maintain an Application where Front End is done using Angular and Back End using .NET Core/ASP.NET Core C# Controllers.

Problem is that Front End and Back End are not put to their own directories like below:

Application\FrontEnd

Application\BackEnd

They reside in same directory or at least typescript config, webpack, .sln solution file etc. I can use VSCode or Visual Studio but problem is that both typescript and C# files are mixed when starting debugging.

Is it possible to configure VSCode (Visual Studio is okay if possible) so that both Front and Back are debugged as their own.

I tried to modify launch.json but didn't succeeded. I can't refactor this Application.

So, is it possible to configure launch.json to run
Front and Back in own "processes" and how or what could be the solution?

Thanks for All,


问:
Using a wakeword to trigger another script in same folder to run. Python3
I have tried several times to get a simple python script to run on a loop and listen for a wakeword. I have got this mostly figured out but after trying SEVERAL(more than 5) different ways, I must say I am stumped now, and need help that Google can't offer!

Here is the code:

```<code>import speech_recognition as sr
import subprocess

# Create a recognition object
r = sr.Recognizer()

# Create a microphone object
mic = sr.Microphone()

# Start listening for audio
with mic as source:
    r.adjust_for_ambient_noise(source)
    print("Listening for 'hello python'...")
    audio = r.listen(source)

# Try to recognize the spoken text
try:
    text = r.recognize_google(audio)
    if text.lower() == "hello python":
        # Run the script "rec_and_translate_2_text.py"
        subprocess.run(["python", "rec_and_translate_2_text.py"])
except sr.UnknownValueError:
    print("Could not understand audio")
except sr.RequestError as e:
    print("Error making request: {}".format(e))

</code>```

Once I run the code, then say "hello python", I get this error(The result I want is to call a script in same dir named "rec_and_translate_2_text.py"):

```<code>Listening for 'hello python'...
result2:
{   'alternative': [{'confidence': 0.98762906, 'transcript': 'hello python'}],
    'final': True}
Traceback (most recent call last):
  File "/home/nate/chatgpt/wake.py", line 21, in <module>
    subprocess.run(["python", "rec_and_translate_2_text.py"])
  File "/usr/lib/python3.10/subprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.10/subprocess.py", line 969, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.10/subprocess.py", line 1845, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'python'
</code>```

I have ironed out several things getting to this point and really need some help. Thanks ahead.

I tried raven, porcupine, and rhasspy, with no luck, they are too complicated for me. It seems like this would be the simplest route but I dont know. I am open to suggestion?

Body:
I have tried several times to get a simple python script to run on a loop and listen for a wakeword. I have got this mostly figured out but after trying SEVERAL(more than 5) different ways, I must say I am stumped now, and need help that Google can't offer!

Here is the code:

import speech_recognition as sr
import subprocess

# Create a recognition object
r = sr.Recognizer()

# Create a microphone object
mic = sr.Microphone()

# Start listening for audio
with mic as source:
    r.adjust_for_ambient_noise(source)
    print("Listening for 'hello python'...")
    audio = r.listen(source)

# Try to recognize the spoken text
try:
    text = r.recognize_google(audio)
    if text.lower() == "hello python":
        # Run the script "rec_and_translate_2_text.py"
        subprocess.run(["python", "rec_and_translate_2_text.py"])
except sr.UnknownValueError:
    print("Could not understand audio")
except sr.RequestError as e:
    print("Error making request: {}".format(e))

Once I run the code, then say "hello python", I get this error(The result I want is to call a script in same dir named "rec_and_translate_2_text.py"):

Listening for 'hello python'...
result2:
{   'alternative': [{'confidence': 0.98762906, 'transcript': 'hello python'}],
    'final': True}
Traceback (most recent call last):
  File "/home/nate/chatgpt/wake.py", line 21, in <module>
    subprocess.run(["python", "rec_and_translate_2_text.py"])
  File "/usr/lib/python3.10/subprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.10/subprocess.py", line 969, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.10/subprocess.py", line 1845, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'python'

I have ironed out several things getting to this point and really need some help. Thanks ahead.

I tried raven, porcupine, and rhasspy, with no luck, they are too complicated for me. It seems like this would be the simplest route but I dont know. I am open to suggestion?


问:
Hi to all, I have this error, can somebody help me?
    your text#Coin Flip Example  OPENQASM 2.0;
your textinclude "qelib1.inc"
your textqreg q[0];
your text creg c[0];
your texth q;
your textmeasure q -> c;``

```<code>``your text`Traceback (most recent call last):
  `your text`File /opt/conda/lib/python3.8/site-packages/IPython/core/compilerop.py:105 in ast_parse
    `your text`return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
  `your text`Input In [10]
    `your text`OPENQASM 2.0;
             ^
`your text`SyntaxError: invalid syntax

`your text`Use %tb to get the full traceback.
</code>```

your textchange the code writing OPENQASM 3.0;`

Body:
    your text#Coin Flip Example  OPENQASM 2.0;
your textinclude "qelib1.inc"
your textqreg q[0];
your text creg c[0];
your texth q;
your textmeasure q -> c;``

``your text`Traceback (most recent call last):
  `your text`File /opt/conda/lib/python3.8/site-packages/IPython/core/compilerop.py:105 in ast_parse
    `your text`return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
  `your text`Input In [10]
    `your text`OPENQASM 2.0;
             ^
`your text`SyntaxError: invalid syntax

`your text`Use %tb to get the full traceback.

your textchange the code writing OPENQASM 3.0;`


问:
Where can I configure SonarLint to order results by line number in IntelliJ?
I get the corrections list, but it restarts the line order results over and over again.
Can I sort it by line number ascending?
Obs: I have SonarQube installed.


问:
How to crawl webpages with titles in URL?
I would like to crawl news from a webpage. They use URLs like this:
https://www.eqs-news.com/de/news/adhoc/vectron-systems-ag-vectron-uebernimmt-acardo/1724329

The last number in the URL is a unique news ID. My hope was that I would be able to crawl all news by simply looping through all possible IDs. However, that is not possible (at least for me), due to the news title in the URL. Is there any way to circumvent the title in the URL?

Thank you very much in advance!

I tried the following:

Using the query string https://www.eqs-news.com/?data-news-item=1724329, without success

I had a look in the sitemap of the webpage but could not find relevant information (https://www.eqs-news.com/wp-sitemap.xml)


问:
Firebase onAuthStateChanged initially setting user to null causing redirection of page
I am using firebase, zustand and react-router-dom v6.6. The idea is a simple login page and one authenticated route which is accessible only when the user is logged in. When I log in I am successfully redirected to dashboard. The problem is when I refresh the dashboard page, user is redirected to login page inspite of being logged in. I suspect this is because when page is refreshed, initial value of user is set to null. How can I get around this behavior?</p>
```<code>function App() {
  const setUserData = useUserStore((state) => state.setUser);
  const userData = useUserStore((state) => state.username);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      if (user) {
        setUserData(user.email);
      } else {
        setUserData(null);
      }
    });

    return () => {
      unsubscribe();
    };
  }, []);
  const router = createBrowserRouter([
    {
      path: "/login",
      element: <Login />,
    },
    {
      path: "/dashboard",
      element: userData ? (
        <Dashboard username={userData} />
      ) : (
        <Navigate to="/login" />
      ),
    },
  ]);

  return <RouterProvider router={router} />;
}
</code>```
```<code>function Dashboard() {
  const username = useUserStore((state) => state.username);
  if (!username) {
    console.log("no username");
  }
  return username ? <div>Hi, {username}</div> : console.log("no");
}
</code>```

Body:
I am using firebase, zustand and react-router-dom v6.6. The idea is a simple login page and one authenticated route which is accessible only when the user is logged in. When I log in I am successfully redirected to dashboard. The problem is when I refresh the dashboard page, user is redirected to login page inspite of being logged in. I suspect this is because when page is refreshed, initial value of user is set to null. How can I get around this behavior?

function App() {
  const setUserData = useUserStore((state) => state.setUser);
  const userData = useUserStore((state) => state.username);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      if (user) {
        setUserData(user.email);
      } else {
        setUserData(null);
      }
    });

    return () => {
      unsubscribe();
    };
  }, []);
  const router = createBrowserRouter([
    {
      path: "/login",
      element: <Login />,
    },
    {
      path: "/dashboard",
      element: userData ? (
        <Dashboard username={userData} />
      ) : (
        <Navigate to="/login" />
      ),
    },
  ]);

  return <RouterProvider router={router} />;
}

function Dashboard() {
  const username = useUserStore((state) => state.username);
  if (!username) {
    console.log("no username");
  }
  return username ?
Hi, {username}
 : console.log("no");
}