问:
How can i detect onRowEditStop when i click on checkbox from another row?
I have a MUI data grid component. My table has certain columns that are editable. In order for the edition of these columns to be enabled, it is necessary to previously select the row using the checkbox.

If I am editing the row, I can exit the edit by pressing Enter, Esc, or clicking on any other row.

This triggers the onRowEditStop function, which is used to save the changes to my database.

Now, I want to add a small change:

Actually, to detect when a row has been changed, as I said before, it is necessary to press Enter, Esc, or click on another row. The problem is that if I press the checkbox of another row, onRowEditStop is not triggered. It is as if a click on the checkbox does not detect that I am leaving the edition of another row.

How can i detect onRowEditStop when i click on checkbox from another row?

```<code>  <DataGrid
      checkboxSelection
      disableSelectionOnClick
      hideFooterSelectedRowCount

      columns={columns}
      editMode="row"
      experimentalFeatures={{
        newEditingApi: true,
      }}
      isCellEditable={params => params.row.id === selectionModel[0]}
      loading={reviews.length === 0}
      pageSize={10}
      rows={reviews}
      rowsPerPageOptions={[
        5,
        10,
        25,
        50,
      ]}
      selectionModel={selectionModel}

      onRowEditStart={params => console.log("Editing ", params.id)}
      onRowEditStop={handleRowEditCommit}
      onSelectionModelChange={selection => {
        if (selection.length > 1) {
          const selectionSet = new Set(selectionModel);
          const result = selection.filter(s => !selectionSet.has(s));

          setSelectionModel(result);
        } else {
          setSelectionModel(selection);
        }
      }}
    />
</code>```

Body:
I have a MUI data grid component. My table has certain columns that are editable. In order for the edition of these columns to be enabled, it is necessary to previously select the row using the checkbox.

If I am editing the row, I can exit the edit by pressing Enter, Esc, or clicking on any other row.

This triggers the onRowEditStop function, which is used to save the changes to my database.

Now, I want to add a small change:

Actually, to detect when a row has been changed, as I said before, it is necessary to press Enter, Esc, or click on another row. The problem is that if I press the checkbox of another row, onRowEditStop is not triggered. It is as if a click on the checkbox does not detect that I am leaving the edition of another row.

How can i detect onRowEditStop when i click on checkbox from another row?

  <DataGrid
      checkboxSelection
      disableSelectionOnClick
      hideFooterSelectedRowCount

      columns={columns}
      editMode="row"
      experimentalFeatures={{
        newEditingApi: true,
      }}
      isCellEditable={params => params.row.id === selectionModel[0]}
      loading={reviews.length === 0}
      pageSize={10}
      rows={reviews}
      rowsPerPageOptions={[
        5,
        10,
        25,
        50,
      ]}
      selectionModel={selectionModel}

      onRowEditStart={params => console.log("Editing ", params.id)}
      onRowEditStop={handleRowEditCommit}
      onSelectionModelChange={selection => {
        if (selection.length > 1) {
          const selectionSet = new Set(selectionModel);
          const result = selection.filter(s => !selectionSet.has(s));

          setSelectionModel(result);
        } else {
          setSelectionModel(selection);
        }
      }}
    />


来源: stackexchange

问:
Is there any way to show Xmind tree in Wordpress?
I have an Xmind document and I need to show it's content in my wordpress blog post. Is there any plug-in or hack to do this?

I couldn't find any plug-ins for it

ContentLicense: CC BY-SA 4.0


问:
react infinite scroll with IntersectionObserver not working
I don't know why the infinite scroll made of react doesn't work.

Here's what I think.

Connected Element Detection

isFetching = true

setTest()

```<code>  const [isFetching, setIsFetching] = useState(false);

  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          setIsFetching(true);
        }
      });

      setIsFetching(false);
    });

    io.observe(document.getElementById("finish")!);

    return () => io.disconnect();
  }, []);

  useEffect(() => {
    if (!isFetching) return;

    setTest([...test, 1]);
  }, [isFetching, test]);```
```

Body:
I don't know why the infinite scroll made of react doesn't work.

Here's what I think.

Connected Element Detection

isFetching = true

setTest()

  const [isFetching, setIsFetching] = useState(false);

  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          setIsFetching(true);
        }
      });

      setIsFetching(false);
    });

    io.observe(document.getElementById("finish")!);

    return () => io.disconnect();
  }, []);

  useEffect(() => {
    if (!isFetching) return;

    setTest([...test, 1]);
  }, [isFetching, test]);```


问:
Location of anaconda base environment moved after creating a new environment
Starting from conda environment as following:

```<code>(base) C:\Users\NAME\anaconda3>conda info -e
#conda environments:
base                  *  C:\Users\NAME\anaconda3
</code>```

I used the following code to create a new anaconda environment,

```<code>(base) C:\Windows\System32>conda create -n my_env1 anaconda
</code>```

Then I got

```<code>(base) C:\Users\NAME\anaconda3>conda info -e
#conda environments:
                         C:\Users\NAME\anaconda3
base                  *  C:\Users\NAME\anaconda3\envs\my_env1
</code>```

Note that the location of base environment moved, and the previous base environment doesn't have any name anymore.

If I look up the information of new environment, its name is base, not my_env1. Why is that? How to fix this?

```<code>(base) C:\Windows\System32>conda activate my_env1
(my_env1) C:\Windows\System32>conda info

     active environment : base
    active env location : C:\Users\NAME\anaconda3\envs\my_env1
            shell level : 2
       user config file : C:\Users\NAME\.condarc
 populated config files : C:\Users\NAME\.condarc
          conda version : 22.11.1
    conda-build version : not installed
         python version : 3.9.15.final.0
       virtual packages : __archspec=1=x86_64
                          __cuda=11.7=0
                          __win=0=0
       base environment : C:\Users\NAME\anaconda3\envs\my_env1  (writable)
      conda av data dir : C:\Users\NAME\anaconda3\envs\my_env1\etc\conda
  conda av metadata url : None
           channel URLs : https://repo.anaconda.com/pkgs/main/win-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/win-64
                          https://repo.anaconda.com/pkgs/r/noarch
                          https://repo.anaconda.com/pkgs/msys2/win-64
                          https://repo.anaconda.com/pkgs/msys2/noarch
          package cache : C:\Users\NAME\anaconda3\envs\my_env1\pkgs
                          C:\Users\NAME\.conda\pkgs
                          C:\Users\NAME\AppData\Local\conda\conda\pkgs
       envs directories : C:\Users\NAME\anaconda3\envs\my_env1\envs
                          C:\Users\NAME\.conda\envs
                          C:\Users\NAME\AppData\Local\conda\conda\envs
               platform : win-64
             user-agent : conda/22.11.1 requests/2.28.1 CPython/3.9.15 Windows/10 Windows/10.0.22621
          administrator : True
             netrc file : None
           offline mode : False

</code>```

Body:
Starting from conda environment as following:

(base) C:\Users\NAME\anaconda3>conda info -e
#conda environments:
base                  *  C:\Users\NAME\anaconda3

I used the following code to create a new anaconda environment,

(base) C:\Windows\System32>conda create -n my_env1 anaconda

Then I got

(base) C:\Users\NAME\anaconda3>conda info -e
#conda environments:
                         C:\Users\NAME\anaconda3
base                  *  C:\Users\NAME\anaconda3\envs\my_env1

Note that the location of base environment moved, and the previous base environment doesn't have any name anymore.

If I look up the information of new environment, its name is base, not my_env1. Why is that? How to fix this?

(base) C:\Windows\System32>conda activate my_env1
(my_env1) C:\Windows\System32>conda info

     active environment : base
    active env location : C:\Users\NAME\anaconda3\envs\my_env1
            shell level : 2
       user config file : C:\Users\NAME\.condarc
 populated config files : C:\Users\NAME\.condarc
          conda version : 22.11.1
    conda-build version : not installed
         python version : 3.9.15.final.0
       virtual packages : __archspec=1=x86_64
                          __cuda=11.7=0
                          __win=0=0
       base environment : C:\Users\NAME\anaconda3\envs\my_env1  (writable)
      conda av data dir : C:\Users\NAME\anaconda3\envs\my_env1\etc\conda
  conda av metadata url : None
           channel URLs : https://repo.anaconda.com/pkgs/main/win-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/win-64
                          https://repo.anaconda.com/pkgs/r/noarch
                          https://repo.anaconda.com/pkgs/msys2/win-64
                          https://repo.anaconda.com/pkgs/msys2/noarch
          package cache : C:\Users\NAME\anaconda3\envs\my_env1\pkgs
                          C:\Users\NAME\.conda\pkgs
                          C:\Users\NAME\AppData\Local\conda\conda\pkgs
       envs directories : C:\Users\NAME\anaconda3\envs\my_env1\envs
                          C:\Users\NAME\.conda\envs
                          C:\Users\NAME\AppData\Local\conda\conda\envs
               platform : win-64
             user-agent : conda/22.11.1 requests/2.28.1 CPython/3.9.15 Windows/10 Windows/10.0.22621
          administrator : True
             netrc file : None
           offline mode : False


问:
adapt a vscode language server for intellij
I have a language server for a custom language written in go, with vscode language server protocol

I want to adapt it to work with Intellij suite, I found lsp4intellij
but encountered a lot of issues while testing ballerina plugin; not sure if it's still maintained.

Is there an easy way to adapt a language server meant for vscode to intellij without rewriting an adapter.


问:
Android studio Pdf
I am new to Android Studio. I was able to make an application, but I would like to add a function but I don't know how.

I would like to add buttons that will download PDFs included in the application on the device where the application is installed. All this to allow them to be printed later by those who want a paper version.

Is it possible please?

several searches and test but it does not fit

Title: Android studio Pdf


问:
Woocommerce, recognize "cash on delivery" not valid addresses
I'm trying to create a function.
My need is follow:
I have a cash on delivery payment method.
Sometime it happens that the shipping comes back because the address is wrong or not real.
Then I put this order in SPAM status.
I want that when I have a COD order, to check in all SPAM orders if address is present, if yes put the order in SPAM review status, so I can check it personally with client.

This is my code:

I put a check address button on "on hold" orders, that will check the addresses:

```<code>// 1. Create 2 new order statuses: SPAM and SPAM REVIEW
function create_new_order_statuses() {
    register_post_status( 'wc-spam', array(
        'label' => 'SPAM',
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true
    ) );

    register_post_status( 'wc-spam-review', array(
        'label' => 'SPAM REVIEW',
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true
    ) );
}
add_action( 'init', 'create_new_order_statuses' );

// 2. Register them in woocommerce
function add_spam_order_statuses_to_select( $order_statuses ) {
    $order_statuses['wc-spam'] = 'SPAM';
    $order_statuses['wc-spam-review'] = 'SPAM REVIEW';
    return $order_statuses;
}
add_filter( 'wc_order_statuses', 'add_spam_order_statuses_to_select' );

add_action( 'woocommerce_admin_order_data_after_order_details', 'check_address_button_on_order_page' );
function check_address_button_on_order_page( $order ) {
    if ( $order->get_status() === 'on-hold' ) {
        $address = $order->get_address( 'shipping' );
        echo '<button class="button check-address-button">Check Address</button>';
        ?>
        <script>
        jQuery('.check-address-button').click( function() {
            var data = {
                'action': 'check_address',
                'address': <?php echo json_encode( $address ); ?>
            };
            jQuery.post(ajaxurl, data, function(response) {
                if(response.found) {
                    alert('Match found, order status changed to "SPAM REVIEW"');
                } else {
                    alert('No match found');
                }
            });
        });
        </script>
        <?php
    }
}

add_action( 'wp_ajax_check_address', 'check_address' );
function check_address() {
    $address = json_decode( $_POST['address'] );
    $spam_orders = wc_get_orders( array(
        'status' => 'spam',
    ) );
    foreach ( $spam_orders as $spam_order ) {
        if ( $address == $spam_order->get_address( 'shipping' ) ) {
            $order_id = $_POST['order_id'];
            $order = wc_get_order( $order_id );
            $order->update_status( 'spam-review' );
            echo json_encode( array( 'found' => true ) );
            wp_die();
        }
    }
    echo json_encode( array( 'found' => false ) );
    wp_die();
}
</code>```

Of course doesn't work... any suggestion?

Body:
I'm trying to create a function.
My need is follow:
I have a cash on delivery payment method.
Sometime it happens that the shipping comes back because the address is wrong or not real.
Then I put this order in SPAM status.
I want that when I have a COD order, to check in all SPAM orders if address is present, if yes put the order in SPAM review status, so I can check it personally with client.

This is my code:

I put a check address button on "on hold" orders, that will check the addresses:

// 1. Create 2 new order statuses: SPAM and SPAM REVIEW
function create_new_order_statuses() {
    register_post_status( 'wc-spam', array(
        'label' => 'SPAM',
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true
    ) );

    register_post_status( 'wc-spam-review', array(
        'label' => 'SPAM REVIEW',
        'public' => true,
        'exclude_from_search' => false,
        'show_in_admin_all_list' => true,
        'show_in_admin_status_list' => true
    ) );
}
add_action( 'init', 'create_new_order_statuses' );

// 2. Register them in woocommerce
function add_spam_order_statuses_to_select( $order_statuses ) {
    $order_statuses['wc-spam'] = 'SPAM';
    $order_statuses['wc-spam-review'] = 'SPAM REVIEW';
    return $order_statuses;
}
add_filter( 'wc_order_statuses', 'add_spam_order_statuses_to_select' );

add_action( 'woocommerce_admin_order_data_after_order_details', 'check_address_button_on_order_page' );
function check_address_button_on_order_page( $order ) {
    if ( $order->get_status() === 'on-hold' ) {
        $address = $order->get_address( 'shipping' );
        echo '<button class="button check-address-button">Check Address</button>';
        ?>

        <?php
    }
}

add_action( 'wp_ajax_check_address', 'check_address' );
function check_address() {
    $address = json_decode( $_POST['address'] );
    $spam_orders = wc_get_orders( array(
        'status' => 'spam',
    ) );
    foreach ( $spam_orders as $spam_order ) {
        if ( $address == $spam_order->get_address( 'shipping' ) ) {
            $order_id = $_POST['order_id'];
            $order = wc_get_order( $order_id );
            $order->update_status( 'spam-review' );
            echo json_encode( array( 'found' => true ) );
            wp_die();
        }
    }
    echo json_encode( array( 'found' => false ) );
    wp_die();
}

Of course doesn't work... any suggestion?


问:
Why the pipeline is targeting ONE Agent DevOps pod instead of distributing the load accross accross all replicas?
I deployed Azure DevOps Agent on Kubernetes, where i added the HPA as well.

When i launch the pipeline, the HPA is working fine ( ie: the autoscaling ), BUT it uses just ONE pod, and the pipeline finishes with :

HPA gets the following value:

And the metrics of agent devops pod (it loojs just one pod is used) :

PS1 : for the deplotement of Azure DevOps Agent on AKS, i used this documenttion + i added some other package like dotnet.

PS2 : When i remove the HPA part + requests and limits from the deploymeny Object, it works : it comsumes the resource of the worker where the pod is hosted. But this not what I want.


问:
Auth0 - Authorize Auth0 Access Token with grant_type = password in our .net core API
we achieved the below points with Auth0.

We are able to get Management API token with client_id, client_secret, audience &  "grant_type":"client_credentials"

We are able to create user/get userinfo with this token.

we are able to get access_token & id_token by "grant_type":"password", with Username & Password.

Till here we are good.

Now Question is, we have our own API which is hosted in AWS, Now we need to Authorize that API with id_token (Considering user-specific Token)

I am able to Authorize with a Management API token, but that is static for all users, I need to authorize my API with a User-Based token when I can also get some claims values, etc.

Thanks.


问:
Why this.$slots.slotname return undefined even when template is in slot
I have a Child Component with named-slots

```<code><template>
  <v-menu v-model="menu"
          :close-on-content-click="false"
          bottom
          min-width="300"
          offset-y
  >
    <template #activator="{ on, attrs }">
      <v-btn class="p-absolute p-right"
             icon
             style="right: 0;"
             v-bind="attrs"
             v-on="on"
      >
        <v-icon>
          mdi-sort
        </v-icon>
      </v-btn>
    </template>
    <v-list dense>

      <slot name="group"
            :groupBy="groupBy"
      />

      <slot name="sort"
            :direction="direction"
            :sortBy="sortBy"
      />
</template>
</code>```

also i have a Parent component which looks like this

```<code><template>
    <Child>
        <template #group="{ groupBy }">
                  <v-list-item>
                    <v-list-item-title>
                      {{ $t('group_by') }}
                    </v-list-item-title>
                  </v-list-item>

                  <v-list-item>
                    <v-autocomplete
                        v-model="groupBy.value"
                        label="Label"
                        dense
                        :items="items"
                    >
                    </v-autocomplete>
                  </v-list-item>
                </template>
        </Child>
</template>
</code>```

When i want to check which of two slots is empty i decided to use
this.$slots.slot-name but it returns undefined even when i passed template to #group

Body:
I have a Child Component with named-slots

<template>
  <v-menu v-model="menu"
          :close-on-content-click="false"
          bottom
          min-width="300"
          offset-y
  >
    <template #activator="{ on, attrs }">
      <v-btn class="p-absolute p-right"
             icon
             style="right: 0;"
             v-bind="attrs"
             v-on="on"
      >
        <v-icon>
          mdi-sort
        </v-icon>
      </v-btn>
    </template>
    <v-list dense>

      <slot name="group"
            :groupBy="groupBy"
      />

      <slot name="sort"
            :direction="direction"
            :sortBy="sortBy"
      />
</template>

also i have a Parent component which looks like this

<template>
    <Child>
        <template #group="{ groupBy }">
                  <v-list-item>
                    <v-list-item-title>
                      {{ $t('group_by') }}
                    </v-list-item-title>
                  </v-list-item>

                  <v-list-item>
                    <v-autocomplete
                        v-model="groupBy.value"
                        label="Label"
                        dense
                        :items="items"
                    >
                    </v-autocomplete>
                  </v-list-item>
                </template>
        </Child>
</template>

When i want to check which of two slots is empty i decided to use
this.$slots.slot-name but it returns undefined even when i passed template to #group


问:
Can Vue read a file/import javascript that containt document.addEventListener event? and passing a value from a component to that js file
I want to passing a variable and read a js file from vue. I already testing it with html only it works, just need too declare  in the head of html. But how it works in vue?

here's the javascript file that i want to read via vue component, and i want to passing a variable from a component to this file

```<code>document.addEventListener('DOMContentLoaded', () => {
  const userGrid = document.querySelector('.grid-user') //done
  const computerGrid = document.querySelector('.grid-computer') //done
  const displayGrid = document.querySelector('.grid-display')
  const ships = document.querySelectorAll('.ship')

  createBoard(userGrid, userSquares)
  createBoard(computerGrid, computerSquares)

  function startSinglePlayer() {
    generate(shipArray[0])
    generate(shipArray[1])
    generate(shipArray[2])
    generate(shipArray[3])
    generate(shipArray[4])

    startButton.addEventListener('click', () => {
      setupButtons.style.display = 'none'
      playGameSingle()
    })
  }

  //Create Board
  function createBoard(grid, squares) {
    for (let i = 0; i < width*width; i++) {
      const square = document.createElement('div')
      square.dataset.id = i
      grid.appendChild(square)
      squares.push(square)
    }
  }

 ........code
})
</code>```

i already try to use like this

```<code>mounted() {
    const plugin = document.createElement("script");
    plugin.setAttribute(
      "src",
      "//api.myplugincom/widget/mykey.js"
    );
    plugin.async = true;
    document.head.appendChild(plugin);
  }```

but the code didn't work.
*when i only use html file not vue it works.
```

Body:
I want to passing a variable and read a js file from vue. I already testing it with html only it works, just need too declare  in the head of html. But how it works in vue?

here's the javascript file that i want to read via vue component, and i want to passing a variable from a component to this file

document.addEventListener('DOMContentLoaded', () => {
  const userGrid = document.querySelector('.grid-user') //done
  const computerGrid = document.querySelector('.grid-computer') //done
  const displayGrid = document.querySelector('.grid-display')
  const ships = document.querySelectorAll('.ship')

  createBoard(userGrid, userSquares)
  createBoard(computerGrid, computerSquares)

  function startSinglePlayer() {
    generate(shipArray[0])
    generate(shipArray[1])
    generate(shipArray[2])
    generate(shipArray[3])
    generate(shipArray[4])

    startButton.addEventListener('click', () => {
      setupButtons.style.display = 'none'
      playGameSingle()
    })
  }

  //Create Board
  function createBoard(grid, squares) {
    for (let i = 0; i < width*width; i++) {
      const square = document.createElement('div')
      square.dataset.id = i
      grid.appendChild(square)
      squares.push(square)
    }
  }

 ........code
})

i already try to use like this

mounted() {
    const plugin = document.createElement("script");
    plugin.setAttribute(
      "src",
      "//api.myplugincom/widget/mykey.js"
    );
    plugin.async = true;
    document.head.appendChild(plugin);
  }```

but the code didn't work.
*when i only use html file not vue it works.


问:
How to Reconnect SignalR request at Server side if Client Close the Browser or logout also Check its Reconnect Status
I am working on SignalR using .NET Core & Angular. I want if Client Close the Browser or logout then server side Received Message on 'OnDisconnectedAsync. It work fine but I want to send request to Client for Connection in 'OnDisconnectedAsync' method. Attempt Less then five time either Connection Successfully Connected or Not.</p>
```<code>public override async Task OnDisconnectedAsync(Exception stopCalled)
{
   int attempt = 1;
   while (attempt < 5)
   {
     await OnConnectedAsync();
     attempt++;
    }
}
</code>```

Body:
I am working on SignalR using .NET Core & Angular. I want if Client Close the Browser or logout then server side Received Message on 'OnDisconnectedAsync. It work fine but I want to send request to Client for Connection in 'OnDisconnectedAsync' method. Attempt Less then five time either Connection Successfully Connected or Not.

public override async Task OnDisconnectedAsync(Exception stopCalled)
{
   int attempt = 1;
   while (attempt < 5)
   {
     await OnConnectedAsync();
     attempt++;
    }
}


问:
Upgrade Apache to latest version in ubuntu
I am pretty new to Unix/Apache/PHP platform/tech.

I need to update the apache server from 2.4.7 to latest version 2.4.54

I am about the follow the steps from this post https://haneefputtur.com/upgrade-apache-to-latest-version-in-ubuntu-server-20.html

My current Ubuntu version is - 14.04.6

My current PHP version is - 7.0.18

I am not able to find the apache compatibility matrix with ubuntu and php.
Can you please advise apache 2.4.54 is compatible with Ubuntu 14.0.46 and PHP 7.0.8?


问:
gnuplot outputs strange text after plot command
Sorry for the vagueness in the title, I don't know how else to describe it.
I am using gnuplot 5.4.5 on macOS Ventura 13.1. Whenever I try to plot something, wether a function or data from a file, the plot window containing the graph correctly appears, but the command line is littered with a bunch of text that I don't understand, like in the following example:

```<code>~ > gnuplot

G N U P L O T
Version 5.4 patchlevel 5    last modified 2022-09-28

Copyright (C) 1986-1993, 1998, 2004, 2007-2022
Thomas Williams, Colin Kelley and many others

gnuplot home:     http://www.gnuplot.info
faq, bugs, etc:   type "help FAQ"
immediate help:   type "help"  (plot window: hit 'h')

Terminal type is now 'qt'
Options are '0 font "Arial,12"'
gnuplot> plot sin(x)
1   HIToolbox                           0x00000001ada9c5c8 _ZN15MenuBarInstance22EnsureAutoShowObserverEv + 120
2   HIToolbox                           0x00000001ada9c188 _ZN15MenuBarInstance14EnableAutoShowEv + 60
3   HIToolbox                           0x00000001ada3f310 SetMenuBarObscured + 372
4   HIToolbox                           0x00000001ada3eee8 _ZN13HIApplication15HandleActivatedEP14OpaqueEventRefhP15OpaqueWindowPtrh + 172
5   HIToolbox                           0x00000001ada38fcc _ZN13HIApplication13EventObserverEjP14OpaqueEventRefPv + 296
6   HIToolbox                           0x00000001ad9ffcd0 _NotifyEventLoopObservers + 176
7   HIToolbox                           0x00000001ada3896c AcquireEventFromQueue + 432
8   HIToolbox                           0x00000001ada27c84 ReceiveNextEventCommon + 320
9   HIToolbox                           0x00000001ada27b2c _BlockUntilNextEventMatchingListInModeWithFilter + 72
10  AppKit                              0x00000001a75d4424 _DPSNextEvent + 632
11  AppKit                              0x00000001a75d35b4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728
12  AppKit                              0x00000001a75c79e4 -[NSApplication run] + 464
13  libqcocoa.dylib                     0x000000010403d7a4 qt_plugin_instance + 174652
14  QtCore                              0x0000000101727f74 _ZN10QEventLoop4execE6QFlagsINS_17ProcessEventsFlagEE + 520
15  QtCore                              0x000000010172c5cc _ZN16QCoreApplication4execEv + 132
16  gnuplot_qt                          0x00000001000ceb70 main + 832
17  dyld                                0x00000001a3f4be50 start + 2544
gnuplot> 1   HIToolbox                           0x00000001ada2790c _ZN15MenuBarInstance22RemoveAutoShowObserverEv + 44
2   HIToolbox                           0x00000001ada3f214 SetMenuBarObscured + 120
3   HIToolbox                           0x00000001ada46390 _ZN13HIApplication11FrontUILostEv + 44
4   HIToolbox                           0x00000001ada3f04c _ZN13HIApplication15HandleActivatedEP14OpaqueEventRefhP15OpaqueWindowPtrh + 528
5   HIToolbox                           0x00000001ada38f70 _ZN13HIApplication13EventObserverEjP14OpaqueEventRefPv + 204
6   HIToolbox                           0x00000001ad9ffcd0 _NotifyEventLoopObservers + 176
7   HIToolbox                           0x00000001ada3896c AcquireEventFromQueue + 432
8   HIToolbox                           0x00000001ada27c84 ReceiveNextEventCommon + 320
9   HIToolbox                           0x00000001ada27b2c _BlockUntilNextEventMatchingListInModeWithFilter + 72
10  AppKit                              0x00000001a75d4424 _DPSNextEvent + 632
11  AppKit                              0x00000001a75d35b4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728
12  AppKit                              0x00000001a75c79e4 -[NSApplication run] + 464
13  libqcocoa.dylib                     0x000000010403d7a4 qt_plugin_instance + 174652
14  QtCore                              0x0000000101727f74 _ZN10QEventLoop4execE6QFlagsINS_17ProcessEventsFlagEE + 520
15  QtCore                              0x000000010172c5cc _ZN16QCoreApplication4execEv + 132
16  gnuplot_qt                          0x00000001000ceb70 main + 832
17  dyld                                0x00000001a3f4be50 start + 2544
gnuplot>
</code>```

Like I said, the graph displays fine and I get no errors, but this makes using gnuplot messy and cumbersome. I also never encountered this problem when using gnuplot form Ubuntu. Any ideas as to what could be causing it?

I tried changing the default qt terminal font (sans), that also caused an error message when plotting something, to Aerial in the .zshrc file - this solved the font issue but the text still appears.

Edit: found partial fix

After I encountered the exact same problem while using matplotlib 's show function, I looked it up and found this question on Stack Overflow to which I refer for details. I confirm the workaround works for gnuplot as well.

Body:
Sorry for the vagueness in the title, I don't know how else to describe it.
I am using gnuplot 5.4.5 on macOS Ventura 13.1. Whenever I try to plot something, wether a function or data from a file, the plot window containing the graph correctly appears, but the command line is littered with a bunch of text that I don't understand, like in the following example:

~ > gnuplot

G N U P L O T
Version 5.4 patchlevel 5    last modified 2022-09-28

Copyright (C) 1986-1993, 1998, 2004, 2007-2022
Thomas Williams, Colin Kelley and many others

gnuplot home:     http://www.gnuplot.info
faq, bugs, etc:   type "help FAQ"
immediate help:   type "help"  (plot window: hit 'h')

Terminal type is now 'qt'
Options are '0 font "Arial,12"'
gnuplot> plot sin(x)
1   HIToolbox                           0x00000001ada9c5c8 _ZN15MenuBarInstance22EnsureAutoShowObserverEv + 120
2   HIToolbox                           0x00000001ada9c188 _ZN15MenuBarInstance14EnableAutoShowEv + 60
3   HIToolbox                           0x00000001ada3f310 SetMenuBarObscured + 372
4   HIToolbox                           0x00000001ada3eee8 _ZN13HIApplication15HandleActivatedEP14OpaqueEventRefhP15OpaqueWindowPtrh + 172
5   HIToolbox                           0x00000001ada38fcc _ZN13HIApplication13EventObserverEjP14OpaqueEventRefPv + 296
6   HIToolbox                           0x00000001ad9ffcd0 _NotifyEventLoopObservers + 176
7   HIToolbox                           0x00000001ada3896c AcquireEventFromQueue + 432
8   HIToolbox                           0x00000001ada27c84 ReceiveNextEventCommon + 320
9   HIToolbox                           0x00000001ada27b2c _BlockUntilNextEventMatchingListInModeWithFilter + 72
10  AppKit                              0x00000001a75d4424 _DPSNextEvent + 632
11  AppKit                              0x00000001a75d35b4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728
12  AppKit                              0x00000001a75c79e4 -[NSApplication run] + 464
13  libqcocoa.dylib                     0x000000010403d7a4 qt_plugin_instance + 174652
14  QtCore                              0x0000000101727f74 _ZN10QEventLoop4execE6QFlagsINS_17ProcessEventsFlagEE + 520
15  QtCore                              0x000000010172c5cc _ZN16QCoreApplication4execEv + 132
16  gnuplot_qt                          0x00000001000ceb70 main + 832
17  dyld                                0x00000001a3f4be50 start + 2544
gnuplot> 1   HIToolbox                           0x00000001ada2790c _ZN15MenuBarInstance22RemoveAutoShowObserverEv + 44
2   HIToolbox                           0x00000001ada3f214 SetMenuBarObscured + 120
3   HIToolbox                           0x00000001ada46390 _ZN13HIApplication11FrontUILostEv + 44
4   HIToolbox                           0x00000001ada3f04c _ZN13HIApplication15HandleActivatedEP14OpaqueEventRefhP15OpaqueWindowPtrh + 528
5   HIToolbox                           0x00000001ada38f70 _ZN13HIApplication13EventObserverEjP14OpaqueEventRefPv + 204
6   HIToolbox                           0x00000001ad9ffcd0 _NotifyEventLoopObservers + 176
7   HIToolbox                           0x00000001ada3896c AcquireEventFromQueue + 432
8   HIToolbox                           0x00000001ada27c84 ReceiveNextEventCommon + 320
9   HIToolbox                           0x00000001ada27b2c _BlockUntilNextEventMatchingListInModeWithFilter + 72
10  AppKit                              0x00000001a75d4424 _DPSNextEvent + 632
11  AppKit                              0x00000001a75d35b4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728
12  AppKit                              0x00000001a75c79e4 -[NSApplication run] + 464
13  libqcocoa.dylib                     0x000000010403d7a4 qt_plugin_instance + 174652
14  QtCore                              0x0000000101727f74 _ZN10QEventLoop4execE6QFlagsINS_17ProcessEventsFlagEE + 520
15  QtCore                              0x000000010172c5cc _ZN16QCoreApplication4execEv + 132
16  gnuplot_qt                          0x00000001000ceb70 main + 832
17  dyld                                0x00000001a3f4be50 start + 2544
gnuplot>

Like I said, the graph displays fine and I get no errors, but this makes using gnuplot messy and cumbersome. I also never encountered this problem when using gnuplot form Ubuntu. Any ideas as to what could be causing it?

I tried changing the default qt terminal font (sans), that also caused an error message when plotting something, to Aerial in the .zshrc file - this solved the font issue but the text still appears.

Edit: found partial fix

After I encountered the exact same problem while using matplotlib 's show function, I looked it up and found this question on Stack Overflow to which I refer for details. I confirm the workaround works for gnuplot as well.


问:
Angular Karma/jasmine Unit testing, InjectorToken , RxJs
Im a Angular newbie and starting to write Unit Tests.
I have a simple Component, which loads data from RxJs - Subject.
Im not able to initialize the spec.ts file for testing does anyone now how to do
the correct implementation ?

Thats my Component

```<code>import { Component, Inject, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { fluxDispatcherToken } from 'src/app/shared/helpers/flux.configuration';
import { FluxStore } from 'src/app/shared/services/flux-store';
import { Account } from 'src/app/shared/types/account';
import { FluxAction, FluxActionTypes } from 'src/app/shared/types/actions.type';
import { CsvTransactionFormComponent } from './csv-transaction-form/csv-transaction-form.component';
import { ManualTransactionFormComponent } from './manual-transaction-form/manual-transaction-form.component';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.scss']
})
export class AccountComponent implements OnInit, OnDestroy {
  @ViewChild('manualTransactionModal') manualTransactionModal!: ManualTransactionFormComponent
  @ViewChild('csvTransactionModal') csvTransactionModal!: CsvTransactionFormComponent
  @Input() activeAccounts: Account[] = []

  accounts: Account[] = []
  selectedAccount?: Account
  data : string = 'noentry'
  private subscription: Subscription[] = []

  constructor(@Inject(fluxDispatcherToken) private dispatcher: Subject<FluxAction>, public store: FluxStore){}

  ngOnInit() {
    this.dispatcher.next(new FluxAction(FluxActionTypes.Load))
    this.subscription.push(this.store.Accounts.subscribe((data) => {
      if (data.length > 0) {
        this.data = 'data'
        this.accounts = data;
      }
      if (data.length === undefined) {
        this.data = 'isloading'
      }
      if (data.length === 0) {
        this.data = 'nodata'
        this.accounts = [];
      }
    }))
  }

  openManualTransactionModal(account: Account) {
    this.selectedAccount = account
    this.manualTransactionModal.manualtransactionform.nativeElement.classList.add('is-active')
  }

  openCsvTransactionModal(account: Account) {
    this.selectedAccount = account
    this.csvTransactionModal.modal.nativeElement.classList.add('is-active')
  }

  ngOnDestroy() {
    this.subscription.forEach((subscription) => {subscription.unsubscribe()})
  }
}
</code>```

And this is the Configuration for the  @Inject(fluxDispatcherToken)

```<code>import { InjectionToken } from '@angular/core'
import { Subject } from 'rxjs'
import { FluxAction } from '../types/actions.type'

export const fluxDispatcherToken = new InjectionToken('fluxActions')

export const fluxActionSubject = new Subject<FluxAction>()

export const FLUX_CONFIG = [
    { provide: fluxDispatcherToken, useValue: fluxActionSubject },
]
</code>```

Here is my test file spec.ts

```<code>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { AccountComponent } from "./account.component";
import { FluxStore } from 'src/app/shared/services/flux-store';
import { fluxDispatcherToken } from 'src/app/shared/helpers/flux.configuration';
import { FluxAction, FluxActionTypes } from 'src/app/shared/types/actions.type';
import { Subject } from 'rxjs';

describe("AccountComponent", () => {
  let component: AccountComponent;
  let fixture: ComponentFixture<AccountComponent>;
  let Store: FluxStore;
  let dispatcher: Subject<FluxAction>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [AccountComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        { provide: FluxStore, useValue: {} },
        { provide: fluxDispatcherToken, useValue: new Subject<FluxAction>() },
      ],
      imports: []
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AccountComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    Store = TestBed.inject(FluxStore);

  });

  describe('method1', () => {
    it('should ...', () => {
      expect(component).toBeTruthy();
    });
  });

})
</code>```

When I start to test there is a failure :
TypeError: Cannot read properties of undefined (reading 'subscribe')

Body:
Im a Angular newbie and starting to write Unit Tests.
I have a simple Component, which loads data from RxJs - Subject.
Im not able to initialize the spec.ts file for testing does anyone now how to do
the correct implementation ?

Thats my Component

import { Component, Inject, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { fluxDispatcherToken } from 'src/app/shared/helpers/flux.configuration';
import { FluxStore } from 'src/app/shared/services/flux-store';
import { Account } from 'src/app/shared/types/account';
import { FluxAction, FluxActionTypes } from 'src/app/shared/types/actions.type';
import { CsvTransactionFormComponent } from './csv-transaction-form/csv-transaction-form.component';
import { ManualTransactionFormComponent } from './manual-transaction-form/manual-transaction-form.component';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.scss']
})
export class AccountComponent implements OnInit, OnDestroy {
  @ViewChild('manualTransactionModal') manualTransactionModal!: ManualTransactionFormComponent
  @ViewChild('csvTransactionModal') csvTransactionModal!: CsvTransactionFormComponent
  @Input() activeAccounts: Account[] = []

  accounts: Account[] = []
  selectedAccount?: Account
  data : string = 'noentry'
  private subscription: Subscription[] = []

  constructor(@Inject(fluxDispatcherToken) private dispatcher: Subject<FluxAction>, public store: FluxStore){}

  ngOnInit() {
    this.dispatcher.next(new FluxAction(FluxActionTypes.Load))
    this.subscription.push(this.store.Accounts.subscribe((data) => {
      if (data.length > 0) {
        this.data = 'data'
        this.accounts = data;
      }
      if (data.length === undefined) {
        this.data = 'isloading'
      }
      if (data.length === 0) {
        this.data = 'nodata'
        this.accounts = [];
      }
    }))
  }

  openManualTransactionModal(account: Account) {
    this.selectedAccount = account
    this.manualTransactionModal.manualtransactionform.nativeElement.classList.add('is-active')
  }

  openCsvTransactionModal(account: Account) {
    this.selectedAccount = account
    this.csvTransactionModal.modal.nativeElement.classList.add('is-active')
  }

  ngOnDestroy() {
    this.subscription.forEach((subscription) => {subscription.unsubscribe()})
  }
}

And this is the Configuration for the  @Inject(fluxDispatcherToken)

import { InjectionToken } from '@angular/core'
import { Subject } from 'rxjs'
import { FluxAction } from '../types/actions.type'

export const fluxDispatcherToken = new InjectionToken('fluxActions')

export const fluxActionSubject = new Subject<FluxAction>()

export const FLUX_CONFIG = [
    { provide: fluxDispatcherToken, useValue: fluxActionSubject },
]

Here is my test file spec.ts

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { AccountComponent } from "./account.component";
import { FluxStore } from 'src/app/shared/services/flux-store';
import { fluxDispatcherToken } from 'src/app/shared/helpers/flux.configuration';
import { FluxAction, FluxActionTypes } from 'src/app/shared/types/actions.type';
import { Subject } from 'rxjs';

describe("AccountComponent", () => {
  let component: AccountComponent;
  let fixture: ComponentFixture<AccountComponent>;
  let Store: FluxStore;
  let dispatcher: Subject<FluxAction>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [AccountComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        { provide: FluxStore, useValue: {} },
        { provide: fluxDispatcherToken, useValue: new Subject<FluxAction>() },
      ],
      imports: []
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AccountComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    Store = TestBed.inject(FluxStore);

  });

  describe('method1', () => {
    it('should ...', () => {
      expect(component).toBeTruthy();
    });
  });

})

When I start to test there is a failure :
TypeError: Cannot read properties of undefined (reading 'subscribe')


问:
Invalid API key of VisionAI
I have created a project that detects the prescription. I have used API key of VisionAI to process the request. After entering the API key in the code Im getting an error "Invalid Key". I have entered the credit card details correctly.

I want to know how to get the valid API key  to detect the contents in the image

Title: Invalid API key of VisionAI


问:
pass object array keycloak configurations to spring boot backend application
well so. my env variables are:

```<code>keycloak.policy-enforcer-config.paths[0].path=/user;
keycloak.policy-enforcer-config.paths[1].path=/company;
    ...
keycloak.policy-enforcer-config.paths[12].path=/healthz;
keycloak.policy-enforcer-config.paths[12].enforcement-mode=DISABLED
</code>```

and it all works fine.

but the problem occurs when passing those env variables in the Kubernetes deployment.yaml
as using a square bracket on environment variable in Kubernetes is not possible.
I have tried using it as:

```<code>- name: "keycloak.policy-enforcer-config.paths__12__path"
    value: "/healthz"
- name: "keycloak.policy-enforcer-config.paths__12__enforcement-mode"
    value: "DISABLED"
</code>```

but it cannot read the env variables.

and surprisingly, it's the same on my local machine too.if I name those with _, I cannot reach the env variables
so the following is not working;

```<code>keycloak.policy-enforcer-config.paths__0__.path=/user;
keycloak.policy-enforcer-config.paths__1__.path=/company;
    ...
keycloak.policy-enforcer-config.paths__12__path=/healthz;
keycloak.policy-enforcer-config.paths__12__enforcement-mode=DISABLED
</code>```

based on what I read new binder supports using _ but as I said it's not working on my case.

could you please show me the way?

Body:
well so. my env variables are:

keycloak.policy-enforcer-config.paths[0].path=/user;
keycloak.policy-enforcer-config.paths[1].path=/company;
    ...
keycloak.policy-enforcer-config.paths[12].path=/healthz;
keycloak.policy-enforcer-config.paths[12].enforcement-mode=DISABLED

and it all works fine.

but the problem occurs when passing those env variables in the Kubernetes deployment.yaml
as using a square bracket on environment variable in Kubernetes is not possible.
I have tried using it as:

- name: "keycloak.policy-enforcer-config.paths__12__path"
    value: "/healthz"
- name: "keycloak.policy-enforcer-config.paths__12__enforcement-mode"
    value: "DISABLED"

but it cannot read the env variables.

and surprisingly, it's the same on my local machine too.if I name those with _, I cannot reach the env variables
so the following is not working;

keycloak.policy-enforcer-config.paths__0__.path=/user;
keycloak.policy-enforcer-config.paths__1__.path=/company;
    ...
keycloak.policy-enforcer-config.paths__12__path=/healthz;
keycloak.policy-enforcer-config.paths__12__enforcement-mode=DISABLED

based on what I read new binder supports using _ but as I said it's not working on my case.

could you please show me the way?


问:
How to open an excel file in heroku?
I'm using heroku with streamlit to do excel automations. But I need to execute the excel formulas so I can get the values computed by them, and to do so I would need to open the excel file. As it is an RPA, I don't want to open the excel file myself, manually, I want the code to open it for me inside the system and execute the formulas, so the code opens the sheet with pandas or openpyxl and get the values provided by the formulas. As heroku runs on linux, OS is not an option. I've tried xlwings a long time ago and it did not work as well, but I'll study it and see if it works, but if you guys have some other recommendation for me, that works better than xlwings (or even something about xlwings usage), it would be really helpfull!
Thanks in advance!

I have already tried to use pandas and openpyxl data_only=True to get the values computed by formulas, but both only work once the excel file has been opened manually, executing all formulae. I want to simulate the manual opening of the excel file inside heroku, but without literally opening it, so formulas inside the file are executed.

Title: How to open an excel file in heroku?


问:
Add Promotion after jenkins pipeline
I know well Jenkins free-style jobs, but I'm new to pipelines.
I'm reworking some validation pipelines to add a manual step/pause before the final publication/diffusion step.
I've read about the input directive, but it's not what we want.
Our need is to be able to run the same pipeline several (10) times with different parameters, and afterwards, make a manual check on some or all the runs, eventually update some repports. Then go on with downstream operations (basically officially publish the reports, for QA team or others).

I used to do such things easily with free-style jobs, and manual promotions (restricted to authorized users). It's safe because all the build artefacts are saved at the end of the free-style job, and can be post-processed later.
Is there a way to achieve such thing in a pipeline ? (adding properties / promotions)
A key point for us is that the same pipeline job should be run several time, so each time the artefacts should be stored in a different location/workspace.

I used the input directive. It's expecting an interractive input.
If I launch the same job again, I'm afraid it will use the same workspace.

I added a free-style job, triggered after the pipeline job.
in this job, I retrieve the artefacts from the first job. The promotion does the job, but it's quite ugly implementation.

I tried to add a promotion using properties + promotions, but I'm not sure if I can do the same thing as a manual promotion in a free-style job. That's what I would like to do, to keep all things in the pipeline.
I have searched for some time, but I did not found much about it.

I have read some things like
https://issues.jenkins.io/browse/JENKINS-36089
or
https://www.jenkins.io/projects/gsoc/2019/artifact-promotion-plugin-for-jenkins-pipeline/
which say it's not possible.
But I'm sure some people have the same need, so some solutions should exist.

Title: Add Promotion after jenkins pipeline


问:
Bash prompt with custom PS1 including current git branch gets corrupt when using reverse-i-search etc
This is not a duplicate against the suggested question. The problem turns out to be how to call a function from within PS1 (which requires escaping the function call), and have that function return a string with escape (color) codes.

Using Bash on MacBook Pro M1, in my ~/.bash_profile I have some logic to provide a nice prompt including the current directory, current git branch etc. Also I have some coloring sequences to make the prompt look e.g. something like this (but with colors):

```<code>myuser ~/somepath (master, 1 file changed) $
</code>```

However, I have a really annoying problem. Whenever a line gets too long, or I use cmd-R (reverse-i-search) to browse previous commands, the cursor will end up in the wrong place and/or the line will be cropped on the screen, making it impossible to alter a previously used line to add a new argument etc, since editing the line will just result in garbage.

My PS1 looks like this (simplified a bit since I managed to boil down to what causes the error described below to appear):

```<code>parse_git_branch() {
    BRANCH=$(git branch --show-current 2> /dev/null)

    if [[ -n $BRANCH ]]; then
        # Add (<branch-name>) in purple to the prompt
        echo -e "\033[95m(${BRANCH})\033[00m"
    fi
}
# Prompt is "<username in yellow> <path in green> <git info> $ "
export PS1="\[\e[33m\]\u \[\e[32m\]\w \[\e[91m\]\$(parse_git_branch)\[\e[00m\]$ "
</code>```

And this looks fine - the git branch name is added in purple color at the end of the prompt. But as soon as I start scrolling through bash history by using CMD-R or just going up to a previous command, it will behave strangely. For example, If I simply do

```<code>myuser ~/somepath (master)$ ls src
</code>```

And then press CMD-r and type ls, normally the prompt will behave like this:

```<code>(reverse-i-search)`ls': ls src
</code>```

If I press e.g. cursor right, I will be able to edit that command with the cursor placed on the match (in this case on the l in ls).

But with my prompt, instead it will display

```<code>myuser ~/somepath (master)$ rch)`ls': ls src
</code>```

with the cursor on the c in rch. And typing foo will result in

```<code>myuser ~/somepath (master)$ rfooch)`ls': ls src
</code>```

Which if pressing enter will in turn (obviously) result in:

```<code>-bash: lfoos: command not found
</code>```

Clearly something is wrong here with how the line is rendered and where the cursor is placed, and where it appears to be.

I noticed that if I remove the escape sequences for coloring from my parse_git_branch, it works:

```<code>parse_git_branch() {
    BRANCH=$(git branch --show-current 2> /dev/null)

    if [[ -n $BRANCH ]]; then
        echo -e "(${BRANCH})"
    fi
}
export PS1="\[\e[33m\]\u \[\e[32m\]\w \[\e[91m\]\$(parse_git_branch)\[\e[00m\]$ "
</code>```

So I guess there's something wrong with the coloring sequences. I'm not very good at bash escape sequences so I mostly copied these coloring sequences from somewhere, and I guess there's a side-effect I don't understand.

Does anyone know why adding these sequences to the string echoed by parse_git_branch will cause the prompt to look fine, but overwrite partial lines and behave as if the cursor is in a different position than it actually is when I start re-using old commands or use reverse-i-search?

Body:
This is not a duplicate against the suggested question. The problem turns out to be how to call a function from within PS1 (which requires escaping the function call), and have that function return a string with escape (color) codes.

Using Bash on MacBook Pro M1, in my ~/.bash_profile I have some logic to provide a nice prompt including the current directory, current git branch etc. Also I have some coloring sequences to make the prompt look e.g. something like this (but with colors):

myuser ~/somepath (master, 1 file changed) $

However, I have a really annoying problem. Whenever a line gets too long, or I use cmd-R (reverse-i-search) to browse previous commands, the cursor will end up in the wrong place and/or the line will be cropped on the screen, making it impossible to alter a previously used line to add a new argument etc, since editing the line will just result in garbage.

My PS1 looks like this (simplified a bit since I managed to boil down to what causes the error described below to appear):

parse_git_branch() {
    BRANCH=$(git branch --show-current 2> /dev/null)

    if [[ -n $BRANCH ]]; then
        # Add (<branch-name>) in purple to the prompt
        echo -e "\033[95m(${BRANCH})\033[00m"
    fi
}
# Prompt is "<username in yellow> <path in green> <git info> $ "
export PS1="\[\e[33m\]\u \[\e[32m\]\w \[\e[91m\]\$(parse_git_branch)\[\e[00m\]$ "

And this looks fine - the git branch name is added in purple color at the end of the prompt. But as soon as I start scrolling through bash history by using CMD-R or just going up to a previous command, it will behave strangely. For example, If I simply do

myuser ~/somepath (master)$ ls src

And then press CMD-r and type ls, normally the prompt will behave like this:

(reverse-i-search)`ls': ls src

If I press e.g. cursor right, I will be able to edit that command with the cursor placed on the match (in this case on the l in ls).

But with my prompt, instead it will display

myuser ~/somepath (master)$ rch)`ls': ls src

with the cursor on the c in rch. And typing foo will result in

myuser ~/somepath (master)$ rfooch)`ls': ls src

Which if pressing enter will in turn (obviously) result in:

-bash: lfoos: command not found

Clearly something is wrong here with how the line is rendered and where the cursor is placed, and where it appears to be.

I noticed that if I remove the escape sequences for coloring from my parse_git_branch, it works:

parse_git_branch() {
    BRANCH=$(git branch --show-current 2> /dev/null)

    if [[ -n $BRANCH ]]; then
        echo -e "(${BRANCH})"
    fi
}
export PS1="\[\e[33m\]\u \[\e[32m\]\w \[\e[91m\]\$(parse_git_branch)\[\e[00m\]$ "

So I guess there's something wrong with the coloring sequences. I'm not very good at bash escape sequences so I mostly copied these coloring sequences from somewhere, and I guess there's a side-effect I don't understand.

Does anyone know why adding these sequences to the string echoed by parse_git_branch will cause the prompt to look fine, but overwrite partial lines and behave as if the cursor is in a different position than it actually is when I start re-using old commands or use reverse-i-search?


问:
How to setup real time video in react native using streams of array buffer (of images) from node js back
Iam getting array buffer of image data from ESP32 cam module and sending that data in realtime to a node js server using socket-io and which in turn sends those array buffer of images to a react native front. But at first i was able to send those buffer array images to a webpage and was able to generate a live stream video playback using the below code.

```<code><!DOCTYPE html>
<html>
<%- include('./partials/head.ejs') %>
<% let test = end %>
<body class="page_display">
    <div class="main_content">
        <div class="page_title"><h1 class="tcenter">Streaming ESPCAM</h1></div>
        <div class="tcenter">

            <canvas id="canvas">
                Lo sentimos, su navegador no es compatible <canvas>.
            </canvas>
        </div>
    </div>
    <script src="/socket.io/socket.io.js"></script>
    <script>
    const socket = io('http://192.168.1.3:5000');
    let video1 = document.getElementById('video1');
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var context = new AudioContext();
    var sampleRate = 48000;
    var startAt = 0;
    var img = new Image();
    img.onload = function() {
            canvas.style.width=this.width+'px';
            canvas.style.height=this.height+'px';
            ctx.drawImage(this, 0, 0, this.width,    this.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle
    }

    socket.on('emittobrowser', function (message) {
        // console.log('message',message);
        console.log('message',new Blob([message]));
        var url = URL.createObjectURL(new Blob([message]));
        console.log('url',url);
        img.src = url;
    });

    </script>
</body>
</html>

</code>```

In the above code i was able to use canvas and image object to get a live stream video from the image array buffers i get by listening to the nodejs socket 'emittobrowser' event.

But when i try to get the same in react native, I was not able to do it. First I got a library called react-native-canvas as a alternative to canvas element in html and also there was a Image constructor in the react-native-canvas library that I was able to use instead of the Image constructor available in the website code. But there was no createObjectURL() method on the URL object available and all i could find, which is somewhat closer, was FileReader class and its method called readAsDataURL(). The code that i've managed to write in react-native is given below , which is not working.

```<code>
import { StyleSheet, Text, View,Dimensions } from 'react-native'
import React, { useEffect, useRef, useState } from 'react'
import {io} from 'socket.io-client';
import { Socket } from 'socket.io-client/build/esm/socket';
import Canvas,{Image} from 'react-native-canvas';

let socket:Socket;
let img:Image;
const {width,height} = Dimensions.get('window');
const reader = new FileReader();
reader.addEventListener("load",()=>{
 img.src = reader.result
},false)
const App = () => {

  const canvasRef = useRef<Canvas>();

  useEffect(()=>{
    socket = io('http://192.168.1.3:5000');
    socket.on('emittobrowser', function (message) {
    const blob = new Blob([buffer]);
    reader.readAsDataURL(blob);

    });
      },[]
        );

  const initialize = () =>{
    img = new Image(canvasRef.current!);
    const ctx = canvasRef.current!.getContext('2d');
    img.addEventListener("load",()=>{
      console.log("load event triggered")
      canvasRef.current!.width=width;
      canvasRef.current!.height=height;
      ctx.drawImage(img, 0, 0, width,  height, 0, 0, canvasRef.current!.width, canvasRef.current!.height);
    })

  }
  return (
    <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
      <Text>App</Text>
      <Canvas ref={c=>{
        canvasRef.current=c
        initialize();

      }} style={{height:500,width:500,borderWidth:2}}/>
    </View>
  )
}

export default App

const styles = StyleSheet.create({})
</code>```

Can anyone show me a alternative code for react-native.

Body:
Iam getting array buffer of image data from ESP32 cam module and sending that data in realtime to a node js server using socket-io and which in turn sends those array buffer of images to a react native front. But at first i was able to send those buffer array images to a webpage and was able to generate a live stream video playback using the below code.

<!DOCTYPE html>

<%- include('./partials/head.ejs') %>
<% let test = end %>

Streaming ESPCAM

            <canvas id="canvas">
                Lo sentimos, su navegador no es compatible <canvas>.
            </canvas>

In the above code i was able to use canvas and image object to get a live stream video from the image array buffers i get by listening to the nodejs socket 'emittobrowser' event.

But when i try to get the same in react native, I was not able to do it. First I got a library called react-native-canvas as a alternative to canvas element in html and also there was a Image constructor in the react-native-canvas library that I was able to use instead of the Image constructor available in the website code. But there was no createObjectURL() method on the URL object available and all i could find, which is somewhat closer, was FileReader class and its method called readAsDataURL(). The code that i've managed to write in react-native is given below , which is not working.

import { StyleSheet, Text, View,Dimensions } from 'react-native'
import React, { useEffect, useRef, useState } from 'react'
import {io} from 'socket.io-client';
import { Socket } from 'socket.io-client/build/esm/socket';
import Canvas,{Image} from 'react-native-canvas';

let socket:Socket;
let img:Image;
const {width,height} = Dimensions.get('window');
const reader = new FileReader();
reader.addEventListener("load",()=>{
 img.src = reader.result
},false)
const App = () => {

  const canvasRef = useRef<Canvas>();

  useEffect(()=>{
    socket = io('http://192.168.1.3:5000');
    socket.on('emittobrowser', function (message) {
    const blob = new Blob([buffer]);
    reader.readAsDataURL(blob);

    });
      },[]
        );

  const initialize = () =>{
    img = new Image(canvasRef.current!);
    const ctx = canvasRef.current!.getContext('2d');
    img.addEventListener("load",()=>{
      console.log("load event triggered")
      canvasRef.current!.width=width;
      canvasRef.current!.height=height;
      ctx.drawImage(img, 0, 0, width,  height, 0, 0, canvasRef.current!.width, canvasRef.current!.height);
    })

  }
  return (
    <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
      <Text>App</Text>
      <Canvas ref={c=>{
        canvasRef.current=c
        initialize();

      }} style={{height:500,width:500,borderWidth:2}}/>
    </View>
  )
}

export default App

const styles = StyleSheet.create({})

Can anyone show me a alternative code for react-native.


问:
Python: Same or different method names in MVC
I am currently writing a booking system and I'm following MVC.
My question is what is considered a better practice:

All methods from the different packages along the line of a single operation to have the same names

Come up with different names for each method?

To clarify my questions, here is an example:
When booking an appointment, that's the current sequence:

The toplevel windows calls root.book_appointment() (root is the "controller" of the view package)

root calls controller.book_appointment()

controller calls model.book_appointment()

model calls database.book_appointment()

I tried to find a convention or opinions somewhere, but I could not find anything.
One way, everything has the same names, even though there is always an identifier before the method call(root, controller, model, database etc). On the other hand for every operation that starts from a panel I need to come up with another 5 method names until I reach the database.

Thanks a lot in advance for your time and answers!

Tried googling for answers, but nothing came up. Most answers were for methods with same names and different parameters.


问:
When reading CSV file, how to set default value to properties when doing mapping
My application reads .CSV file(which does not have a header in CSV file) and converts it into XML file.I am using CSVHelper version v2.0. For existing code written as

```<code>sr = new StreamReader(fs);
fs = null;

using (CsvReader csvReader = new CsvReader(sr))
{
    sr = null;

    csvReader.Configuration.HasHeaderRecord = hasHeaderRecord;
    csvReader.Configuration.IgnoreBlankLines = false;
    csvReader.Configuration.IgnoreReadingExceptions = true;
    csvReader.Configuration.WillThrowOnMissingField = false;
    csvReader.Configuration.TrimFields = true;

    csvReader.Configuration.RegisterClassMap<Class1Map>();
    FileRecords = csvReader.GetRecords<Class1>().ToList();
}

    public class Class1Map : CsvClassMap<Class1>
        {
            public Class1Map()
            {
                Map(m => m.AccountId).Index(0);
                Map(m => m.MeterId).Index(1);
                .......
                .......
            }
         }
</code>```

For now, I have a new CSV file. This time, the new CSV file has a header, and header names are not identical to class1 properties. Using bool flag, I am identifying whether it is an old file OR new file by passing value into class1Map constructor.

```<code>public Class1Map(bool IsNewCSV=false)
        {
            if (IsNewCSV)
            {
                Map(m => m.AccountId).Name("ACCOUNTREF");
                Map(m => m.MeterId).Name("MeterREF");
                Map(m => m.IsEnable).Name("IsEnable").Default("");
                Map(m => m.CheckID).Default("");
            }
           else
            {
                Map(m => m.AccountId).Index(0);
                Map(m => m.MeterId).Index(1);
                Map(m => m.IsEnable).Index(2);
                Map(m => m.CheckId).Index(3);
            }
}
</code>```

For new CSV some of the properties are always empty. i.e. IsEnable, CheckID values are empty always and for old CSV files, values will be available in the file.

Now I am getting IsEnable=NULL and CheckID=0 for the new CSV file. I want both values will be empty values as we are not providing values in the new CSV file.
I tried with default(). But still am getting null and 0 values in the list.

Can anyone suggest a way to implement it?

Body:
My application reads .CSV file(which does not have a header in CSV file) and converts it into XML file.I am using CSVHelper version v2.0. For existing code written as

sr = new StreamReader(fs);
fs = null;

using (CsvReader csvReader = new CsvReader(sr))
{
    sr = null;

    csvReader.Configuration.HasHeaderRecord = hasHeaderRecord;
    csvReader.Configuration.IgnoreBlankLines = false;
    csvReader.Configuration.IgnoreReadingExceptions = true;
    csvReader.Configuration.WillThrowOnMissingField = false;
    csvReader.Configuration.TrimFields = true;

    csvReader.Configuration.RegisterClassMap<Class1Map>();
    FileRecords = csvReader.GetRecords<Class1>().ToList();
}

    public class Class1Map : CsvClassMap<Class1>
        {
            public Class1Map()
            {
                Map(m => m.AccountId).Index(0);
                Map(m => m.MeterId).Index(1);
                .......
                .......
            }
         }

For now, I have a new CSV file. This time, the new CSV file has a header, and header names are not identical to class1 properties. Using bool flag, I am identifying whether it is an old file OR new file by passing value into class1Map constructor.

public Class1Map(bool IsNewCSV=false)
        {
            if (IsNewCSV)
            {
                Map(m => m.AccountId).Name("ACCOUNTREF");
                Map(m => m.MeterId).Name("MeterREF");
                Map(m => m.IsEnable).Name("IsEnable").Default("");
                Map(m => m.CheckID).Default("");
            }
           else
            {
                Map(m => m.AccountId).Index(0);
                Map(m => m.MeterId).Index(1);
                Map(m => m.IsEnable).Index(2);
                Map(m => m.CheckId).Index(3);
            }
}

For new CSV some of the properties are always empty. i.e. IsEnable, CheckID values are empty always and for old CSV files, values will be available in the file.

Now I am getting IsEnable=NULL and CheckID=0 for the new CSV file. I want both values will be empty values as we are not providing values in the new CSV file.
I tried with default(). But still am getting null and 0 values in the list.

Can anyone suggest a way to implement it?


问:
Get tls keys from a powershell call
I was using wireshark to see some https packets when trying to access an website through any WebBrowser. Pretty much we just store the tls session keys in a env variable called SSLKEYLOGFILE to an txt file and then ask wireshark to use it in order to decrypt.

I also have a powershell script that uses some APIs from a website and I just would like to know if/how can I get the tls session keys to decrypt a https traffic that was generated by my Invoke-WebRequest call in powershell.

I have tried the same steps for browser tsl key tracking but no success. Just hoping if I can have the same but for when I execute a powershell call to an website

Thanks

Title: Get tls keys from a powershell call


问:
Filtering estimates of the orientation using optimization
I am trying to implement Algorithm 2 (p.38) from Kok et al. 2017, for calculating G_{t-1}, I need R tilda. It is explained as "a linearization point parametrized either as a unit quaternion or rotation matrix R tilda and an orientation deviation using a rotation vector" (p.22). My question is how to initialize it in the algorithm. Thanks in advance for the response.</p>


问:
Is there С# [TestCase] attribute analog for PHPUnit?
It's the test example for C# using NUnit from Microsoft docs

[TestCase(-1)]
[TestCase(0)]
[TestCase(1)]
public void IsPrime_ValuesLessThan2_ReturnFalse(int value)
{
    var result = _primeService.IsPrime(value);

    Assert.IsFalse(result, $"{value} should not be prime");
}
```

Here we use just one function but 3 tests will be executed with different parameters: -1, 0, 1. Thanks to [TestCase] attribute.

Is there a way we can do the same in PHPUnit? Or maybe there is some other library/framework for writing tests in php with this feature?

Body:
It's the test example for C# using NUnit from Microsoft docs

[TestCase(-1)]
[TestCase(0)]
[TestCase(1)]
public void IsPrime_ValuesLessThan2_ReturnFalse(int value)
{
    var result = _primeService.IsPrime(value);

    Assert.IsFalse(result, $"{value} should not be prime");
}

Here we use just one function but 3 tests will be executed with different parameters: -1, 0, 1. Thanks to [TestCase] attribute.

Is there a way we can do the same in PHPUnit? Or maybe there is some other library/framework for writing tests in php with this feature?


问:
GSheets Multi-Select Dropdown affects entire worksheet instead of a specific sheet
I am new to this and I found an old post with this code. I am currently using it but it affects all tabs of my spreadsheet. Is there a way for it to work on a specific tab only? Thank you.

```<code>`const separator = ', ';
const dvType = SpreadsheetApp.DataValidationCriteria.VALUE_IN_RANGE;

function onEdit(e) {
  if (e.value != null && e.oldValue != null && e.value !== "") {
    var dataValidation = e.range.getDataValidation();
    if(dataValidation != null && dataValidation.getCriteriaType() == dvType &&
      e.value.indexOf(separator) < 0 && e.oldValue.indexOf(e.value) < 0) {
        e.range.setValue(e.oldValue + separator + e.value);
    }
  }
}`
</code>```

I tried to change the criteria but since I am new to coding, I always get error.

Body:
I am new to this and I found an old post with this code. I am currently using it but it affects all tabs of my spreadsheet. Is there a way for it to work on a specific tab only? Thank you.

`const separator = ', ';
const dvType = SpreadsheetApp.DataValidationCriteria.VALUE_IN_RANGE;

function onEdit(e) {
  if (e.value != null && e.oldValue != null && e.value !== "") {
    var dataValidation = e.range.getDataValidation();
    if(dataValidation != null && dataValidation.getCriteriaType() == dvType &&
      e.value.indexOf(separator) < 0 && e.oldValue.indexOf(e.value) < 0) {
        e.range.setValue(e.oldValue + separator + e.value);
    }
  }
}`

I tried to change the criteria but since I am new to coding, I always get error.


问:
How to disable onClick splash in Flutter WebView
I'm new to flutter and would appreciate some help.

I have simple app with WebView. And when I click some button or another widget on page, opened in WebView, this button is highlighted like this (not my screenshot, just an example)

(https://i.stack.imgur.com/nJ5dt.png)

Can I disable this highlight or change color to transparent?


问:
How to get calender for selected date and month only in javascript
I want to get the datepicket calender for the selected month and year using jquery/javascript.

for example, if i select the year to 2023 and month january then, the date field should show January 2023 calender only. like mindate is 2023-01-01 and maxdate is 2023-01-31.

I tried some online methods but they are not working though jquery/javascript. Can somebody help me to getting out of this


问:
Send Discussion Message Pyrogram
How to send message to chat discussion group?

I want to know, how to send message to chat discussion group
I think its: app.send_message(channelDiscussId, text, {reply_to_message_id: msgId}) but how to get 'channelDiscussId' ?

Title: Send Discussion Message Pyrogram


问:
Folders in the same tree adds to breadcrumbs rather than replacing the last folder in the breadcrumb
I am currently making a breadcrumbs section for a website. Ignoring files, I want the folders to appear in the breadcrumbs when the folder name is clicked in the sidebar.

However, when there are 2 folders inside the same folder and I click the both of them, I want the latest folder clicked to appear on the breadcrumbs, and not the both of them. Is this possible?

I am currently using sveltekit and breadcrumbs from DaisyUI.

Currently, I have a function sidebarfolder in sidebar.svelte that changes currentFolder when folder name is clicked

When currentFolder changes, it gets added to currentFolderFlow. This currentFolderFlow will then be the sequence of the breadcrumbs

Folders.json

[
    {
      "name": "Documents",
      "files": [
        {
          "name": "Quarterly Results"
        }
      ]
    },
    {
      "name": "Favourites",
      "files": [
        {
          "name": "Brawl Stars",
          "files": [
            {
              "name": "NS dying in 5 seconds"
            },
            {
              "name": "Josiah raping NS"
            }
          ]
        },
        {
          "name": "Coding",
          "files": [
            {
              "name": "Coding is so fun"
            },
            {
              "name": "I love svelte",
              "files": [
                {
                  "name": "REPL"
                },
                {
                  "name": "oh nooo"
                }
              ]
            }
          ]
        },
        {
          "name": "Favourites 1"
        },
        {
          "name": "Favourites 2"
        },
        {
          "name": "Favourites 3"
        }
      ]
    },
    {
      "name": "Knowledge Base 1"
    }
  ]
```
<p><strong>Sidebar.svelte</strong></p>
<pre class="lang-html prettyprint-override"><code><script>
export let currentFolder
    export let currentFolderFlow
    export let expanded = false;
    export let name;
    export let files;

const sideBarFolder = (folderName) => {
        if (currentFolder === folderName) {
            return false
        }

        currentFolder = folderName

        if (!currentFolderFlow.includes(folderName)) {
        currentFolderFlow = [...currentFolderFlow, folderName]
        } else {
            currentFolderFlow = currentFolderFlow.filter(i => currentFolderFlow.indexOf(i) <= currentFolderFlow.indexOf(folderName))
        }
    }
</script>

<button class=" pl-1" on:click={() => sideBarFolder(name)}>{name}</button>
</code>```

Main page

            {#each currentFolderFlow as folderFlow}

{folderFlow}

            {/each}

```

Body:
I am currently making a breadcrumbs section for a website. Ignoring files, I want the folders to appear in the breadcrumbs when the folder name is clicked in the sidebar.

However, when there are 2 folders inside the same folder and I click the both of them, I want the latest folder clicked to appear on the breadcrumbs, and not the both of them. Is this possible?

I am currently using sveltekit and breadcrumbs from DaisyUI.

Currently, I have a function sidebarfolder in sidebar.svelte that changes currentFolder when folder name is clicked

When currentFolder changes, it gets added to currentFolderFlow. This currentFolderFlow will then be the sequence of the breadcrumbs

Folders.json

[
    {
      "name": "Documents",
      "files": [
        {
          "name": "Quarterly Results"
        }
      ]
    },
    {
      "name": "Favourites",
      "files": [
        {
          "name": "Brawl Stars",
          "files": [
            {
              "name": "NS dying in 5 seconds"
            },
            {
              "name": "Josiah raping NS"
            }
          ]
        },
        {
          "name": "Coding",
          "files": [
            {
              "name": "Coding is so fun"
            },
            {
              "name": "I love svelte",
              "files": [
                {
                  "name": "REPL"
                },
                {
                  "name": "oh nooo"
                }
              ]
            }
          ]
        },
        {
          "name": "Favourites 1"
        },
        {
          "name": "Favourites 2"
        },
        {
          "name": "Favourites 3"
        }
      ]
    },
    {
      "name": "Knowledge Base 1"
    }
  ]

Sidebar.svelte

<button class=" pl-1" on:click={() => sideBarFolder(name)}>{name}</button>

Main page

            {#each currentFolderFlow as folderFlow}

{folderFlow}

            {/each}


问:
OAEP Padding error occurs when C# decrypts data encrypted with RSA in NodeJS crypto module
I have created a C# Client and NodeJS Server that communicate with WebsocketsAnd I encrypted the message passing through the socket with RSAThe data encrypted by the client using the public key could be decrypted by the server, but the data encrypted by the server by the private key could not be decrypted by the client. and then an error occurred 'System.Security.Cryptography.CryptographicException: 'Error occurred while decoding OAEP padding.'

Client code - Form1.cs

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using System;
using System.IO;
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Something Namespace
{
    public partial class Form1: Form
    {
        private ClientWebSocket ws = new ClientWebSocket();
        public Login(string[] args)
        {
            InitializeComponent();
        }

        private async void Login_Load(object sender, EventArgs e)
        {
            RSACryptoServiceProvider RSA = ImportPublicKey("Something Public Key");
            string MessageEncrypted = Convert.ToBase64String(RSA.Encrypt(Encoding.UTF8.GetBytes("Hi I am Client"), true));
            MessageBox.Show(MessageEncrypted);
            Uri serverUri = new Uri("ws://localhost:3000/");
            await ws.ConnectAsync(serverUri, CancellationToken.None);
            ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(MessageEncrypted));
            await ws.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
            while (ws.State == WebSocketState.Open)
            {
                ArraySegment<byte> bytesReceived = new ArraySegment<byte>(new byte[2048]);
                WebSocketReceiveResult result = await ws.ReceiveAsync(bytesReceived, CancellationToken.None);
                string response = Encoding.UTF8.GetString(bytesReceived.Array, 0, result.Count);

                MessageBox.Show(response);
                if (response != "Hi I am Client")
                {
                    RSA.Decrypt(Convert.FromBase64String(response), true);
                }
            }
        }

        public static RSACryptoServiceProvider ImportPublicKey(string pem)
        {
            PemReader pr = new PemReader(new StringReader(pem));
            AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter)pr.ReadObject();
            RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaKeyParameters)publicKey);

            RSACryptoServiceProvider csp = new RSACryptoServiceProvider();;
            csp.ImportParameters(rsaParams);
            return csp;
        }
    }
}
```
<p>Server code - index.js</p>
<pre class="lang-js prettyprint-override"><code>require('dotenv').config();
const express = require('express');

const app = express();

async function initialize() {
    // app.use(express.static(__dirname + '/public'));
    var server = await require('./server')(app);
    var ws = await require('./socket')(server);

    // bot
}

initialize();
</code>```

Server code - server.js

module.exports = async (app) => {
    ...

    await loadMiddlewares();
    await loadRoutes();
    await checkDatabase();
    return await app.listen(app.get('port'), () => {
        logger.info(`${process.env.SERVER_NAME} server started on port ${app.get('port')}`);
    });
};
```
<p>Server code - socket.js</p>
<pre class="lang-js prettyprint-override"><code>const webSocket = require('ws');
const rsa = require('./modules/rsa')

module.exports = (server) => {
    const ws = new webSocket.Server({ server });

    ws.on('connection', (client, req) => {
        client.id = req.headers['sec-websocket-key'];
        ws.clients[client.id] = client;

        client.on('message', (message) => {
            switch (req.url) {
                default:
                    console.log('received: %s', message)
                    var received = rsa.privateDecrypt(String(message, 'utf8'), process.env.RSA_PRIVATE_KEY)
                    client.send(received);
                    var sent = rsa.privateEncrypt(received, process.env.RSA_PRIVATE_KEY)
                    client.send(sent);
                    console.log('sent: %s', sent);
                    break;
            }
        });

        client.on('close', (code, reason) => {
            delete ws.clients[client.id];
        });
    });

    return ws;
};
</code>```

Server code - rsa.js

const crypto = require('crypto');

exports.privateEncrypt = (data, key) => {
    const buffer = Buffer.from(data);
    const encrypted = crypto.privateEncrypt(key, buffer);
    return encrypted.toString("base64");
}

exports.privateDecrypt = (data, key) => {
    const buffer = Buffer.from(data, "base64");
    const decrypted = crypto.privateDecrypt(key, buffer);
    return decrypted.toString("utf8");
}

exports.publicEncrypt = (data, key) => {
    const buffer = Buffer.from(data);
    const encrypted = crypto.publicEncrypt(key, buffer);
    return encrypted.toString("base64");
}

exports.publicDecrypt = (data, key) => {
    const buffer = Buffer.from(data, "base64");
    const decrypted = crypto.publicDecrypt(key, buffer);
    return decrypted.toString("utf8");
}
```

there was no problem with the value encrypted by the server
then I found a post on stackoverflow with the same problem, and there it was said that UTF-8 encoding may not always return the same result so I tried using other encodings instead of UTF-8, but I cant solve this problem in my head

Body:
I have created a C# Client and NodeJS Server that communicate with WebsocketsAnd I encrypted the message passing through the socket with RSAThe data encrypted by the client using the public key could be decrypted by the server, but the data encrypted by the server by the private key could not be decrypted by the client. and then an error occurred 'System.Security.Cryptography.CryptographicException: 'Error occurred while decoding OAEP padding.'

Client code - Form1.cs

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using System;
using System.IO;
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Something Namespace
{
    public partial class Form1: Form
    {
        private ClientWebSocket ws = new ClientWebSocket();
        public Login(string[] args)
        {
            InitializeComponent();
        }

        private async void Login_Load(object sender, EventArgs e)
        {
            RSACryptoServiceProvider RSA = ImportPublicKey("Something Public Key");
            string MessageEncrypted = Convert.ToBase64String(RSA.Encrypt(Encoding.UTF8.GetBytes("Hi I am Client"), true));
            MessageBox.Show(MessageEncrypted);
            Uri serverUri = new Uri("ws://localhost:3000/");
            await ws.ConnectAsync(serverUri, CancellationToken.None);
            ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(MessageEncrypted));
            await ws.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
            while (ws.State == WebSocketState.Open)
            {
                ArraySegment<byte> bytesReceived = new ArraySegment<byte>(new byte[2048]);
                WebSocketReceiveResult result = await ws.ReceiveAsync(bytesReceived, CancellationToken.None);
                string response = Encoding.UTF8.GetString(bytesReceived.Array, 0, result.Count);

                MessageBox.Show(response);
                if (response != "Hi I am Client")
                {
                    RSA.Decrypt(Convert.FromBase64String(response), true);
                }
            }
        }

        public static RSACryptoServiceProvider ImportPublicKey(string pem)
        {
            PemReader pr = new PemReader(new StringReader(pem));
            AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter)pr.ReadObject();
            RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaKeyParameters)publicKey);

            RSACryptoServiceProvider csp = new RSACryptoServiceProvider();;
            csp.ImportParameters(rsaParams);
            return csp;
        }
    }
}

Server code - index.js

require('dotenv').config();
const express = require('express');

const app = express();

async function initialize() {
    // app.use(express.static(__dirname + '/public'));
    var server = await require('./server')(app);
    var ws = await require('./socket')(server);

    // bot
}

initialize();

Server code - server.js

module.exports = async (app) => {
    ...

    await loadMiddlewares();
    await loadRoutes();
    await checkDatabase();
    return await app.listen(app.get('port'), () => {
        logger.info(`${process.env.SERVER_NAME} server started on port ${app.get('port')}`);
    });
};

Server code - socket.js

const webSocket = require('ws');
const rsa = require('./modules/rsa')

module.exports = (server) => {
    const ws = new webSocket.Server({ server });

    ws.on('connection', (client, req) => {
        client.id = req.headers['sec-websocket-key'];
        ws.clients[client.id] = client;

        client.on('message', (message) => {
            switch (req.url) {
                default:
                    console.log('received: %s', message)
                    var received = rsa.privateDecrypt(String(message, 'utf8'), process.env.RSA_PRIVATE_KEY)
                    client.send(received);
                    var sent = rsa.privateEncrypt(received, process.env.RSA_PRIVATE_KEY)
                    client.send(sent);
                    console.log('sent: %s', sent);
                    break;
            }
        });

        client.on('close', (code, reason) => {
            delete ws.clients[client.id];
        });
    });

    return ws;
};

Server code - rsa.js

const crypto = require('crypto');

exports.privateEncrypt = (data, key) => {
    const buffer = Buffer.from(data);
    const encrypted = crypto.privateEncrypt(key, buffer);
    return encrypted.toString("base64");
}

exports.privateDecrypt = (data, key) => {
    const buffer = Buffer.from(data, "base64");
    const decrypted = crypto.privateDecrypt(key, buffer);
    return decrypted.toString("utf8");
}

exports.publicEncrypt = (data, key) => {
    const buffer = Buffer.from(data);
    const encrypted = crypto.publicEncrypt(key, buffer);
    return encrypted.toString("base64");
}

exports.publicDecrypt = (data, key) => {
    const buffer = Buffer.from(data, "base64");
    const decrypted = crypto.publicDecrypt(key, buffer);
    return decrypted.toString("utf8");
}

there was no problem with the value encrypted by the server
then I found a post on stackoverflow with the same problem, and there it was said that UTF-8 encoding may not always return the same result so I tried using other encodings instead of UTF-8, but I cant solve this problem in my head


问:
Convert Bearer token to JWT token using .NET 6
I have been asked to connect to different applications via API, one application is a third-party app, (vendors) and the other one are. NET.
the only way to authenticate available is via a token. the vendor app allegedly said that I will get a JWT token that we don't see. YES. when we tried to decode it is just a bearer token. I don't understand why.
I need to find the token payload that this vendor app is sending. I need a header payload and signature.
what I get :
I get a bearer token but I need the JWT Token(header payload and signature).
the vendor keeps claiming that they are sending a JWT token, but I am getting a bearer token.
-I tried -

https://jwt.io -(NOT AN OPTION )because again what I get is a bearer token.

string url = "https://...some URL HERE....";

```<code>    HttpRequestMessage httpRequest = new HttpRequestMessage();
    httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var credentials = Encoding.ASCII.GetBytes(url);                                                                                var auth = httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer",Convert.ToBase64String(credentials));
    string authFinal = auth.ToString().Replace("Bearer ", "");
</code>```

Now, my only option is what?
Im using .NET 6

Body:
I have been asked to connect to different applications via API, one application is a third-party app, (vendors) and the other one are. NET.
the only way to authenticate available is via a token. the vendor app allegedly said that I will get a JWT token that we don't see. YES. when we tried to decode it is just a bearer token. I don't understand why.
I need to find the token payload that this vendor app is sending. I need a header payload and signature.
what I get :
I get a bearer token but I need the JWT Token(header payload and signature).
the vendor keeps claiming that they are sending a JWT token, but I am getting a bearer token.
-I tried -

https://jwt.io -(NOT AN OPTION )because again what I get is a bearer token.

string url = "https://...some URL HERE....";

    HttpRequestMessage httpRequest = new HttpRequestMessage();
    httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var credentials = Encoding.ASCII.GetBytes(url);                                                                                var auth = httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer",Convert.ToBase64String(credentials));
    string authFinal = auth.ToString().Replace("Bearer ", "");

Now, my only option is what?
Im using .NET 6


问:
Java GRPC annotation based role authorization
I am building a grpc based server client system with multiple different clients (iOS, Android, Web).
My backend will have a role system for allowing access to certain methods. For this I've implemented my own java annotation with values like, which should be added before every grpc method. Only users with at least one of the roles should be allowed to execute the method.

@ProjectSecure({"Role1", "Role2})

using GRPC's ServerInterceptor I have access to the token of the user containing all the roles (JWT).

```<code>@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata,
ServerCallHandler<ReqT, RespT> serverCallHandler) {
     String fullMethodName = serverCall.getMethodDescriptor().getFullMethodName();
}
</code>```

In my case the call above returns
de.example.project.api.user.LdapUserInterface/save but the value I need is different because in the given class is not loadable by reflection, because it is not part of my project instead it is a dependecy. The real implementation with the annotation is in the following class: de.example.project.backend.api.impl.server.LdapUserInterfaceImplGrpc/save

It there any easy and cheap way to get the real class called? Because I want to check annotation and its values.

The annotation is implemented as following

```<code>@Retention(RUNTIME)
@Target(METHOD)
public @interface EfbSecured {

      String[] permissionRights() default { };
}

</code>```

I cannot provide more code, because in reality it is more a company secret, but I will try to answer questions as good as possible.

Edit:
Due to our infrastructure and architecture, we are not able to use SpringSecurity.

Body:
I am building a grpc based server client system with multiple different clients (iOS, Android, Web).
My backend will have a role system for allowing access to certain methods. For this I've implemented my own java annotation with values like, which should be added before every grpc method. Only users with at least one of the roles should be allowed to execute the method.

@ProjectSecure({"Role1", "Role2})

using GRPC's ServerInterceptor I have access to the token of the user containing all the roles (JWT).

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata,
ServerCallHandler<ReqT, RespT> serverCallHandler) {
     String fullMethodName = serverCall.getMethodDescriptor().getFullMethodName();
}

In my case the call above returns
de.example.project.api.user.LdapUserInterface/save but the value I need is different because in the given class is not loadable by reflection, because it is not part of my project instead it is a dependecy. The real implementation with the annotation is in the following class: de.example.project.backend.api.impl.server.LdapUserInterfaceImplGrpc/save

It there any easy and cheap way to get the real class called? Because I want to check annotation and its values.

The annotation is implemented as following

@Retention(RUNTIME)
@Target(METHOD)
public @interface EfbSecured {

      String[] permissionRights() default { };
}

I cannot provide more code, because in reality it is more a company secret, but I will try to answer questions as good as possible.

Edit:
Due to our infrastructure and architecture, we are not able to use SpringSecurity.