问:
Is this a memory issue with DNN_BACKEND_CUDA and DNN_FRONTEND_CUDA?
I have the following code:

```<code>#include <iostream>
#include <opencv2/dnn_superres.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <filesystem>
#include <thread>
#include <future>
#include <opencv2/dnn/dnn.hpp>
#include <opencv2/core/cuda.hpp>
#include <iostream>

using namespace std;
using namespace cv;
using namespace cuda;
using namespace dnn;
using namespace dnn_superres;

int upsample_and_save(DnnSuperResImpl sr,
                      std::filesystem::path file_path,
                      std::filesystem::path save_dir) {
    std::cout<<"We are inside of upsample_and_save!" ;
    Mat img = cv::imread(file_path.string()); //Read image
    std::cout<<"We are inside of upsample_and_save and read the image" ;
    Mat img_new ; //Container to store upsampled image
    std::cout<<"We are inside of upsample_and_save and created img_new" ;
    sr.upsample(img, img_new); //Upsample
    std::cout<<"We upsampled" ;

    cv::imwrite((save_dir / file_path.filename()).string(), img_new); //Save upscaled image
    std::cout<<"We wrote the image!" ;
    std::cout<< (save_dir / file_path.filename()).string();
    return 0;
}

int main() {
    // Parameters
    string original_path = "C:/Users/Administrator/Desktop/Upscale/original"; //Path to folder containing original files
    std::filesystem::path upscaled_path = "C:/Users/Administrator/Desktop/Upscale/upscaled"; //Folder to save upscaled images

    std::vector<std::string> models {"lapsrn", "fsrcnn"};
    std::vector<std::string> model_weights {"LapSRN_x8.pb", "FSRCNN_x2.pb"};
    std::vector<int> scale_factors {8,2};

    string model_dir = "C:/Users/Administrator/Desktop/Upscale/models/";
    int model_choice = 1; //CHOOSE MODEL HERE (index in vector starting from 0)
    std::vector<std::string> allowed {".jpg",".png"}; //Allowed image types

    string model = models[model_choice]; //Model for dnn_superres
    int scale_factor = scale_factors[model_choice]; //Scale factor
    string model_path = model_dir + model_weights[model_choice]; //Model weights

    DnnSuperResImpl sr; //Module instance
    sr.readModel(model_path); //Read model weights
    sr.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
    sr.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
    sr.setModel(model, scale_factor); //Set model and scale
    std::cout<<"We set up OK!";

    for (const auto &file : std::filesystem::directory_iterator(original_path)) {
        std::cout<<"We are inside of the for loop!";

        if (std::count(allowed.begin(), allowed.end(), file.path().extension())) {
            upsample_and_save(sr, file.path(), upscaled_path);
            std::cout<< "We hit upsample in the for loop!";
        } else {
        std::cout<<"The if statement has failed!";
        }

std::cout<< "out of the loop";
return 0;
}
}

</code>```

The issue I am having:

If I set the model to FSRCNN_x2.pb by adjusting model_choice to 1, the code works great! This model upscales an image by 2x. However, if I select LapSRN_x8.pb, the code will produce the following output:

```<code>PS C:\Users\Administrator\Desktop\Upscale\build\Release> ."C:/Users/Administrator/Desktop/Upscale/build/Release/upscale.exe"
We set up OK! We are inside of the for loop! We hit upsample in the for loop! We are inside of upsample_and_save! We are inside of upsample_and_save and read the image! We are inside of upsample_and_save and created img_new
PS C:\Users\Administrator\Desktop\Upscale\build\Release>
</code>```

The code seems to hit the sr.upsample(img,img_new) and then completely crash!

I have attempted to fix this by commenting out

```<code>    sr.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
    sr.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
</code>```

And after doing so, it appears that the code works fine. Does anyone know why this is happening?

Body:
I have the following code:

#include <iostream>
#include <opencv2/dnn_superres.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <filesystem>
#include <thread>
#include <future>
#include <opencv2/dnn/dnn.hpp>
#include <opencv2/core/cuda.hpp>
#include <iostream>

using namespace std;
using namespace cv;
using namespace cuda;
using namespace dnn;
using namespace dnn_superres;

int upsample_and_save(DnnSuperResImpl sr,
                      std::filesystem::path file_path,
                      std::filesystem::path save_dir) {
    std::cout<<"We are inside of upsample_and_save!" ;
    Mat img = cv::imread(file_path.string()); //Read image
    std::cout<<"We are inside of upsample_and_save and read the image" ;
    Mat img_new ; //Container to store upsampled image
    std::cout<<"We are inside of upsample_and_save and created img_new" ;
    sr.upsample(img, img_new); //Upsample
    std::cout<<"We upsampled" ;

    cv::imwrite((save_dir / file_path.filename()).string(), img_new); //Save upscaled image
    std::cout<<"We wrote the image!" ;
    std::cout<< (save_dir / file_path.filename()).string();
    return 0;
}

int main() {
    // Parameters
    string original_path = "C:/Users/Administrator/Desktop/Upscale/original"; //Path to folder containing original files
    std::filesystem::path upscaled_path = "C:/Users/Administrator/Desktop/Upscale/upscaled"; //Folder to save upscaled images

    std::vector<std::string> models {"lapsrn", "fsrcnn"};
    std::vector<std::string> model_weights {"LapSRN_x8.pb", "FSRCNN_x2.pb"};
    std::vector<int> scale_factors {8,2};

    string model_dir = "C:/Users/Administrator/Desktop/Upscale/models/";
    int model_choice = 1; //CHOOSE MODEL HERE (index in vector starting from 0)
    std::vector<std::string> allowed {".jpg",".png"}; //Allowed image types

    string model = models[model_choice]; //Model for dnn_superres
    int scale_factor = scale_factors[model_choice]; //Scale factor
    string model_path = model_dir + model_weights[model_choice]; //Model weights

    DnnSuperResImpl sr; //Module instance
    sr.readModel(model_path); //Read model weights
    sr.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
    sr.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
    sr.setModel(model, scale_factor); //Set model and scale
    std::cout<<"We set up OK!";

    for (const auto &file : std::filesystem::directory_iterator(original_path)) {
        std::cout<<"We are inside of the for loop!";

        if (std::count(allowed.begin(), allowed.end(), file.path().extension())) {
            upsample_and_save(sr, file.path(), upscaled_path);
            std::cout<< "We hit upsample in the for loop!";
        } else {
        std::cout<<"The if statement has failed!";
        }

std::cout<< "out of the loop";
return 0;
}
}

The issue I am having:

If I set the model to FSRCNN_x2.pb by adjusting model_choice to 1, the code works great! This model upscales an image by 2x. However, if I select LapSRN_x8.pb, the code will produce the following output:

PS C:\Users\Administrator\Desktop\Upscale\build\Release> ."C:/Users/Administrator/Desktop/Upscale/build/Release/upscale.exe"
We set up OK! We are inside of the for loop! We hit upsample in the for loop! We are inside of upsample_and_save! We are inside of upsample_and_save and read the image! We are inside of upsample_and_save and created img_new
PS C:\Users\Administrator\Desktop\Upscale\build\Release>

The code seems to hit the sr.upsample(img,img_new) and then completely crash!

I have attempted to fix this by commenting out

    sr.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
    sr.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);

And after doing so, it appears that the code works fine. Does anyone know why this is happening?


来源: stackexchange

问:
In manifest v3 is conditional redirecting possible?
We have a Chrome extension that we use that allows our developers to quickly setup redirects for certain URLs, for easier debugging across different clients' sites. It currently uses manifest v2 manifest with webRequestBlocking.

In brief, it behaves something like this:

Search for a URL pattern like: https://www.example.com/c1234/path/to/javascript.js

Use the c1234 part of the matched URL in an HTTP call to a web service that to look-up the value of a variable, which we'll call shortName here.

Redirect the URL in #1 to a new URL that follows a pattern something like this: https://localhost/imp-{shortName}/javascript.js.

With the declarativeNetRequest in manifest v3, I'm able to set rules that redirect using regular expressions, but I don't see any way to use a part of the matched URL to look-up a variable from an outside source (step #2) above.

Is this not possible with manfiest v3 at all? I'm using the updateSessionRules API as follows:

```<code>chrome.declarativeNetRequest.updateSessionRules({
  addRules: [
  {
    id: 1,
    action: {
      type: 'redirect',
      redirect: {
        regexSubstitution: '\1://localhost/{shortName}/javascript.js'
      }
    },
    condition: {
      regexFilter: '^(https?):.+(example.com).+(c[0-9]+).+javascript.+$'
    }
  }
];
  rules,
  removeRuleIds: [1]
});
</code>```

In manifest v2, I used chrome.webRequest.onBeforeRequest to intercept before the request was made:

```<code>chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    return redirectOnMatch(details);
  },
  {
    urls : ["<all_urls>"]
  },
  ["blocking"]
);
</code>```

The redirectOnMatch function would first check to see if the URL matched a pattern, and if it did, extract the c1234 value and use it in an HTTP call.

Is there any way to have code run and set the redirect rules before the request is made in manifest v3?

ContentLicense: CC BY-SA 4.0

Body:
We have a Chrome extension that we use that allows our developers to quickly setup redirects for certain URLs, for easier debugging across different clients' sites. It currently uses manifest v2 manifest with webRequestBlocking.

In brief, it behaves something like this:

Search for a URL pattern like: https://www.example.com/c1234/path/to/javascript.js

Use the c1234 part of the matched URL in an HTTP call to a web service that to look-up the value of a variable, which we'll call shortName here.

Redirect the URL in #1 to a new URL that follows a pattern something like this: https://localhost/imp-{shortName}/javascript.js.

With the declarativeNetRequest in manifest v3, I'm able to set rules that redirect using regular expressions, but I don't see any way to use a part of the matched URL to look-up a variable from an outside source (step #2) above.

Is this not possible with manfiest v3 at all? I'm using the updateSessionRules API as follows:

chrome.declarativeNetRequest.updateSessionRules({
  addRules: [
  {
    id: 1,
    action: {
      type: 'redirect',
      redirect: {
        regexSubstitution: '\1://localhost/{shortName}/javascript.js'
      }
    },
    condition: {
      regexFilter: '^(https?):.+(example.com).+(c[0-9]+).+javascript.+$'
    }
  }
];
  rules,
  removeRuleIds: [1]
});

In manifest v2, I used chrome.webRequest.onBeforeRequest to intercept before the request was made:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    return redirectOnMatch(details);
  },
  {
    urls : ["<all_urls>"]
  },
  ["blocking"]
);

The redirectOnMatch function would first check to see if the URL matched a pattern, and if it did, extract the c1234 value and use it in an HTTP call.

Is there any way to have code run and set the redirect rules before the request is made in manifest v3?


问:
Unable to backup or restore openstack and juju
I am in need of assistance, as the title says, I am unable to back my data up in any way. Once a node is corrupted and everything deletes I lost everything and unable to backup or restore I'm using MAAS 3.0 and Openstack wallaby.

The way I use MAAS is I PXE my nodes and it gets them, so IF I do clone my MAAS server, the data on the old nodes would be gone... and cloning ALL four nodes would be difficult due to limited resources.

I tried the juju backup command, however the juju restore command is not working.
I tried copying the instances, snapshots, volumes from the juju charm it self, however they were too big it crashed.

I was not able to find any solution anywhere. please help :(


问:
Adding an unmute button to Squarespace Vimeo video header
I'm trying to add an unmute button to our Squarespace video header (Vimeo). I have found various methods but nothing seems to be working.

view site here

Here is the code Squarespace creates in the header...

```<code><div class="sqs-video-background content-fill" data-config-url="https://vimeo.com/779083883" data-config-playback-speed="1" data-config-filter="1" data-config-filter-strength="89">

<div id="player" style="position: absolute; top: 0; bottom: 0; left: 0; right: 0;">

<iframe id="vimeoplayer" src="//player.vimeo.com/video/779083883?api=1&background=1" class="background-video ready" style="width: 1123.56px; height: 632px; left: -159.278px; top: 0px;">
</iframe>

</div>

  </div>
</code>```

I tried following the instructions outlined here, using the iframe id in place of "video"

https://discourse.webflow.com/t/custom-button-to-unmute-vimeo-embed/181629
Video Mute and unmute button

Body:
I'm trying to add an unmute button to our Squarespace video header (Vimeo). I have found various methods but nothing seems to be working.

view site here

Here is the code Squarespace creates in the header...

I tried following the instructions outlined here, using the iframe id in place of "video"

https://discourse.webflow.com/t/custom-button-to-unmute-vimeo-embed/181629
Video Mute and unmute button


问:
Encoding a JMESPath in a query URL
I am calling an API to evaluate a JMESPath expression passed as a query parameter. All goes well until I try to use logical AND.  How do I encode the ampersand in the URL?

Using logical OR the URL looks like:

```<code>http://localhost:5000/query?query=members[?userSessions>=`0` ||  userSessions>=`0`].componentInfo[].code
</code>```

The following query using logical AND does not work:

```<code>http://localhost:5000/query?query=members[?userSessions>=`0` &&  userSessions>=`0`].componentInfo[].code
</code>```

The query is ok - I tested it at http://play.jmespath.org/

Title: Encoding a JMESPath in a query URL

Body:
I am calling an API to evaluate a JMESPath expression passed as a query parameter. All goes well until I try to use logical AND.  How do I encode the ampersand in the URL?

Using logical OR the URL looks like:

http://localhost:5000/query?query=members[?userSessions>=`0` ||  userSessions>=`0`].componentInfo[].code

The following query using logical AND does not work:

http://localhost:5000/query?query=members[?userSessions>=`0` &&  userSessions>=`0`].componentInfo[].code

The query is ok - I tested it at http://play.jmespath.org/


问:
Does msvcrt not work with python GUI libraries like tkinter? Or is is the IDLE? New to python GUI
I am using the latest version of PyCharm and Python. I'm trying to get my program to wait for specific keypresses like the arrow keys. I've been messing with the mscvrt (not worried about only windows) and using the getch() but it freezes my program everytime. I was able to get it to work printing to the console by using "emulate terminal in output console". But once I tried implementing it to a GUI with my code in tkinter it still freezes. Was wondering if it just doesn't work in GUI's and that's the issue (saw this mentioned on the internet) and if anyone had suggestions for what I could do.

For example:

This runs in the console and works. The arrow keys print as (b'\xe0' b'K') (left) and (b'\xe0' b'M') (right)

```<code>while True:
    if msvcrt.kbhit():
        key = str(msvcrt.getch())
        if key == "b'w'":
            print(key)
        elif key == 'w':
            print("suck it")
</code>```

This freezes my program before I get the chance to press any keys. It seems to be only when I introduce GUI into the program. I also tried binding this as a function to space and it will freeze the GUI when I press space and crash after a bit. I also tried not using a while function and also without the kbhit part as well.

```<code>while True:
    if msvcrt.kbhit()
    user_input = str(msvcrt.getch())
    start = tk.Label(window, text=(user_input), font=("arial", '25'))
    start.place(relx=.5, rely=.7, anchor="center")
</code>```

Appreciate any help/advice. I'm somewhat new to python and coding so not sure what the issue could be.

Body:
I am using the latest version of PyCharm and Python. I'm trying to get my program to wait for specific keypresses like the arrow keys. I've been messing with the mscvrt (not worried about only windows) and using the getch() but it freezes my program everytime. I was able to get it to work printing to the console by using "emulate terminal in output console". But once I tried implementing it to a GUI with my code in tkinter it still freezes. Was wondering if it just doesn't work in GUI's and that's the issue (saw this mentioned on the internet) and if anyone had suggestions for what I could do.

For example:

This runs in the console and works. The arrow keys print as (b'\xe0' b'K') (left) and (b'\xe0' b'M') (right)

while True:
    if msvcrt.kbhit():
        key = str(msvcrt.getch())
        if key == "b'w'":
            print(key)
        elif key == 'w':
            print("suck it")

This freezes my program before I get the chance to press any keys. It seems to be only when I introduce GUI into the program. I also tried binding this as a function to space and it will freeze the GUI when I press space and crash after a bit. I also tried not using a while function and also without the kbhit part as well.

while True:
    if msvcrt.kbhit()
    user_input = str(msvcrt.getch())
    start = tk.Label(window, text=(user_input), font=("arial", '25'))
    start.place(relx=.5, rely=.7, anchor="center")

Appreciate any help/advice. I'm somewhat new to python and coding so not sure what the issue could be.


问:
SQL into ActiveRecord scope: Retrieve Records with given association, or whose nested objects have the given association
How do I translate this SQL into an ActiveRecord scope?

```<code>SELECT * FROM trxes
WHERE date="2022-05-01"
AND id IN (SELECT lines.trx_id FROM lines WHERE lines.category_id = 15)
OR id IN (SELECT id FROM trxes WHERE trxes.category_id = 15)
</code>```

The scope I'm using gets close but returns Trxes outside of May 2022.

```<code>scope :category_id, -> (cat_id) { where(lines: Line.where(category_id: cat_id)).or(Trx.where(category_id: cat_id)) }
</code>```

Trx.date("2022-May-01").category_id(15)

Trx Load (0.3ms) SELECT "trxes".* FROM "trxes" WHERE ("trxes"."date" = ? AND "trxes"."id" IN (SELECT "lines"."trx_id" FROM "lines" WHERE "lines"."category_id" = ?)                        OR "trxes"."category_id" = ?) [["date", "2022-05-01"], ["category_id", 15], ["category_id", 15]]

More information: A simple Trx has a category= Fuel, Groceries, Entertainment..., and 0 Line objects. A complex Trx has category=Split, and it has multiple Line objects which themselves have a category= Fuel, Groceries, Entertainment...

I want to query Trx model for category=Fuel, and retrieve all simple Trxes where category=Fuel, and complex Trxes containing a Line that has category=Fuel.

```<code>class Trx < ApplicationRecord
  belongs_to :category, optional: true
  has_many :lines, dependent: :destroy
...
class Line < ApplicationRecord
  belongs_to :trx
  belongs_to :category, optional: true
...
class Category < ApplicationRecord
  has_many :lines
  has_many :trxes
...
</code>```

Additional effort I would like to combine the results of the following two ActiveRecord queries

```<code>Trx.where(date:"2022-May-01").where(category_id: 15)
Trx.where(date:"2022-May-01").where(lines: Line.where(category_id: 15))
</code>```

Body:
How do I translate this SQL into an ActiveRecord scope?

SELECT * FROM trxes
WHERE date="2022-05-01"
AND id IN (SELECT lines.trx_id FROM lines WHERE lines.category_id = 15)
OR id IN (SELECT id FROM trxes WHERE trxes.category_id = 15)

The scope I'm using gets close but returns Trxes outside of May 2022.

scope :category_id, -> (cat_id) { where(lines: Line.where(category_id: cat_id)).or(Trx.where(category_id: cat_id)) }

Trx.date("2022-May-01").category_id(15)

Trx Load (0.3ms) SELECT "trxes".* FROM "trxes" WHERE ("trxes"."date" = ? AND "trxes"."id" IN (SELECT "lines"."trx_id" FROM "lines" WHERE "lines"."category_id" = ?)                        OR "trxes"."category_id" = ?) [["date", "2022-05-01"], ["category_id", 15], ["category_id", 15]]

More information: A simple Trx has a category= Fuel, Groceries, Entertainment..., and 0 Line objects. A complex Trx has category=Split, and it has multiple Line objects which themselves have a category= Fuel, Groceries, Entertainment...

I want to query Trx model for category=Fuel, and retrieve all simple Trxes where category=Fuel, and complex Trxes containing a Line that has category=Fuel.

class Trx < ApplicationRecord
  belongs_to :category, optional: true
  has_many :lines, dependent: :destroy
...
class Line < ApplicationRecord
  belongs_to :trx
  belongs_to :category, optional: true
...
class Category < ApplicationRecord
  has_many :lines
  has_many :trxes
...

Additional effort I would like to combine the results of the following two ActiveRecord queries

Trx.where(date:"2022-May-01").where(category_id: 15)
Trx.where(date:"2022-May-01").where(lines: Line.where(category_id: 15))


问:
File uploading directly from client to backlaze bucket using Uppy Js
I tried three different methods to get checksum of a same file.

1- using crypto-js (with CryptoJS.SHA1(event.target.result))

2- using sha1.min.js (with sha1(event.target.result)

3- using crypto (with crypto.subtle.digest('SHA-1', fileUint8))

Each one produces different sha1 value for same file, I don't know why.
However, sha1(event.target.result) created same checksum as produced by online sha1 calculator. I tried all values one by one in uploading but request is failed with message 'Checksum did not match data received'
If i assume that one of sha1 value is correct, then it means there is something  wrong in Uppy Uploading and the file contents are not pushed properly to bucket so error message appears in response.

.....

Here is the code sample to get sha-1.

```<code>    function digestFile(file) {
       var reader = new FileReader();

       reader.onloadend = function (event) {
           if (event.target.readyState == FileReader.DONE) {
               var file_sha1 = CryptoJS.SHA1(event.target.result); // first method
               var file_sha2 = sha1(event.target.result); // second method
       };
       reader.readAsArrayBuffer(file.data);
   }
</code>```

third method is here

```<code>   async function digestMessage1(file) {
       const fileUint8 = new TextEncoder().encode(file);
       const hashBuffer = await crypto.subtle.digest('SHA-1', fileUint8);
       const hashArray = Array.from(new Uint8Array(hashBuffer));
       const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
       return hashHex;
   }

   function digestFile(file) {
       var reader = new FileReader();

       reader.onloadend = function (event) {
           if (event.target.readyState == FileReader.DONE) {
               digestMessage1(event.target.result)
                   .then((digestHex) => console.log(digestHex));
       };
       reader.readAsArrayBuffer(file.data);
   }
</code>```

..

Here is the Uppy JS code.

```<code>   let data = this.el.dataset;

   var uppy = new UppyLib({
    autoProceed: true,
    allowMultipleUploadBatches: true,
    restrictions: { allowedFileTypes: ['image/*', '.jpg', '.jpeg', '.png', '.gif'] }
    })

    uppy.use(Uppy.Dashboard, { target: '#drag-drop-area', inline: true, width: 750, height: 550})

    uppy.use(AwsS3, {
        getUploadParameters(file) {
            return fetch('/assets/new', {
                method: 'GET',
                headers: { accept: 'application/json', 'content-type': 'application/json' }
            }).then((response) => {

                return response.json()
            }).then((data) => {
                 return {
                    method: 'POST',
                    url: `${data.url}`,
                    fields: [],
                    headers: {
                        "Content-Type": "b2/x-auto",
                        "Authorization": `${data.token}`,
                        "X-Bz-File-Name": `assets/${Date.now()}-${encodeURI(file.name)}`,
                        "X-Bz-Content-Sha1": "94d2ff39a524e0cf20f3bd6cf909c426"
                    },
                }
            })
        }
    })}
</code>```

Body:
I tried three different methods to get checksum of a same file.

1- using crypto-js (with CryptoJS.SHA1(event.target.result))

2- using sha1.min.js (with sha1(event.target.result)

3- using crypto (with crypto.subtle.digest('SHA-1', fileUint8))

Each one produces different sha1 value for same file, I don't know why.
However, sha1(event.target.result) created same checksum as produced by online sha1 calculator. I tried all values one by one in uploading but request is failed with message 'Checksum did not match data received'
If i assume that one of sha1 value is correct, then it means there is something  wrong in Uppy Uploading and the file contents are not pushed properly to bucket so error message appears in response.

.....

Here is the code sample to get sha-1.

    function digestFile(file) {
       var reader = new FileReader();

       reader.onloadend = function (event) {
           if (event.target.readyState == FileReader.DONE) {
               var file_sha1 = CryptoJS.SHA1(event.target.result); // first method
               var file_sha2 = sha1(event.target.result); // second method
       };
       reader.readAsArrayBuffer(file.data);
   }

third method is here

   async function digestMessage1(file) {
       const fileUint8 = new TextEncoder().encode(file);
       const hashBuffer = await crypto.subtle.digest('SHA-1', fileUint8);
       const hashArray = Array.from(new Uint8Array(hashBuffer));
       const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
       return hashHex;
   }

   function digestFile(file) {
       var reader = new FileReader();

       reader.onloadend = function (event) {
           if (event.target.readyState == FileReader.DONE) {
               digestMessage1(event.target.result)
                   .then((digestHex) => console.log(digestHex));
       };
       reader.readAsArrayBuffer(file.data);
   }

..

Here is the Uppy JS code.

   let data = this.el.dataset;

   var uppy = new UppyLib({
    autoProceed: true,
    allowMultipleUploadBatches: true,
    restrictions: { allowedFileTypes: ['image/*', '.jpg', '.jpeg', '.png', '.gif'] }
    })

    uppy.use(Uppy.Dashboard, { target: '#drag-drop-area', inline: true, width: 750, height: 550})

    uppy.use(AwsS3, {
        getUploadParameters(file) {
            return fetch('/assets/new', {
                method: 'GET',
                headers: { accept: 'application/json', 'content-type': 'application/json' }
            }).then((response) => {

                return response.json()
            }).then((data) => {
                 return {
                    method: 'POST',
                    url: `${data.url}`,
                    fields: [],
                    headers: {
                        "Content-Type": "b2/x-auto",
                        "Authorization": `${data.token}`,
                        "X-Bz-File-Name": `assets/${Date.now()}-${encodeURI(file.name)}`,
                        "X-Bz-Content-Sha1": "94d2ff39a524e0cf20f3bd6cf909c426"
                    },
                }
            })
        }
    })}


问:
How to animate a number ticking up in HTML
I'm trying to have a number "tick up" when it changes, in a similar fashion to Twitter's like/retweet/comment counters and Discord's reaction counter. I haven't found any information about this on the web (mainly because I don't know what it's formally called).

Here is my code:

The counter element itself:

0
```
<p>The CSS for the element:</p>
<pre class="lang-css prettyprint-override"><code>.counter {
    display: inline-block;
    height: 15px;
    font-size: 15px;
    overflow-y: hidden;
}
</code>```

The JavaScript for changing the counter:

function changeCounter(id, num) {
    var _x = document.getElementById(id);
    _x.innerHTML += _x.innerHTML + "
" + num;
    _x.style.transition = "0.2s";
    setTimeout(function () {
        _x.style.marginTop = "-15px";
        setTimeout(function () {
            _x.innerHTML = num;
            _x.style.transition = "0";
            _x.style.marginTop = "0";
        }, 200);
    }, 16);
}
```
<p>What happens is that it puts the new number next to the original number, goes up, and goes down with just the new number. I want it to have the new number under the old one and just snap to its original position after it stops animating.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function changeCounter(id, num) {
    var _x = document.getElementById(id);
    _x.innerHTML += _x.innerHTML + "<br>" + num;
    _x.style.transition = "0.2s";
    setTimeout(function () {
        _x.style.marginTop = "-15px";
        setTimeout(function () {
            _x.innerHTML = num;
            _x.style.transition = "0";
            _x.style.marginTop = "0";
        }, 200);
    }, 16);
}</code>```

.counter {
    display: inline-block;
    height: 15px;
    font-size: 15px;
    overflow-y: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="counter" class="counter">0</span>

<button onclick="changeCounter('counter', Math.floor(Math.random()*100))">Change</button></code>```

Body:
I'm trying to have a number "tick up" when it changes, in a similar fashion to Twitter's like/retweet/comment counters and Discord's reaction counter. I haven't found any information about this on the web (mainly because I don't know what it's formally called).

Here is my code:

The counter element itself:

0

The CSS for the element:

.counter {
    display: inline-block;
    height: 15px;
    font-size: 15px;
    overflow-y: hidden;
}

The JavaScript for changing the counter:

function changeCounter(id, num) {
    var _x = document.getElementById(id);
    _x.innerHTML += _x.innerHTML + "
" + num;
    _x.style.transition = "0.2s";
    setTimeout(function () {
        _x.style.marginTop = "-15px";
        setTimeout(function () {
            _x.innerHTML = num;
            _x.style.transition = "0";
            _x.style.marginTop = "0";
        }, 200);
    }, 16);
}

What happens is that it puts the new number next to the original number, goes up, and goes down with just the new number. I want it to have the new number under the old one and just snap to its original position after it stops animating.

function changeCounter(id, num) {
    var _x = document.getElementById(id);
    _x.innerHTML += _x.innerHTML + "
" + num;
    _x.style.transition = "0.2s";
    setTimeout(function () {
        _x.style.marginTop = "-15px";
        setTimeout(function () {
            _x.innerHTML = num;
            _x.style.transition = "0";
            _x.style.marginTop = "0";
        }, 200);
    }, 16);
}

.counter {
    display: inline-block;
    height: 15px;
    font-size: 15px;
    overflow-y: hidden;
}

0

<button onclick="changeCounter('counter', Math.floor(Math.random()*100))">Change</button>


问:
Dynamic clustering for panel data
I have panel data consisting of time series for 120 months, 45 institutions and approximately 8 variables for each one. I want to do a cluster analysis in order to detect stressed institutions based on dynamic clustering analysis. For instance, check if a stressed institution does move from one cluster to another, or if its behavior changes so much that it is no longer part of its own cluster.

The idea would be to use the information up to time t to cluster the institutions and get the clusters for each institution so it can evolve with new information and use all the information available up to that point from all the banks, with time varying clusters.

My first idea was to use statistical control techniques and anomaly detection for time series such as the ones in the package anomaly, but this procedure does not use all the information from the other banks, just its own. It might be that the whole system is stressed, so detecting an anomaly in one bank might be because of the system and not because of the particular bank.

I also tried using clustering in each period through hierarchical clustering, and did a decent job on classifying the institutions based on my knowledge of them. However, this procedure only uses data at each point in time, not all the data available up to that point.

I had the idea of using clustering methods for panel data at each point in time, using the data up to that point, and cycling through each month to get dynamic clusters using the whole dataset. However, I don't know if this approach makes sense, or if there are better methods to do this kind of analysis.

Thank you very much!

Title: Dynamic clustering for panel data


问:
file not found when clicking a problem in vscode for an angular project
I started using Visual Studio code for my angular 15 project.

I have a problem that when the editor detects errors and i can see them on the Problems Tab:

and I double click on one of the problems to open the relevant file, it gives me the error The editor could not be opened because the file was not found

as you can see in the problem, the Error talks about src/app/yt-player/yt-player.component.ts

and the file does exists

I googled and it's related to something related to relative path maybe ?

.vscode directory is in the root of the project and the location relative to the root of the project is correct.

what am I missing ?

these are the list of my installed extensions:

```<code>Angular.ng-template
bmewburn.vscode-intelephense-client
cschlosser.doxdocgen
ecmel.vscode-html-css
EditorConfig.EditorConfig
eg2.vscode-npm-script
golang.go
jeff-hykin.better-cpp-syntax
johnpapa.Angular2
ms-azuretools.vscode-docker
ms-ossdata.vscode-postgresql
ms-python.isort
ms-python.python
ms-python.vscode-pylance
ms-toolsai.jupyter
ms-toolsai.jupyter-keymap
ms-toolsai.jupyter-renderers
ms-toolsai.vscode-jupyter-cell-tags
ms-toolsai.vscode-jupyter-slideshow
ms-vscode-remote.remote-containers
ms-vscode.cmake-tools
ms-vscode.cpptools
ms-vscode.cpptools-extension-pack
ms-vscode.cpptools-themes
mtxr.sqltools
nrwl.angular-console
PKief.material-icon-theme
twxs.cmake
zhuangtongfa.material-theme
</code>```

update - this is confusing

as you can see here i have 3 errors, the bottom one and the top one are on the same file, src/app/yt-player/yt-player.component.html with the same  error, the bottom error states from which component it's derived from, the top error doesn't.

when I click on the bottom error it jumps to the file properly, at the top error it gives me file not found.

Body:
I started using Visual Studio code for my angular 15 project.

I have a problem that when the editor detects errors and i can see them on the Problems Tab:

and I double click on one of the problems to open the relevant file, it gives me the error The editor could not be opened because the file was not found

as you can see in the problem, the Error talks about src/app/yt-player/yt-player.component.ts

and the file does exists

I googled and it's related to something related to relative path maybe ?

.vscode directory is in the root of the project and the location relative to the root of the project is correct.

what am I missing ?

these are the list of my installed extensions:

Angular.ng-template
bmewburn.vscode-intelephense-client
cschlosser.doxdocgen
ecmel.vscode-html-css
EditorConfig.EditorConfig
eg2.vscode-npm-script
golang.go
jeff-hykin.better-cpp-syntax
johnpapa.Angular2
ms-azuretools.vscode-docker
ms-ossdata.vscode-postgresql
ms-python.isort
ms-python.python
ms-python.vscode-pylance
ms-toolsai.jupyter
ms-toolsai.jupyter-keymap
ms-toolsai.jupyter-renderers
ms-toolsai.vscode-jupyter-cell-tags
ms-toolsai.vscode-jupyter-slideshow
ms-vscode-remote.remote-containers
ms-vscode.cmake-tools
ms-vscode.cpptools
ms-vscode.cpptools-extension-pack
ms-vscode.cpptools-themes
mtxr.sqltools
nrwl.angular-console
PKief.material-icon-theme
twxs.cmake
zhuangtongfa.material-theme

update - this is confusing

as you can see here i have 3 errors, the bottom one and the top one are on the same file, src/app/yt-player/yt-player.component.html with the same  error, the bottom error states from which component it's derived from, the top error doesn't.

when I click on the bottom error it jumps to the file properly, at the top error it gives me file not found.


问:
Where is the correct place to build the needed Window for app in Cocoa macOS
I am confused to find the concert way for building the needed Window for app, so one of source say that I have to use this down code:

```<code>    import Cocoa
import SwiftUI

class ViewController: NSViewController {

    override func viewWillAppear() {

        self.view = NSHostingView(rootView: ContentView())

        self.view.window?.makeKeyAndOrderFront(nil)
        self.view.window?.standardWindowButton(NSWindow.ButtonType.zoomButton)?.isHidden = true
        self.view.window?.standardWindowButton(NSWindow.ButtonType.miniaturizeButton)?.isHidden = true
        self.view.window?.standardWindowButton(NSWindow.ButtonType.closeButton)?.isHidden = true

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

}
</code>```

And some other source says I have use this code:

```<code>    @main
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        // Insert code here to initialize your application

        let window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 300, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)

        window.center()
        window.setFrameAutosaveName("Main Window")
        window.contentView = NSHostingView(rootView: ContentView())
        window.makeKeyAndOrderFront(nil)

        window.standardWindowButton(NSWindow.ButtonType.zoomButton)?.isHidden = true
        window.standardWindowButton(NSWindow.ButtonType.miniaturizeButton)?.isHidden = true
        window.standardWindowButton(NSWindow.ButtonType.closeButton)?.isHidden = true
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
        return true
    }

}
</code>```

Which I am really confused which one is needed and why? can some one explain it to me?

Body:
I am confused to find the concert way for building the needed Window for app, so one of source say that I have to use this down code:

    import Cocoa
import SwiftUI

class ViewController: NSViewController {

    override func viewWillAppear() {

        self.view = NSHostingView(rootView: ContentView())

        self.view.window?.makeKeyAndOrderFront(nil)
        self.view.window?.standardWindowButton(NSWindow.ButtonType.zoomButton)?.isHidden = true
        self.view.window?.standardWindowButton(NSWindow.ButtonType.miniaturizeButton)?.isHidden = true
        self.view.window?.standardWindowButton(NSWindow.ButtonType.closeButton)?.isHidden = true

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

}

And some other source says I have use this code:

    @main
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        // Insert code here to initialize your application

        let window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 300, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)

        window.center()
        window.setFrameAutosaveName("Main Window")
        window.contentView = NSHostingView(rootView: ContentView())
        window.makeKeyAndOrderFront(nil)

        window.standardWindowButton(NSWindow.ButtonType.zoomButton)?.isHidden = true
        window.standardWindowButton(NSWindow.ButtonType.miniaturizeButton)?.isHidden = true
        window.standardWindowButton(NSWindow.ButtonType.closeButton)?.isHidden = true
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
        return true
    }

}

Which I am really confused which one is needed and why? can some one explain it to me?


问:
Why is the result of my Firestore Query inconsistent?
When I query a firestore collection using "array-contains" once, it always is correct. Strangely, when I cause the function to be triggered more than once in a 20 second period, it starts returning empty results for the query that is still very much not empty. The function is triggered by a write to a completely different collection.

```<code>const eventDocs = await firestore()
    .collection("eventCollection")
    .where("guests", "array-contains", incorrect_uuid)
    .get()
    .catch((e) => functions.logger.info(e));
</code>```

Run Once (triggered by write to users collection):

Returns firestore.QuerySnapshot<firestore.DocumentData> of size 3

Run Twice (triggered by write to users collection, wait up to 15 seconds, write again):

Note that it is a different query (incorrect_uuid changes) but both should be non-empty

Returns firestore.QuerySnapshot<firestore.DocumentData> of size 3 for the first (correct)

Returns firestore.QuerySnapshot<firestore.DocumentData> of size 0 for the second (wrong)

Body:
When I query a firestore collection using "array-contains" once, it always is correct. Strangely, when I cause the function to be triggered more than once in a 20 second period, it starts returning empty results for the query that is still very much not empty. The function is triggered by a write to a completely different collection.

const eventDocs = await firestore()
    .collection("eventCollection")
    .where("guests", "array-contains", incorrect_uuid)
    .get()
    .catch((e) => functions.logger.info(e));

Run Once (triggered by write to users collection):

Returns firestore.QuerySnapshot<firestore.DocumentData> of size 3

Run Twice (triggered by write to users collection, wait up to 15 seconds, write again):

Note that it is a different query (incorrect_uuid changes) but both should be non-empty

Returns firestore.QuerySnapshot<firestore.DocumentData> of size 3 for the first (correct)

Returns firestore.QuerySnapshot<firestore.DocumentData> of size 0 for the second (wrong)


问:
VSCode-Docker Not Invoking "CMD"
TL;DR Image built by VSCode only executes the CMD command when I press the Run button in the Docker Desktop UI.

Hello Folks,

I'm playing around with a Drools image along with Docker Desktop and VSCode.

My devcontainer.json file looks like the following:

```<code>{
    "name": "Existing Dockerfile",
    "build": {
        // Sets the run context to one level up instead of the .devcontainer folder.
        "context": "..",
        // Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename.
        "dockerfile": "../Dockerfile"
    },

    // Use 'forwardPorts' to make a list of ports inside the container available locally.
    "forwardPorts": [8001,8080]
}
</code>```

My Dockerfile is minimalist and looks like the following:

```<code>FROM quay.io/kiegroup/business-central-workbench:latest
</code>```

And my compose.yaml file looks like so:

```<code>services:
  app:
    entrypoint:
    - sleep
    - infinity
    image: docker/dev-environments-default:stable-1
    init: true
    volumes:
    - type: bind
      source: /var/run/docker.sock
      target: /var/run/docker.sock
</code>```

The issue is that when VSCode sends the image to Docker Desktop, the
CMD ["./start_business-central-wb.sh"] found in the parent image does not seem to be getting set off as seen in the logs

However, when I click "Run" the command gets kicked off after spawning a new instance

What concept am I missing as to why the Docker image doesn't immediately begin running when VSCode sends it to Docker Desktop?  I'm super inexperienced with both techs.

Any help is greatly appreciated.

Title: VSCode-Docker Not Invoking "CMD"

Body:
TL;DR Image built by VSCode only executes the CMD command when I press the Run button in the Docker Desktop UI.

Hello Folks,

I'm playing around with a Drools image along with Docker Desktop and VSCode.

My devcontainer.json file looks like the following:

{
    "name": "Existing Dockerfile",
    "build": {
        // Sets the run context to one level up instead of the .devcontainer folder.
        "context": "..",
        // Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename.
        "dockerfile": "../Dockerfile"
    },

    // Use 'forwardPorts' to make a list of ports inside the container available locally.
    "forwardPorts": [8001,8080]
}

My Dockerfile is minimalist and looks like the following:

FROM quay.io/kiegroup/business-central-workbench:latest

And my compose.yaml file looks like so:

services:
  app:
    entrypoint:
    - sleep
    - infinity
    image: docker/dev-environments-default:stable-1
    init: true
    volumes:
    - type: bind
      source: /var/run/docker.sock
      target: /var/run/docker.sock

The issue is that when VSCode sends the image to Docker Desktop, the
CMD ["./start_business-central-wb.sh"] found in the parent image does not seem to be getting set off as seen in the logs

However, when I click "Run" the command gets kicked off after spawning a new instance

What concept am I missing as to why the Docker image doesn't immediately begin running when VSCode sends it to Docker Desktop?  I'm super inexperienced with both techs.

Any help is greatly appreciated.


问:
Maya FBXImport replace certain string when importing FBX
I'm trying to import FBX to apply its animations onto the rig already in the scene.

```<code>        options = "targetTime=3;option=insert;match=string;selected=childrenToo;search=XXX;replace={};".format(prefix)
        pm.mel.FBXImport(f=file_path,t=1,options=options)
</code>```

File() works fine with this option. How can use this option with FBXImport?
Thank you in advance.

Importing atom:

```<code>        options = "targetTime=3;option=insert;match=string;selected=childrenToo;search=XXX;replace={};".format(prefix)

        cmds.file(file_path, i=True, type="atomImport", options=options)
</code>```

works fine.

Importing FBX:

```<code>        options = "targetTime=3;option=insert;match=string;selected=childrenToo;search=XXX;replace={};".format(prefix)
        pm.mel.FBXImport(f=file_path,t=1,options=options)
</code>```

This doesn't.I'm trying to rename certain string when importing FBX.

Body:
I'm trying to import FBX to apply its animations onto the rig already in the scene.

        options = "targetTime=3;option=insert;match=string;selected=childrenToo;search=XXX;replace={};".format(prefix)
        pm.mel.FBXImport(f=file_path,t=1,options=options)

File() works fine with this option. How can use this option with FBXImport?
Thank you in advance.

Importing atom:

        options = "targetTime=3;option=insert;match=string;selected=childrenToo;search=XXX;replace={};".format(prefix)

        cmds.file(file_path, i=True, type="atomImport", options=options)

works fine.

Importing FBX:

        options = "targetTime=3;option=insert;match=string;selected=childrenToo;search=XXX;replace={};".format(prefix)
        pm.mel.FBXImport(f=file_path,t=1,options=options)

This doesn't.I'm trying to rename certain string when importing FBX.


问:
ggplot2: grouping legend items by a variable for combined geom_path and geom_point
I have a connected scatterplot using geom_path and geom_point. I currently have the lines connecting the points by a grouping variable (Species_ordered) and each level of that variable symbolized by a different shape. I have another grouping variable (Type) which has two levels. I have colored the lines and points based on Type, but I also want the symbols in the legend to be grouped by Type, with labels. Something like this:

Sample

Native:

[] label

[] label

[] label

Non-Native:

[] label

[] label

[] label

I currently have this code for a related plot which successfully combined the points and lines into a single legend (thanks to help on this question).

ggplot(great_hollow, aes(x = d15N, y = Sample_ordered), color =
   Species_ordered) +
  geom_path(aes(group = Species_ordered, colour = Species_ordered)) +
  geom_point(aes(shape = Species_ordered, fill = Species_ordered),
  colour = "black", size = 3) +
  scale_shape_manual(values = c(21, 22, 24, 21, 23, 25)) +
  facet_wrap(~Type, scales = "fixed") +
  ggtitle(expression(paste(delta^{15},
    "N Values by Site and Trophic Level"))) +
  scale_x_continuous(expression(paste(delta^{15}, "N (\u2030 VS air)"))) +
  scale_y_discrete(limits=rev) +
  labs(color = "Sample", shape = "Sample", fill = "Sample") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5),
        axis.title.y = element_blank(),
        plot.background = element_rect(color = 1, linewidth = 1),
        plot.margin = margin(t = 10, r = 10, b = 10, l = 10))
```
<p>The resulting plot: <img src="https://i.stack.imgur.com/pYn7O.png" alt="single legend, legend items not grouped" /></p>
<p>I'm trying to create a plot like it where the legend is still combined but the plot is not faceted, there are only two colors (by Type), and the different levels of Species_ordered are grouped by Type in the legend.</p>
<p>This is what I have so far based on this question, using <code>ggnewscale</code>:</p>
<pre class="lang-r prettyprint-override"><code>ggplot(great_hollow, aes(x = d15N, y = Sample_ordered), color = Type) +
  geom_path(aes(group = Species_ordered, colour = Type)) +
  geom_point(aes(shape = Species_ordered, fill = Type),
   colour = "black", size = 3) +
  scale_shape_manual(values = c(21, 22, 24, 21, 23, 25)) +
  scale_fill_manual(name = "Native",
                    values = c("blue", "red"),
                    breaks = great_hollow$Type[c(1,5,6)],
                    labels = great_hollow$Species_ordered[c(1,5,6)],
                    guide = guide_legend(title.position = "top", order = 1))
   +
  new_scale_fill() +
  geom_path(aes(group = Species_ordered, colour = Type)) +
  scale_colour_manual(values = c("blue", "red")) +
  geom_point(aes(shape = Species_ordered, fill = Type), colour = "black",
  size = 3) +
  scale_fill_manual(name = "Non-Native",
                    values = c("blue", "red"),
                    breaks = great_hollow$Type[c(2:4)],
                    labels = great_hollow$Species_ordered[c(2:4)],
                    guide = guide_legend(title.position = "top", order = 2))
  +
  scale_colour_manual(values = c("blue", "red")) +
  ggtitle(expression(paste(delta^{15},
   "N Values by Site and Trophic Level"))) +
  scale_x_continuous(expression(paste(delta^{15}, "N (\u2030 VS air)"))) +
  scale_y_discrete(limits=rev) +
  labs(colour = "Sample", shape = "Sample", fill = "Sample") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5),
        axis.title.y = element_blank(),
        plot.background = element_rect(color = 1, linewidth = 1),
        plot.margin = margin(t = 10, r = 10, b = 10, l = 10))
</code>```

The resulting plot:

To be perfectly honest I can't quite figure out what the answerer was doing with "breaks" inside scale_fill_manual() so my issue might be there. I'm not sure why the "Native" and "Non-Native" legend groups appear by themselves and not integrated with the other legends or why they each only show one of the three labels from Species_ordered. I'm also not sure why the red points are switched to grey.

------ EDIT ------

After further digging I've made some progress. I was able to fix the mismatched coloring and merge the legends, but the legend does not show the line through the shape like it did in my first graph. I've also managed to separate the legend items into columns, but I still can't figure out how to sort them into those columns by Type or add subheadings.

```<code>ggplot(great_hollow, aes(x = d15N, y = Sample_ordered), colour = Type) +
  geom_path(aes(group = Species_ordered, colour = Type)) +
  scale_colour_manual(values = c("blue", "red")) +
  geom_point(aes(shape = Species_ordered, fill = Type), colour = "black", size = 3) +
  scale_shape_manual(name = "Species",
                     labels = great_hollow$Species_ordered,
                     values = c(21, 22, 24, 21, 23, 25)) +
  scale_fill_manual(name = "Species",
                    labels = great_hollow$Species_ordered,
                    values = c("blue", "red"),
                    guide = "none",
                    aesthetics = c("colour", "fill")) +
  guides(shape = guide_legend(ncol = 2, override.aes = list(fill = c("blue", "red", "red", "red", "blue", "blue")))) +
  ggtitle(expression(paste(delta^{15},"N Values by Site and Trophic Level"))) +
  scale_x_continuous(expression(paste(delta^{15}, "N (\u2030 VS air)"))) +
  scale_y_discrete(limits=rev) +
  theme_bw() +
  theme(axis.title.y = element_blank())
</code>```

And the resulting graph: Colors and columns mostly fixed, no subheadings

Body:
I have a connected scatterplot using geom_path and geom_point. I currently have the lines connecting the points by a grouping variable (Species_ordered) and each level of that variable symbolized by a different shape. I have another grouping variable (Type) which has two levels. I have colored the lines and points based on Type, but I also want the symbols in the legend to be grouped by Type, with labels. Something like this:

Sample

Native:

[] label

[] label

[] label

Non-Native:

[] label

[] label

[] label

I currently have this code for a related plot which successfully combined the points and lines into a single legend (thanks to help on this question).

ggplot(great_hollow, aes(x = d15N, y = Sample_ordered), color =
   Species_ordered) +
  geom_path(aes(group = Species_ordered, colour = Species_ordered)) +
  geom_point(aes(shape = Species_ordered, fill = Species_ordered),
  colour = "black", size = 3) +
  scale_shape_manual(values = c(21, 22, 24, 21, 23, 25)) +
  facet_wrap(~Type, scales = "fixed") +
  ggtitle(expression(paste(delta^{15},
    "N Values by Site and Trophic Level"))) +
  scale_x_continuous(expression(paste(delta^{15}, "N (\u2030 VS air)"))) +
  scale_y_discrete(limits=rev) +
  labs(color = "Sample", shape = "Sample", fill = "Sample") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5),
        axis.title.y = element_blank(),
        plot.background = element_rect(color = 1, linewidth = 1),
        plot.margin = margin(t = 10, r = 10, b = 10, l = 10))

The resulting plot:

I'm trying to create a plot like it where the legend is still combined but the plot is not faceted, there are only two colors (by Type), and the different levels of Species_ordered are grouped by Type in the legend.

This is what I have so far based on this question, using ggnewscale:

ggplot(great_hollow, aes(x = d15N, y = Sample_ordered), color = Type) +
  geom_path(aes(group = Species_ordered, colour = Type)) +
  geom_point(aes(shape = Species_ordered, fill = Type),
   colour = "black", size = 3) +
  scale_shape_manual(values = c(21, 22, 24, 21, 23, 25)) +
  scale_fill_manual(name = "Native",
                    values = c("blue", "red"),
                    breaks = great_hollow$Type[c(1,5,6)],
                    labels = great_hollow$Species_ordered[c(1,5,6)],
                    guide = guide_legend(title.position = "top", order = 1))
   +
  new_scale_fill() +
  geom_path(aes(group = Species_ordered, colour = Type)) +
  scale_colour_manual(values = c("blue", "red")) +
  geom_point(aes(shape = Species_ordered, fill = Type), colour = "black",
  size = 3) +
  scale_fill_manual(name = "Non-Native",
                    values = c("blue", "red"),
                    breaks = great_hollow$Type[c(2:4)],
                    labels = great_hollow$Species_ordered[c(2:4)],
                    guide = guide_legend(title.position = "top", order = 2))
  +
  scale_colour_manual(values = c("blue", "red")) +
  ggtitle(expression(paste(delta^{15},
   "N Values by Site and Trophic Level"))) +
  scale_x_continuous(expression(paste(delta^{15}, "N (\u2030 VS air)"))) +
  scale_y_discrete(limits=rev) +
  labs(colour = "Sample", shape = "Sample", fill = "Sample") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5),
        axis.title.y = element_blank(),
        plot.background = element_rect(color = 1, linewidth = 1),
        plot.margin = margin(t = 10, r = 10, b = 10, l = 10))

The resulting plot:

To be perfectly honest I can't quite figure out what the answerer was doing with "breaks" inside scale_fill_manual() so my issue might be there. I'm not sure why the "Native" and "Non-Native" legend groups appear by themselves and not integrated with the other legends or why they each only show one of the three labels from Species_ordered. I'm also not sure why the red points are switched to grey.

------ EDIT ------

After further digging I've made some progress. I was able to fix the mismatched coloring and merge the legends, but the legend does not show the line through the shape like it did in my first graph. I've also managed to separate the legend items into columns, but I still can't figure out how to sort them into those columns by Type or add subheadings.

ggplot(great_hollow, aes(x = d15N, y = Sample_ordered), colour = Type) +
  geom_path(aes(group = Species_ordered, colour = Type)) +
  scale_colour_manual(values = c("blue", "red")) +
  geom_point(aes(shape = Species_ordered, fill = Type), colour = "black", size = 3) +
  scale_shape_manual(name = "Species",
                     labels = great_hollow$Species_ordered,
                     values = c(21, 22, 24, 21, 23, 25)) +
  scale_fill_manual(name = "Species",
                    labels = great_hollow$Species_ordered,
                    values = c("blue", "red"),
                    guide = "none",
                    aesthetics = c("colour", "fill")) +
  guides(shape = guide_legend(ncol = 2, override.aes = list(fill = c("blue", "red", "red", "red", "blue", "blue")))) +
  ggtitle(expression(paste(delta^{15},"N Values by Site and Trophic Level"))) +
  scale_x_continuous(expression(paste(delta^{15}, "N (\u2030 VS air)"))) +
  scale_y_discrete(limits=rev) +
  theme_bw() +
  theme(axis.title.y = element_blank())

And the resulting graph: Colors and columns mostly fixed, no subheadings


问:
Not able to set values on Material UI TextField Select component
I am new to React.

I want to build a Form that has a Text field and a dropdown with 2 selections.
The form renders but I am unable to select any values from the dropdown. The handleChange function doesnt run.

```<code>const Category = () => {
    const theme = useTheme();
    const colors = tokens(theme.palette.mode);

    const [formValues, setformValues] = useState({
        categoryName: "Test",
        categoryType: "Expense",
    })

    const categories = [
        {
            value: 'Income',
            label: 'Income',
        },
        {
            value: 'Expense',
            label: 'Expense',
        },
    ];
    const handleFormSubmit = (values) => {
        console.log(`Submitting : ${JSON.stringify(values)}`);
    };
    const isNonMobile = useMediaQuery("(min-width:600px)");
    const handleCategoryTextChange = (event) => {
        console.log(`Category Text Change ${event}`);
        setformValues({
            ...formValues,
            categoryName: event.target.value,
        })
    }
    const handleCategoryChange = (event) => {
        console.log(`Category Change Event ${event.target.value}`);
        setformValues({
            ...formValues,
            categoryType: event.target.value
        })
    };

    return (
        <Box>
            <Box m="20px">
                <Header title="CREATE CATEGORY" subtitle="Create a New Category" />

                <form onSubmit={handleFormSubmit}>
                    <Box
                        display="grid"
                        gap="30px"
                        gridTemplateColumns="repeat(4, minmax(0, 1fr))"
                        sx={{
                            "& > div": { gridColumn: isNonMobile ? undefined : "span 4" },
                        }}
                    >
                        <TextField
                            fullWidth
                            variant="filled"
                            type="text"
                            label="Category Name"
                            onChange={handleCategoryTextChange}
                            value={formValues.categoryName}
                            name="categoryName"
                            sx={{ gridColumn: "span 2" }}
                        />
                        <TextField
                            fullWidth
                            variant="filled"
                            label="Category Type"
                            onChange={handleCategoryChange}
                            value={formValues.categoryType}
                            name="categoryType"
                            sx={{ gridColumn: "span 2" }}
                            select
                            >
                            {categories.map((option) => (
                                <MenuItem key = {option.value} value={option.value}>
                                    {option.label}
                                </MenuItem>
                            ))}
                        </TextField>
                    </Box>
                </form>

               </Box>
        </Box>
    );
};
</code>```

I am expecting the dropdown to be selectable and the handleChange events to be triggered.

Once this is working, I would submit the form values to an API endpoint

Body:
I am new to React.

I want to build a Form that has a Text field and a dropdown with 2 selections.
The form renders but I am unable to select any values from the dropdown. The handleChange function doesnt run.

const Category = () => {
    const theme = useTheme();
    const colors = tokens(theme.palette.mode);

    const [formValues, setformValues] = useState({
        categoryName: "Test",
        categoryType: "Expense",
    })

    const categories = [
        {
            value: 'Income',
            label: 'Income',
        },
        {
            value: 'Expense',
            label: 'Expense',
        },
    ];
    const handleFormSubmit = (values) => {
        console.log(`Submitting : ${JSON.stringify(values)}`);
    };
    const isNonMobile = useMediaQuery("(min-width:600px)");
    const handleCategoryTextChange = (event) => {
        console.log(`Category Text Change ${event}`);
        setformValues({
            ...formValues,
            categoryName: event.target.value,
        })
    }
    const handleCategoryChange = (event) => {
        console.log(`Category Change Event ${event.target.value}`);
        setformValues({
            ...formValues,
            categoryType: event.target.value
        })
    };

    return (
        <Box>
            <Box m="20px">

                <form onSubmit={handleFormSubmit}>
                    <Box
                        display="grid"
                        gap="30px"
                        gridTemplateColumns="repeat(4, minmax(0, 1fr))"
                        sx={{
                            "& > div": { gridColumn: isNonMobile ? undefined : "span 4" },
                        }}
                    >
                        <TextField
                            fullWidth
                            variant="filled"
                            type="text"
                            label="Category Name"
                            onChange={handleCategoryTextChange}
                            value={formValues.categoryName}
                            name="categoryName"
                            sx={{ gridColumn: "span 2" }}
                        />
                        <TextField
                            fullWidth
                            variant="filled"
                            label="Category Type"
                            onChange={handleCategoryChange}
                            value={formValues.categoryType}
                            name="categoryType"
                            sx={{ gridColumn: "span 2" }}
                            select
                            >
                            {categories.map((option) => (
                                <MenuItem key = {option.value} value={option.value}>
                                    {option.label}
                                </MenuItem>
                            ))}
                        </TextField>
                    </Box>
                </form>

               </Box>
        </Box>
    );
};

I am expecting the dropdown to be selectable and the handleChange events to be triggered.

Once this is working, I would submit the form values to an API endpoint


问:
I want build a alert for ema indicator crypto in a special list
First one:

```<code>    ### configuration details
    TELEGRAM_TOKEN = '' # telegram bot token
    TELEGRAM_CHANNEL ='' # channel id
    INTERVAL = '1m' # binance time interval
    SHORT_EMA = 7 # short interval for ema
    LONG_EMA = 21 # long interval for ema
</code>```

Here is my second code:

```<code>
import requests
import talib
import time
import numpy as np
import websocket

from config import TELEGRAM_TOKEN, TELEGRAM_CHANNEL , INTERVAL, SHORT_EMA , LONG_EMA

def streamKline(currency, interval):
    websocket.enableTrace(False)
    socket = f'wss://stream.binance.com:9443/ws/{currency}@kline_{interval}'
    ws = websocket.WebSocketApp(socket)

    ws.run_forever()

#SYMBOLS TO LOOK FOR ALERTS
SYMBOLS = [
    "ETHUSDT",
    "BTCUSDT",
    "ATOMUSDT",
    "BNBUSDT",
    "FTMBUSD",
    "ENJUSDT",
    "WAXPUSDT"
]

#sending alerts to telegram
def send_message(message):
    url = "https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}&parse_mode=markdown".format(TELEGRAM_TOKEN,TELEGRAM_CHANNEL,message)
    res = requests.get(url);print(url);
    return res

# getting klines data to process
def streamKline(symbol):
    data = socket.streamKline(symbol=symbol,interval=INTERVAL,limit=300) # more data means more precision but at the trade off between speed and time
    return_data = []
    # taking closing data for each kline
    for each in data:
        return_data.append(float(each[4])) # 4 is the index of the closing data in each kline
    return np.array(return_data) # returning as numpy array for better precision and performance

def main():
    # making a infinite loop that keeps checking for condition
    while True:
        #looping through each coin
        for each in SYMBOLS:
            data = streamKline(each)
            ema_short = talib.EMA(data,int(SHORT_EMA))
            ema_long = talib.EMA(data,int(LONG_EMA))

            last_ema_short  = ema_short[-2]
            last_ema_long = ema_long[-2]

            ema_short = ema_short[-1]
            ema_long = ema_long[-1]

            # conditions for alerts
            if(ema_short > ema_long and last_ema_short < last_ema_long):
                message  = each + "bullcoming "+ str(SHORT_EMA) + " over "+str(LONG_EMA);print(each ,"alert came");
                send_message(message);
            time.sleep(0.5);

# calling the function
if __name__ == "__main__":
    main()

</code>```

The part of config is all settle done, just second for the kline data, the error mention lot like this.

```<code>  data = socket.streamKline(symbol=symbol,interval=INTERVAL,limit=300) # more data means more precision but at the
trade off between speed and time
NameError: name 'socket' is not defined
</code>```

I just don't know how to do it, I want build a ema alert that can give me a message when I am not watching chart, through this way seems not work, I have tried many times, and also find many video but still, I am just an beginner, nothing improving at all.

Body:
First one:

    ### configuration details
    TELEGRAM_TOKEN = '' # telegram bot token
    TELEGRAM_CHANNEL ='' # channel id
    INTERVAL = '1m' # binance time interval
    SHORT_EMA = 7 # short interval for ema
    LONG_EMA = 21 # long interval for ema

Here is my second code:

import requests
import talib
import time
import numpy as np
import websocket

from config import TELEGRAM_TOKEN, TELEGRAM_CHANNEL , INTERVAL, SHORT_EMA , LONG_EMA

def streamKline(currency, interval):
    websocket.enableTrace(False)
    socket = f'wss://stream.binance.com:9443/ws/{currency}@kline_{interval}'
    ws = websocket.WebSocketApp(socket)

    ws.run_forever()

#SYMBOLS TO LOOK FOR ALERTS
SYMBOLS = [
    "ETHUSDT",
    "BTCUSDT",
    "ATOMUSDT",
    "BNBUSDT",
    "FTMBUSD",
    "ENJUSDT",
    "WAXPUSDT"
]

#sending alerts to telegram
def send_message(message):
    url = "https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}&parse_mode=markdown".format(TELEGRAM_TOKEN,TELEGRAM_CHANNEL,message)
    res = requests.get(url);print(url);
    return res

# getting klines data to process
def streamKline(symbol):
    data = socket.streamKline(symbol=symbol,interval=INTERVAL,limit=300) # more data means more precision but at the trade off between speed and time
    return_data = []
    # taking closing data for each kline
    for each in data:
        return_data.append(float(each[4])) # 4 is the index of the closing data in each kline
    return np.array(return_data) # returning as numpy array for better precision and performance

def main():
    # making a infinite loop that keeps checking for condition
    while True:
        #looping through each coin
        for each in SYMBOLS:
            data = streamKline(each)
            ema_short = talib.EMA(data,int(SHORT_EMA))
            ema_long = talib.EMA(data,int(LONG_EMA))

            last_ema_short  = ema_short[-2]
            last_ema_long = ema_long[-2]

            ema_short = ema_short[-1]
            ema_long = ema_long[-1]

            # conditions for alerts
            if(ema_short > ema_long and last_ema_short < last_ema_long):
                message  = each + "bullcoming "+ str(SHORT_EMA) + " over "+str(LONG_EMA);print(each ,"alert came");
                send_message(message);
            time.sleep(0.5);

# calling the function
if __name__ == "__main__":
    main()

The part of config is all settle done, just second for the kline data, the error mention lot like this.

  data = socket.streamKline(symbol=symbol,interval=INTERVAL,limit=300) # more data means more precision but at the
trade off between speed and time
NameError: name 'socket' is not defined

I just don't know how to do it, I want build a ema alert that can give me a message when I am not watching chart, through this way seems not work, I have tried many times, and also find many video but still, I am just an beginner, nothing improving at all.


问:
XLSX2CSV in pandas only reading filtered rows in excel unlike read_excel(). How to read all rows?
I am trying to use XLSX2CSV instead of read_excel() method since XLSX2CSV is faster. But issue is it is only reading filtered rows in excel and not all the rows.
I am using XLSX2CSV because it is faster in reading excel files as compared to read_excel() from openpyxl. But using XLSX2CSV only reads filtered rows of a sheet whereas read_excel() reads all rows regardless if the sheet is filtered or not.
I havent found any method to read all rows using XLSX2CSV. Below is the sample code

```<code>filepath = os.path.join(FolderPath, FileName)
a = load_workbook(filepath, read_only=True)

def read_excel_file(path: str, sheet_index: int) -> pd.DataFrame:
buffer = StringIO()
     Xlsx2csv(path, outputencoding="utf8").convert(buffer,sheetid=sheet_index)
buffer.seek(0)
df = pd.read_csv(buffer)
return df
</code>```

dfinal=read_excel_file(filepath,a.index(a.get_sheet_by_name('Sheetname'))+1)

Body:
I am trying to use XLSX2CSV instead of read_excel() method since XLSX2CSV is faster. But issue is it is only reading filtered rows in excel and not all the rows.
I am using XLSX2CSV because it is faster in reading excel files as compared to read_excel() from openpyxl. But using XLSX2CSV only reads filtered rows of a sheet whereas read_excel() reads all rows regardless if the sheet is filtered or not.
I havent found any method to read all rows using XLSX2CSV. Below is the sample code

filepath = os.path.join(FolderPath, FileName)
a = load_workbook(filepath, read_only=True)

def read_excel_file(path: str, sheet_index: int) -> pd.DataFrame:
buffer = StringIO()
     Xlsx2csv(path, outputencoding="utf8").convert(buffer,sheetid=sheet_index)
buffer.seek(0)
df = pd.read_csv(buffer)
return df

dfinal=read_excel_file(filepath,a.index(a.get_sheet_by_name('Sheetname'))+1)


问:
How to update ejs data and go through the cycle of commands again while deleting the original array without disturbing any textboxes
So I have an EJS page that displays data from a query in a forloop. Is there a way that I would be able to delete the stuff contained in the forloop, do another query, then display the results all without redirection and also without removing anything from the textbox that the user is using?

I just have a typical EJS page pushing an array and a few bits of data through so is this possible? Would I need another listener?


问:
"Error in `[.data.frame`(database, , apollo_control$indivID) : undefined columns selected" in R studio
At this moment i want to create a model from apollo packages. I import the data from .txt file and want to create appollo_fixed variable.Then, this error message occured. (The data was imported succesfully)

apollo_inputs = apollo_validateInputs()
Error in [.data.frame(database, , apollo_control$indivID) :
undefined columns selected

The code I use is shown here,

```<code>rm(list = ls())
### Load libraries
library(apollo)
### Initialise code
apollo_initialise()

### Set core controls
apollo_control = list(
     modelName  ="MNL",
     modelDescr ="Simple MNL model on mode choice data",
     indivID    ="id")

# ####################################################### #
#### 2. Data loading                                   ####
# ####################################################### #

mydata <- read.table("/Documents/Travelmode_Final_project.txt", header=TRUE)
database = mydata
rm(mydata)

# ####################################################### #
#### 3. Parameter definition                           ####
# ####################################################### #

### Vector of parameters, including any that are kept fixed during estimation
apollo_beta=c(shuttlebus=0,
               citybus=0,
               bike=0,
               ubike=0,
               motorbike=0,
               car=0,
               mrt=0,
               taxi=0,
               b_SB_TC=0,
               b_SB_TT=0,
               b_CB_TC=0,
               b_CB_TT=0,
               b_B_TC=0,
               b_B_TT=0,
               b_UB_TC = 0,
               b_UB_TT=0,
               b_M_TC=0,
               b_M_TT=0,
               b_C_TC=0,
               b_C_TT=0,
               b_MRT_TT=0,
               b_MRT_TC=0,
               b_T_TT=0,
               b_T_TC=0)

apollo_fixed = c("shuttlebus")

# ####################################################### #
#### 4. Input validation                               ####
# ####################################################### #

apollo_inputs = apollo_validateInputs()

</code>```

Is there any solution I may need to change to solve this error? Or any potential reasons that may cause this error?

Body:
At this moment i want to create a model from apollo packages. I import the data from .txt file and want to create appollo_fixed variable.Then, this error message occured. (The data was imported succesfully)

apollo_inputs = apollo_validateInputs()
Error in [.data.frame(database, , apollo_control$indivID) :
undefined columns selected

The code I use is shown here,

rm(list = ls())
### Load libraries
library(apollo)
### Initialise code
apollo_initialise()

### Set core controls
apollo_control = list(
     modelName  ="MNL",
     modelDescr ="Simple MNL model on mode choice data",
     indivID    ="id")

# ####################################################### #
#### 2. Data loading                                   ####
# ####################################################### #

mydata <- read.table("/Documents/Travelmode_Final_project.txt", header=TRUE)
database = mydata
rm(mydata)

# ####################################################### #
#### 3. Parameter definition                           ####
# ####################################################### #

### Vector of parameters, including any that are kept fixed during estimation
apollo_beta=c(shuttlebus=0,
               citybus=0,
               bike=0,
               ubike=0,
               motorbike=0,
               car=0,
               mrt=0,
               taxi=0,
               b_SB_TC=0,
               b_SB_TT=0,
               b_CB_TC=0,
               b_CB_TT=0,
               b_B_TC=0,
               b_B_TT=0,
               b_UB_TC = 0,
               b_UB_TT=0,
               b_M_TC=0,
               b_M_TT=0,
               b_C_TC=0,
               b_C_TT=0,
               b_MRT_TT=0,
               b_MRT_TC=0,
               b_T_TT=0,
               b_T_TC=0)

apollo_fixed = c("shuttlebus")

# ####################################################### #
#### 4. Input validation                               ####
# ####################################################### #

apollo_inputs = apollo_validateInputs()

Is there any solution I may need to change to solve this error? Or any potential reasons that may cause this error?


问:
Capture Print Screen key pressed from background service c#
I have .NET6 Background Service application from which I want to listen to keyboard and when Print Screen button is pressed, to run some code from that background service.

I have found multiple answers to listening for key press but haven't managed to make any work. All of them use User32.dll and methods that I tried using are RegisterHotkey and SetWindowsHookEx.

Closes I think I came is with SetWindowsHookEx since when I run it and try opening new tab in chrome with Control + T I see it lags for few milliseconds, but for some reason callback handler in my code is not hit.

Here is the that code I managed to get to kind a work:

```<code>namespace LSShot;
using System.Drawing;
using System.Runtime.InteropServices;

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    #region Import Methods
    [DllImport("User32.dll")]
    public static extern IntPtr GetDC(IntPtr hwnd);
    [DllImport("User32.dll")]
    public static extern void ReleaseDC(IntPtr hwnd, IntPtr dc);
    [DllImport("User32.dll")]
    public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
    [DllImport("User32.dll")]
    public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    [DllImport("User32.dll")]
    public static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
    [DllImport("user32.dll")]
    public static extern bool UnhookWindowsHookEx(IntPtr hInstance);
    [DllImport("user32.dll")]
    static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
    [DllImport("kernel32.dll")]
    static extern IntPtr LoadLibrary(string lpFileName);
    #endregion
    #region Structures
    public struct keyboardHookStruct
    {
        public int vkCode;
        public int scanCode;
        public int flags;
        public int time;
        public int dwExtraInfo;
    }
    #endregion
    public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
    public IntPtr hhook = IntPtr.Zero;
    private static keyboardHookProc callbackDelegate;
    const int WH_KEYBOARD_LL = 13;
    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
        Hook();
    }
    ~Worker()
    {
        Unhook();
    }

    private void Hook()
    {
        if(callbackDelegate != null)
            throw new InvalidOperationException("Can't hook more than once!");

        IntPtr hInstance = LoadLibrary("User32");
        callbackDelegate = new keyboardHookProc(hookProc);
        hhook = SetWindowsHookEx(WH_KEYBOARD_LL, callbackDelegate, hInstance, 0);

        if (hhook == IntPtr.Zero)
            throw new Exception("IntPtr.Zero");
    }

    private void Unhook()
    {

    }

    private int hookProc(int code, int wParam, ref keyboardHookStruct lParam)
    {
        _logger.LogInformation(code.ToString());
        return CallNextHookEx(hhook, code, wParam, ref lParam);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
        }
    }
}

</code>```

Body:
I have .NET6 Background Service application from which I want to listen to keyboard and when Print Screen button is pressed, to run some code from that background service.

I have found multiple answers to listening for key press but haven't managed to make any work. All of them use User32.dll and methods that I tried using are RegisterHotkey and SetWindowsHookEx.

Closes I think I came is with SetWindowsHookEx since when I run it and try opening new tab in chrome with Control + T I see it lags for few milliseconds, but for some reason callback handler in my code is not hit.

Here is the that code I managed to get to kind a work:

namespace LSShot;
using System.Drawing;
using System.Runtime.InteropServices;

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    #region Import Methods
    [DllImport("User32.dll")]
    public static extern IntPtr GetDC(IntPtr hwnd);
    [DllImport("User32.dll")]
    public static extern void ReleaseDC(IntPtr hwnd, IntPtr dc);
    [DllImport("User32.dll")]
    public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
    [DllImport("User32.dll")]
    public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    [DllImport("User32.dll")]
    public static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
    [DllImport("user32.dll")]
    public static extern bool UnhookWindowsHookEx(IntPtr hInstance);
    [DllImport("user32.dll")]
    static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
    [DllImport("kernel32.dll")]
    static extern IntPtr LoadLibrary(string lpFileName);
    #endregion
    #region Structures
    public struct keyboardHookStruct
    {
        public int vkCode;
        public int scanCode;
        public int flags;
        public int time;
        public int dwExtraInfo;
    }
    #endregion
    public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
    public IntPtr hhook = IntPtr.Zero;
    private static keyboardHookProc callbackDelegate;
    const int WH_KEYBOARD_LL = 13;
    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
        Hook();
    }
    ~Worker()
    {
        Unhook();
    }

    private void Hook()
    {
        if(callbackDelegate != null)
            throw new InvalidOperationException("Can't hook more than once!");

        IntPtr hInstance = LoadLibrary("User32");
        callbackDelegate = new keyboardHookProc(hookProc);
        hhook = SetWindowsHookEx(WH_KEYBOARD_LL, callbackDelegate, hInstance, 0);

        if (hhook == IntPtr.Zero)
            throw new Exception("IntPtr.Zero");
    }

    private void Unhook()
    {

    }

    private int hookProc(int code, int wParam, ref keyboardHookStruct lParam)
    {
        _logger.LogInformation(code.ToString());
        return CallNextHookEx(hhook, code, wParam, ref lParam);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
        }
    }
}


问:
github: merge master to feature branch, then push feature branch, merge to master?
I have a question about github:

```<code>1. create a new feature branch locally: fb and work on it.
2. At the same time, other people may work on master, or work on their feature branches and merge to master. So master branch keeps changing.
3. I finish the work on my local feature branch fb.
4. I want to merge fb and master together locally so as to have all the updates.
5. I push local fb to remote fb and wait for approve request.
6. Once approved, will merge fb to master.
</code>```

How to finish these steps?

Body:
I have a question about github:

1. create a new feature branch locally: fb and work on it.
2. At the same time, other people may work on master, or work on their feature branches and merge to master. So master branch keeps changing.
3. I finish the work on my local feature branch fb.
4. I want to merge fb and master together locally so as to have all the updates.
5. I push local fb to remote fb and wait for approve request.
6. Once approved, will merge fb to master.

How to finish these steps?


问:
CI-CD declarative pipeline. How to trigger automatic dependency updates using pipeline in jenkins
I want to implement automatic dependency update on my Jenkins job through declarative pipeline approach. Please guide me how I can achieve this.  I searched everywhere but I couldn't find any solution, I want to implement the logic inside the pipeline stage where it would automatically updated required dependency if any update is required.

I want to check dependency only in my application pom.xml file and automatically update if any dependency is missing or needs updated through declarative pipeline CI-CD process. Please guide me


问:
How to resolve SoapClient ssl error on server
I have:

```<code>$soap = new \SoapClient(
    $this->getWsdl(),
    [
        'local_cert' => $this->certificatePath,
        'passphrase' => $this->certificatePassword,
        'trace' => true,
        'exceptions' => true,
        'style' => SOAP_RPC,
        'use' => SOAP_ENCODED,
        'soap_version' => SOAP_1_2,
        'wsdl_cache' => $this->isTest ? WSDL_CACHE_NONE : WSDL_CACHE_MEMORY,
    ]
);
</code>```

Result of $soap->__doRequest is null and openssl_error_string() display 0607A082:digital envelope routines:EVP_CIPHER_CTX_set_key_length:invalid key length.

Same code on xampp work well.

Certificate path is correct, because when i run file_get_contents($this->certificatePath()), I see the file data.

Body:
I have:

$soap = new \SoapClient(
    $this->getWsdl(),
    [
        'local_cert' => $this->certificatePath,
        'passphrase' => $this->certificatePassword,
        'trace' => true,
        'exceptions' => true,
        'style' => SOAP_RPC,
        'use' => SOAP_ENCODED,
        'soap_version' => SOAP_1_2,
        'wsdl_cache' => $this->isTest ? WSDL_CACHE_NONE : WSDL_CACHE_MEMORY,
    ]
);

Result of $soap->__doRequest is null and openssl_error_string() display 0607A082:digital envelope routines:EVP_CIPHER_CTX_set_key_length:invalid key length.

Same code on xampp work well.

Certificate path is correct, because when i run file_get_contents($this->certificatePath()), I see the file data.


问:
Using Mongo Atlas API in Netlify Functions
I am trying to return a string from a mongo Atlas function that works locally, but whenever I run neltify deploy I get a message saying invalid URL. My .env variables, which are API URL and API key, are stored in my netlify server. I am new to mongo atlas API, so I am not sure what the issue is. My mongo function allows anonymous authentication as well as an API key. Here is my netlify function

```<code>
import axios from "axios"
export async function handler(event, context) {
    const web = process.env.MONGO_ENDPOINT
    console.log(web)
    console.log("hi")
    try {
        const response = await axios.get(process.env.MONGO_ENDPOINT, {
            headers: {
                'Content-Type':'application/json',
                'Access-Control-Request-Headers':' *',
                'api-key': process.env.KEY,
            }
        })
        const data = response.data

        return {
            statusCode: 200,
            body: JSON.stringify({ msg: data[0].quote })
        };
    } catch (err) {
        console.log(err) // output to netlify function log
        return {
            statusCode: 500,
            body: JSON.stringify({ msg: err.message }) // Could be a custom message or object i.e. JSON.stringify(err)
        }
    }
}
</code>```

and here is my mongo API endpoint

```<code>exports = function(arg){

    const mongodb = context.services.get("Cluster0");
    const db=mongodb.db("phi")
    const collection=db.collection("quotes");
    const item = collection.aggregate([{ $sample: { size: 1 } }])
    const quote =item
  return (quote);
};
</code>```

As I said it all works locally, but not when I deploy to Netlify. Please let me know if you have any tips

I tried using the headers recommended by MongoDB and no success. I also tried to use the MongoClient package, but id rather use my mongo function endpoint

ANSWER: You do not need quotes around .env variables

Body:
I am trying to return a string from a mongo Atlas function that works locally, but whenever I run neltify deploy I get a message saying invalid URL. My .env variables, which are API URL and API key, are stored in my netlify server. I am new to mongo atlas API, so I am not sure what the issue is. My mongo function allows anonymous authentication as well as an API key. Here is my netlify function

import axios from "axios"
export async function handler(event, context) {
    const web = process.env.MONGO_ENDPOINT
    console.log(web)
    console.log("hi")
    try {
        const response = await axios.get(process.env.MONGO_ENDPOINT, {
            headers: {
                'Content-Type':'application/json',
                'Access-Control-Request-Headers':' *',
                'api-key': process.env.KEY,
            }
        })
        const data = response.data

        return {
            statusCode: 200,
            body: JSON.stringify({ msg: data[0].quote })
        };
    } catch (err) {
        console.log(err) // output to netlify function log
        return {
            statusCode: 500,
            body: JSON.stringify({ msg: err.message }) // Could be a custom message or object i.e. JSON.stringify(err)
        }
    }
}

and here is my mongo API endpoint

exports = function(arg){

    const mongodb = context.services.get("Cluster0");
    const db=mongodb.db("phi")
    const collection=db.collection("quotes");
    const item = collection.aggregate([{ $sample: { size: 1 } }])
    const quote =item
  return (quote);
};

As I said it all works locally, but not when I deploy to Netlify. Please let me know if you have any tips

I tried using the headers recommended by MongoDB and no success. I also tried to use the MongoClient package, but id rather use my mongo function endpoint

ANSWER: You do not need quotes around .env variables


问:
ORA-00904 whlie executing impdp
I'm trying to import ORIG schema into TEST schema.

ORIG schema was exported with filename exp_orig.dmp.

Following are the command I executed and its referencing parfile(imp_testdb.par).

command :

impdp TEST/123@TESTDB parfile=imp_testdb.par

imp_testdb.par :

```<code>remap_schema=ORIG:TEST
dumpfile=exp_orig.dmp
logfile=imp_test.log
directory=ORA_IMPROT
logtime=ALL
metrics=YES
exclude=DB_LINK
table_exists_action=REPLACE
</code>```

When I execute the command, it crashes with following errors :

```<code>ORA-39068: invalid master table data in row with PROCESS_ORDER=-13
ORA-00904: "TAG": invalid identifier
</code>```

I have no idea how to debug ORA-00904 and I couldn't find solution on google which applies to my situation, so I tried validating things one by one.

I created another user with the same spec and impdp to that user failed with same errors.

=> so it wasn't specific to target schema

I exported(expdp) the original schema again and impdp with the new file failed with same errors.

=> so it wasn't specific to a dumpfile

Then I started validating the parfile parameters

=> when I took out exclude=DB_LINK option in the parfile, impdp was successfully executed.

What reason could this possibly be due to?

Title: ORA-00904 whlie executing impdp

Body:
I'm trying to import ORIG schema into TEST schema.

ORIG schema was exported with filename exp_orig.dmp.

Following are the command I executed and its referencing parfile(imp_testdb.par).

command :

impdp TEST/123@TESTDB parfile=imp_testdb.par

imp_testdb.par :

remap_schema=ORIG:TEST
dumpfile=exp_orig.dmp
logfile=imp_test.log
directory=ORA_IMPROT
logtime=ALL
metrics=YES
exclude=DB_LINK
table_exists_action=REPLACE

When I execute the command, it crashes with following errors :

ORA-39068: invalid master table data in row with PROCESS_ORDER=-13
ORA-00904: "TAG": invalid identifier

I have no idea how to debug ORA-00904 and I couldn't find solution on google which applies to my situation, so I tried validating things one by one.

I created another user with the same spec and impdp to that user failed with same errors.

=> so it wasn't specific to target schema

I exported(expdp) the original schema again and impdp with the new file failed with same errors.

=> so it wasn't specific to a dumpfile

Then I started validating the parfile parameters

=> when I took out exclude=DB_LINK option in the parfile, impdp was successfully executed.

What reason could this possibly be due to?


问:
Uploaded file appended to Form Data shows as empty?
I am trying to upload an image file, using vue.js to process it client-side, axios to post to the server, and Laravel as the php server.

On the client side I have:

<template>
    <form class="row g-3 needs-validation" novalidate @submit.prevent="save" enctype="multipart/form-data">
        <input type="file" id="inputImg" accept="image/png, image/jpeg" @change="handleFileUpload($event)" />
    </form>
    <button type="button" class="btn btn-success" @click="saveItem">Save</button>
</template>
```
<p>When the post request is sent the formData shows correctly, except the file which shows as empty in the request. The console log of formData shows:</p>
<pre class="lang-bash prettyprint-override"><code>FormData(5) { file → {}, name → "testItem", type → "hot dish", price → "1", description → "desc" }
</code>```

But under  it has the File object itself, as can be seen here: https://imgur.com/xS1KH5x

I've googled around and most tutorials and showcases say that simply appending the file is enough to send it to the server. Adding

headers: { 'content-type': 'multipart/form-data' }
```

to axios does not help, as the file always shows as empty.

Body:
I am trying to upload an image file, using vue.js to process it client-side, axios to post to the server, and Laravel as the php server.

On the client side I have:

<template>
    <form class="row g-3 needs-validation" novalidate @submit.prevent="save" enctype="multipart/form-data">
        <input type="file" id="inputImg" accept="image/png, image/jpeg" @change="handleFileUpload($event)" />
    </form>
    <button type="button" class="btn btn-success" @click="saveItem">Save</button>
</template>

When the post request is sent the formData shows correctly, except the file which shows as empty in the request. The console log of formData shows:

FormData(5) { file → {}, name → "testItem", type → "hot dish", price → "1", description → "desc" }

But under  it has the File object itself, as can be seen here: https://imgur.com/xS1KH5x

I've googled around and most tutorials and showcases say that simply appending the file is enough to send it to the server. Adding

headers: { 'content-type': 'multipart/form-data' }

to axios does not help, as the file always shows as empty.


问:
Cannot get response for requests that are over abt 5 minutes on AWS load-balanced environment
We are sending a POST request that could take a couple of minutes from our application registered as a windows service on one AWS server to our API which is located in an AWS load-balanced environment. Both are C# .Net 4.7.2 projects.

The request could take 1 - 60 minutes depending on the data amount. And we notice that for requests that take more than around 5 minutes, there is a big chance that the request would be lost. We have adde detailed logs at both ends to ensure that the response is generated and sent out from our API, but no response or error message is received on the other end. Since we set an one-hour cancelationToken for the request, so at last the request would failed due to timeout after one hour, however according to the logs we added, the response should have been sent out a long time ago.

For now, we have checked IIS and AWS idle timeout but none seems to be relavant to the issue. And we are having no idea at all about what could possibly cause this issue.

If anyone had experienced similar situation or know potential direction that we could dig into, that would be really helpful!

Thanks!

========================================================================
We have tried adding logs to ensure the response is not blocked somewhere in the api or it reaches the service and we just didn't realize.

We have tried configured IIS and AWS timeout, the first does not seem to be relevant, the second is already over one hour so should not be the obstacle.

WE have tried specifying the api address to go to one specific server rather than load-balanced url, and this is still occurring.

Shorter responses do not have this problem. The shorter time it takes, the lower chance it could be lost.