问:
ubuntu20.04：The file is damaged, resulting in the inability of conda to connect to the network
My computer environment is ubuntu20.04，conda 22.9.0. I'm Unable to execute the [conda install] and [conda env list] commands. However, I can execute the [conda activate lf] command. When the [conda install ] and [conda env list] command  is executed, this error prompt appears

```<code>Traceback (most recent call last):
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/gateways/connection/__init__.py", line 8, in <module>
    from requests import ConnectionError, HTTPError, Session
ModuleNotFoundError: No module named 'requests'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/wpu/anaconda3/bin/conda-env", line 6, in <module>
    from conda_env.cli.main import main
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda_env/cli/main.py", line 13, in <module>
    import conda.exports  # noqa
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/exports.py", line 24, in <module>
    from . import plan  # noqa: F401
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/plan.py", line 28, in <module>
    from .core.index import LAST_CHANNEL_URLS, _supplement_index_with_prefix
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/core/index.py", line 19, in <module>
    from .package_cache_data import PackageCacheData
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/core/package_cache_data.py", line 21, in <module>
    from .path_actions import CacheUrlAction, ExtractPackageAction
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/core/path_actions.py", line 34, in <module>
    from ..gateways.connection.download import download
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/gateways/connection/__init__.py", line 21, in <module>
    from pip._vendor.requests import ConnectionError, HTTPError, Session
ModuleNotFoundError: No module named 'pip'
</code>```

I don't know what causes these problem. Can you help me?

I thought the [requests] module was not installed, but when I execute the [pip install requests] command, the following prompt appears:

```<code>Requirement already satisfied: requests in /usr/lib/python3/dist-packages (2.22.0)
</code>```

Executing the pip statement smoothly。

Body:
My computer environment is ubuntu20.04，conda 22.9.0. I'm Unable to execute the [conda install] and [conda env list] commands. However, I can execute the [conda activate lf] command. When the [conda install ] and [conda env list] command  is executed, this error prompt appears

Traceback (most recent call last):
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/gateways/connection/__init__.py", line 8, in <module>
    from requests import ConnectionError, HTTPError, Session
ModuleNotFoundError: No module named 'requests'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/wpu/anaconda3/bin/conda-env", line 6, in <module>
    from conda_env.cli.main import main
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda_env/cli/main.py", line 13, in <module>
    import conda.exports  # noqa
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/exports.py", line 24, in <module>
    from . import plan  # noqa: F401
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/plan.py", line 28, in <module>
    from .core.index import LAST_CHANNEL_URLS, _supplement_index_with_prefix
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/core/index.py", line 19, in <module>
    from .package_cache_data import PackageCacheData
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/core/package_cache_data.py", line 21, in <module>
    from .path_actions import CacheUrlAction, ExtractPackageAction
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/core/path_actions.py", line 34, in <module>
    from ..gateways.connection.download import download
  File "/home/wpu/anaconda3/lib/python3.9/site-packages/conda/gateways/connection/__init__.py", line 21, in <module>
    from pip._vendor.requests import ConnectionError, HTTPError, Session
ModuleNotFoundError: No module named 'pip'

I don't know what causes these problem. Can you help me?

I thought the [requests] module was not installed, but when I execute the [pip install requests] command, the following prompt appears:

Requirement already satisfied: requests in /usr/lib/python3/dist-packages (2.22.0)

Executing the pip statement smoothly。


来源: stackexchange

问:
CMAKE: CMAKE_SYSTEM_PROCESSOR not set/empty although toolchain file is not used
We have a pretty large build environment with cmake, utilizing conan to install/download dependency files and then run our build. Within our build I need to identify the target system processor and therefore I am utilizing CMAKE_SYSTEM_PROCESSOR. However on M1 macbook this value seems to be empty and unset in our environment (does not occur on macbook with intel processor), such as I attempted to print the useful defines (after calling project(<NAME>)) and got;

```<code>=== CMAKE_SYSTEM_PROCESSOR:
=== CMAKE_HOST_SYSTEM_PROCESSOR: arm64
=== CMAKE_TOOLCHAIN_FILE:
=== CMAKE_APPLE_SILICON_PROCESSOR:
</code>```

From my understanding if the CMAKE_TOOLCHAIN_FILE is unset then CMAKE_SYSTEM_PROCESSOR should equal the CMAKE_HOST_SYSTEM_PROCESSOR, which it does not occur in our use case. I attempted to make a more simply hello-world example on my system and it does indeed get set correctly, however I am unable to determine why this same does not occur in our environment.

ContentLicense: CC BY-SA 4.0

Body:
We have a pretty large build environment with cmake, utilizing conan to install/download dependency files and then run our build. Within our build I need to identify the target system processor and therefore I am utilizing CMAKE_SYSTEM_PROCESSOR. However on M1 macbook this value seems to be empty and unset in our environment (does not occur on macbook with intel processor), such as I attempted to print the useful defines (after calling project(<NAME>)) and got;

=== CMAKE_SYSTEM_PROCESSOR:
=== CMAKE_HOST_SYSTEM_PROCESSOR: arm64
=== CMAKE_TOOLCHAIN_FILE:
=== CMAKE_APPLE_SILICON_PROCESSOR:

From my understanding if the CMAKE_TOOLCHAIN_FILE is unset then CMAKE_SYSTEM_PROCESSOR should equal the CMAKE_HOST_SYSTEM_PROCESSOR, which it does not occur in our use case. I attempted to make a more simply hello-world example on my system and it does indeed get set correctly, however I am unable to determine why this same does not occur in our environment.


问:
How to extract month from "created_at" column and display in "Brazilian Portuguese"?
In my table, in "created_at" column:

```<code>2023-01-03 08:43:40

</code>```

In my view I am using this code to extract the date:

```<code><span>
   {{ date("F", strtotime($item->created_at)) }} de
   {{ date("Y", strtotime($item->created_at)) }}
</span>

</code>```

The result shows:

```<code>JANUARY de 2023

</code>```

Is there a way to extract this month in Brazilian Portuguese?

To show like this:

```<code>JANEIRO de 2023

</code>```

Body:
In my table, in "created_at" column:

2023-01-03 08:43:40

In my view I am using this code to extract the date:

   {{ date("F", strtotime($item->created_at)) }} de
   {{ date("Y", strtotime($item->created_at)) }}

The result shows:

JANUARY de 2023

Is there a way to extract this month in Brazilian Portuguese?

To show like this:

JANEIRO de 2023


问:
ReadExactlyAsync not cancellable?
I have a program that communicates with a device over a virtual serial port.
I am working on making it async. However, it seems, that the underlying buffer methods do not honor cancellation, as they should.

```<code>var _serialPort = new SerialPort("COM1", 19200, Parity.None);

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
cts.Token.Register(() => Console.WriteLine("Cancelled"));

var buffer = new byte[10];

_serialPort.Open();

await Task.Run(async () =>
    {
        while (!cts.IsCancellationRequested)
        {
            Console.WriteLine("Waiting for data");
            await _serialPort.BaseStream.ReadExactlyAsync(buffer, cts.Token);
            Console.WriteLine("Got data");
        }
    });

Console.WriteLine("Done");
</code>```

I got - with no data actually on the stream:

And that's it. What am I missing?

Title: ReadExactlyAsync not cancellable?

Body:
I have a program that communicates with a device over a virtual serial port.
I am working on making it async. However, it seems, that the underlying buffer methods do not honor cancellation, as they should.

var _serialPort = new SerialPort("COM1", 19200, Parity.None);

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
cts.Token.Register(() => Console.WriteLine("Cancelled"));

var buffer = new byte[10];

_serialPort.Open();

await Task.Run(async () =>
    {
        while (!cts.IsCancellationRequested)
        {
            Console.WriteLine("Waiting for data");
            await _serialPort.BaseStream.ReadExactlyAsync(buffer, cts.Token);
            Console.WriteLine("Got data");
        }
    });

Console.WriteLine("Done");

I got - with no data actually on the stream:

And that's it. What am I missing?


问:
How can you avoid display of the current font in the TinyMCE toolbar when no styling is set?
We use TinyMCE to create HTML text blocks that are included into various other contexts. Typically the styling is defined by the destination, not by the text block itself, but we still have limited font and size selection in the toolbar to allow the destination styling to be overridden if required.

In TinyMCE 4 these style toolbar items were 'unset' in the case where the styling hadn't been overridden, showing general text such as "Font".

We are now upgrading to TinyMCE 6 and the current font is always shown in the toolbar, even when no explicit styling is present in the HTML. This not only hides the case where no explicit styling is set, but it is often incorrect when no styling has been applied, as in some cases we style the size using percentages (the only valid options are 10%, 20% etc.) but TinyMCE shows the current font settings (e.g. 11px) regardless of whether they are valid or not.

Is there any way to restore the original behaviour? The current behaviour doesn't make a lot of sense for our use case.

I can't see any option that would seem to affect this behaviour.


问:
product variant array issue
Trying create a variable product variants

I am getting this array from product upload form but I want to convert it like :
{color: ["red", "blue"], size: ["M", "L"]}

how I want to convert it like this ....

[{"color":"red","size":"M"},{"color":"red","size":"L"},{"color":"blue","size":"M"},{"color":"blue","size":"L"}]

I try with this but not working

`foreach($att as $key=>$value)
{
$array[$key]  = $value;

```<code>        foreach($value as $key1=>$value1){
            $array[][$key] = $value1;
        }

        $array[][$key] = $value;
    }`
</code>```

Title: product variant array issue

Body:
Trying create a variable product variants

I am getting this array from product upload form but I want to convert it like :
{color: ["red", "blue"], size: ["M", "L"]}

how I want to convert it like this ....

[{"color":"red","size":"M"},{"color":"red","size":"L"},{"color":"blue","size":"M"},{"color":"blue","size":"L"}]

I try with this but not working

`foreach($att as $key=>$value)
{
$array[$key]  = $value;

        foreach($value as $key1=>$value1){
            $array[][$key] = $value1;
        }

        $array[][$key] = $value;
    }`


问:
dealing with promises returned from mongoose
This is probably a simple concept to some but an understanding of promises is something that I continue to struggle with...

I have a simple web app that connects to a mongo DB using mongoose and an MVC pattern. I used this tutorial to get up and running but I am not looking to build an API just a back end for my application. I believe interfacing with the controller is where I need some help understanding...

My App structure is as follows

```<code>db.congif.js - DB connection managed here
movie.model.js - this is where my object schema is defined
movie.contrller.js - this is where the db operations are written
index.js - main file for my app
</code>```

Here is the example controller

```<code>    exports.create = (req, res) => {
        // Validate request
        if (!req.body.title) {
          res.status(400).send({ message: "Content can not be empty!" });
          return;
        }

        // Create a Tutorial
        const tutorial = new Tutorial({
          title: req.body.title,
          description: req.body.description,
          published: req.body.published ? req.body.published : false
        });

        // Save Tutorial in the database
        tutorial
          .save(tutorial)
          .then(data => {
            res.send(data);
          })
          .catch(err => {
            res.status(500).send({
              message:
                err.message || "Some error occurred while creating the Tutorial."
            });
          });
      };
</code>```

I want to update this to accept an object and return a "response" here begins my lack of understanding

```<code>    exports.create = (tutorialObject) => {

    // Save Tutorial in the database
    tutorial
      .save(tutorialObject)
      .then(data => {
        return data;
      })
      .catch(err => {
          return {
          message:
            err.message || "Some error occurred while creating the Tutorial."
          };
      });
    };
</code>```

and finally how I am calling this

```<code>    let dbResponse = tutorial.create(
      {
          original_title : original_title,
          title : title,
          poster_path : poster_path
      })
</code>```

So my question... Please help me understand the correct way to code\call this. Is the controller code correct, am I calling it correctly? I am not sure because even though this is working to write records to the DB the dbResponse is always undefined.

The code works to write records to the DB but the response from the controller is undefined. I would expect to have the response be the record that was inserted?

Body:
This is probably a simple concept to some but an understanding of promises is something that I continue to struggle with...

I have a simple web app that connects to a mongo DB using mongoose and an MVC pattern. I used this tutorial to get up and running but I am not looking to build an API just a back end for my application. I believe interfacing with the controller is where I need some help understanding...

My App structure is as follows

db.congif.js - DB connection managed here
movie.model.js - this is where my object schema is defined
movie.contrller.js - this is where the db operations are written
index.js - main file for my app

Here is the example controller

    exports.create = (req, res) => {
        // Validate request
        if (!req.body.title) {
          res.status(400).send({ message: "Content can not be empty!" });
          return;
        }

        // Create a Tutorial
        const tutorial = new Tutorial({
          title: req.body.title,
          description: req.body.description,
          published: req.body.published ? req.body.published : false
        });

        // Save Tutorial in the database
        tutorial
          .save(tutorial)
          .then(data => {
            res.send(data);
          })
          .catch(err => {
            res.status(500).send({
              message:
                err.message || "Some error occurred while creating the Tutorial."
            });
          });
      };

I want to update this to accept an object and return a "response" here begins my lack of understanding

    exports.create = (tutorialObject) => {

    // Save Tutorial in the database
    tutorial
      .save(tutorialObject)
      .then(data => {
        return data;
      })
      .catch(err => {
          return {
          message:
            err.message || "Some error occurred while creating the Tutorial."
          };
      });
    };

and finally how I am calling this

    let dbResponse = tutorial.create(
      {
          original_title : original_title,
          title : title,
          poster_path : poster_path
      })

So my question... Please help me understand the correct way to code\call this. Is the controller code correct, am I calling it correctly? I am not sure because even though this is working to write records to the DB the dbResponse is always undefined.

The code works to write records to the DB but the response from the controller is undefined. I would expect to have the response be the record that was inserted?


问:
why is the variable not changing from upper to lower case in the data frame in r but it changed in the console?
To easily call functions in R i changed all variable names from upper case (WorldwideBox Ofice)  to lower case (worldwidebox office) and replaced all spaces with an underscore (worldwidebox_office) while the code successfully ran in the console the variable names have however remained the same in the data frame.[enter image description here]

this is the code i used to make the change

```<code>#data cleaning and manipulation-  substitute space in variable with underscore
#change variable names to lower case

names(film) <- gsub(' ','_',names(film))
names(film) <- tolower(names(film))
names(film)
</code>```

I was expecting something like this in the data frame:

```<code>rank, year, movie, worldwidebox_office, domesticbox_office, internationalbox_office
</code>```

But this what i got (https://i.stack.imgur.com/p18I8.png)

THANK YOU IN ADVANCE.

Body:
To easily call functions in R i changed all variable names from upper case (WorldwideBox Ofice)  to lower case (worldwidebox office) and replaced all spaces with an underscore (worldwidebox_office) while the code successfully ran in the console the variable names have however remained the same in the data frame.[enter image description here]

this is the code i used to make the change

#data cleaning and manipulation-  substitute space in variable with underscore
#change variable names to lower case

names(film) <- gsub(' ','_',names(film))
names(film) <- tolower(names(film))
names(film)

I was expecting something like this in the data frame:

rank, year, movie, worldwidebox_office, domesticbox_office, internationalbox_office

But this what i got (https://i.stack.imgur.com/p18I8.png)

THANK YOU IN ADVANCE.


问:
Og:Image not showing on Github Pages
I'm hosting via github pages, and using a google DNS, the link would be:

https://thiagosaud.dev

However, the og:image is not being displayed either locally, or on github.io or in DNS.

What is wrong?

```<code>const getHtmlWebPackPluginOptions = (filename, templateName) => ({
    minify: true,
    cache: true,
    filename,
    template: path.resolve(__dirname, templateName),
    favicon: 'src/assets/imgs/favicon.ico',
    meta: {
        viewport: 'width=device-width, initial-scale=1',
        author: PackageJSON.author.name,
        description: PackageJSON.description,
        keywords: `${PackageJSON.keywords}`,
        robots: 'index, follow',
        'og:locale': 'en_US',
        'og:type': 'website',
        'og:url': 'https://www.thiagosaud.dev',
        'og:title': 'THIAGO SAUD - FRONTEND',
        'og:site_name': 'THIAGO SAUD - FRONTEND',
        'og:description': PackageJSON.description,
        'og:image': 'https://raw.githubusercontent.com/thiagosaud/thiagosaud.github.io/main/temp/imgs/social-preview.png',
        'theme-color': '#171717',
        'msapplication-TileColor': '#171717',
    },
});
</code>```

Title: Og:Image not showing on Github Pages

Body:
I'm hosting via github pages, and using a google DNS, the link would be:

https://thiagosaud.dev

However, the og:image is not being displayed either locally, or on github.io or in DNS.

What is wrong?

const getHtmlWebPackPluginOptions = (filename, templateName) => ({
    minify: true,
    cache: true,
    filename,
    template: path.resolve(__dirname, templateName),
    favicon: 'src/assets/imgs/favicon.ico',
    meta: {
        viewport: 'width=device-width, initial-scale=1',
        author: PackageJSON.author.name,
        description: PackageJSON.description,
        keywords: `${PackageJSON.keywords}`,
        robots: 'index, follow',
        'og:locale': 'en_US',
        'og:type': 'website',
        'og:url': 'https://www.thiagosaud.dev',
        'og:title': 'THIAGO SAUD - FRONTEND',
        'og:site_name': 'THIAGO SAUD - FRONTEND',
        'og:description': PackageJSON.description,
        'og:image': 'https://raw.githubusercontent.com/thiagosaud/thiagosaud.github.io/main/temp/imgs/social-preview.png',
        'theme-color': '#171717',
        'msapplication-TileColor': '#171717',
    },
});


问:
Ingesting json message into even hub by using python
I am trying to ingest the json message into AZURE Event Hub
My problem is size of json message since Event hub has a limit of 1MB
I have one big json message which consists of multiple json message

```<code>DATA = [{"Id": "393092", "UID": "7f0034ee", "date": "2023-01-06", "f_id": "430", "origin": "CN"}, {"Id": "393092", "UID": "7f0034ee", "date": "2023-01-06", "f_id": "430", "origin": "CN"}, {"Id": "393092", "UID": "7f0034ee", "date": "2023-01-06", "f_id": "430", "origin": "CN"}]
</code>```

This Data is an example.
DATA is already in json format but DATA contains 10000+ json event with same format
I would like to ingest this json message into event hub

Can anyone help me out How can I ingest this one big message into event hub? by slicing it or some other way

Thanks a lot !

Yoonsik

I tried slicing it but the number of events within one json message always different and very big...

Body:
I am trying to ingest the json message into AZURE Event Hub
My problem is size of json message since Event hub has a limit of 1MB
I have one big json message which consists of multiple json message

DATA = [{"Id": "393092", "UID": "7f0034ee", "date": "2023-01-06", "f_id": "430", "origin": "CN"}, {"Id": "393092", "UID": "7f0034ee", "date": "2023-01-06", "f_id": "430", "origin": "CN"}, {"Id": "393092", "UID": "7f0034ee", "date": "2023-01-06", "f_id": "430", "origin": "CN"}]

This Data is an example.
DATA is already in json format but DATA contains 10000+ json event with same format
I would like to ingest this json message into event hub

Can anyone help me out How can I ingest this one big message into event hub? by slicing it or some other way

Thanks a lot !

Yoonsik

I tried slicing it but the number of events within one json message always different and very big...


问:
Failed to mount volume with Singlestore "cluster-in-a-box" Docker image
I'm using the 'singlestore/cluster-in-a-box:latest' image and trying to map the singlestore data to my host machine (windows), in a custom location, but no luck so far.

I've tried as I do it in any other container:

```<code>    volumes:
    - ./data/singlestore-data:/var/lib/memsql
</code>```

but this gives me the following errors when I run it:

singlestoreissue  | ✓ Set up runtime environment
singlestoreissue  | Starting Memsql nodes
singlestoreissue  | ✘ Failed to start node with node ID 9DA037A1695B23997F48D58E5098A1B88F108D47 (1/2)
singlestoreissue  | Starting nodes
singlestoreissue  | ✘ Failed to start node with node ID F395C09DFE9841A27B18DF7F1FC5B9DD27DEB389 (2/2)
singlestoreissue  | Starting nodes
singlestoreissue  | ✓ Started 0 nodes
singlestoreissue  | Latest errors from the database's tracelog:
singlestoreissue  |
singlestoreissue  | : Failed to connect to the database: process exited: exit status 255
singlestoreissue exited with code 1

I've also tried other ways:

```<code>    volumes:
    - singlestore-data:/var/lib/memsql
....
volumes:
  singlestore-data:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: ./data/singlestore-data

</code>```

Error response from daemon: failed to mount local volume: mount data/singlestore-data:/var/lib/docker/volumes/singlestoreissue2_singlestore-data/_data, flags: 0x1000: no such file or directory

```<code>    volumes:
    - singlestore-data:/var/lib/memsql
....
volumes:
  singlestore-data:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: ${PWD}/data/singlestore-data

</code>```

time="2023-01-11T16:29:34Z" level=warning msg="The "PWD" variable is not set. Defaulting to a blank string."
Running 0/0
Container singlestoreneat  Creating                                                                             0.1s
Error response from daemon: failed to mount local volume: mount data/singlestore-data:/var/lib/docker/volumes/singlestoreissue2_singlestore-data/_data, flags: 0x1000: no such file or directory

Am I missing something here?

Body:
I'm using the 'singlestore/cluster-in-a-box:latest' image and trying to map the singlestore data to my host machine (windows), in a custom location, but no luck so far.

I've tried as I do it in any other container:

    volumes:
    - ./data/singlestore-data:/var/lib/memsql

but this gives me the following errors when I run it:

singlestoreissue  | ✓ Set up runtime environment
singlestoreissue  | Starting Memsql nodes
singlestoreissue  | ✘ Failed to start node with node ID 9DA037A1695B23997F48D58E5098A1B88F108D47 (1/2)
singlestoreissue  | Starting nodes
singlestoreissue  | ✘ Failed to start node with node ID F395C09DFE9841A27B18DF7F1FC5B9DD27DEB389 (2/2)
singlestoreissue  | Starting nodes
singlestoreissue  | ✓ Started 0 nodes
singlestoreissue  | Latest errors from the database's tracelog:
singlestoreissue  |
singlestoreissue  | : Failed to connect to the database: process exited: exit status 255
singlestoreissue exited with code 1

I've also tried other ways:

    volumes:
    - singlestore-data:/var/lib/memsql
....
volumes:
  singlestore-data:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: ./data/singlestore-data

Error response from daemon: failed to mount local volume: mount data/singlestore-data:/var/lib/docker/volumes/singlestoreissue2_singlestore-data/_data, flags: 0x1000: no such file or directory

    volumes:
    - singlestore-data:/var/lib/memsql
....
volumes:
  singlestore-data:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: ${PWD}/data/singlestore-data

time="2023-01-11T16:29:34Z" level=warning msg="The "PWD" variable is not set. Defaulting to a blank string."
Running 0/0
Container singlestoreneat  Creating                                                                             0.1s
Error response from daemon: failed to mount local volume: mount data/singlestore-data:/var/lib/docker/volumes/singlestoreissue2_singlestore-data/_data, flags: 0x1000: no such file or directory

Am I missing something here?


问:
How to throw exception from EventHubConsumerAsyncClient - Azure Messaging Hubs
I was referring to: https://learn.microsoft.com/en-us/java/api/com.azure.messaging.eventhubs.eventhubconsumerasyncclient?view=azure-java-stable, how

can we throw the exception and add Junit test case for it?

```<code>// Receives events from all partitions from the beginning of each partition.
 consumer.receive(true).subscribe(partitionEvent -> {
     PartitionContext context = partitionEvent.getPartitionContext();
     EventData event = partitionEvent.getData();
     System.out.printf("Event %s is from partition %s%n.", event.getSequenceNumber(), context.getPartitionId());
 }, error -> System.err.print(error.toString()));
</code>```

Body:
I was referring to: https://learn.microsoft.com/en-us/java/api/com.azure.messaging.eventhubs.eventhubconsumerasyncclient?view=azure-java-stable, how

can we throw the exception and add Junit test case for it?

// Receives events from all partitions from the beginning of each partition.
 consumer.receive(true).subscribe(partitionEvent -> {
     PartitionContext context = partitionEvent.getPartitionContext();
     EventData event = partitionEvent.getData();
     System.out.printf("Event %s is from partition %s%n.", event.getSequenceNumber(), context.getPartitionId());
 }, error -> System.err.print(error.toString()));


问:
How to fix the IDs renaming problem while using View Binding in android studio?
The problem is that when I rename the id of any view like a button in the xml file, the name of the view doesn't get updated in the activity while using view binding.

When I rename the id, I use (refactor) or (shift+f6).

This is a big problem because when ever I rename an id in the XML file, it will break the code in the activity in case I'm using View Binding.

Example:-

```<code> <Button
    android:id="@+id/Button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</code>```

when I change Button1 to Button2, the code breaks in the activity in case I'm using View binding.

Can anyone give me any way to properly rename the IDs so that the names in the activity get updated automatically while using View Binding.

Please, remember I do use (refactor) not f2.

If you agree with me that this is a very urging problem and it breaks our code, please vote this question up, so it will be suggested to more android developers. Maybe some already found a solution.

Body:
The problem is that when I rename the id of any view like a button in the xml file, the name of the view doesn't get updated in the activity while using view binding.

When I rename the id, I use (refactor) or (shift+f6).

This is a big problem because when ever I rename an id in the XML file, it will break the code in the activity in case I'm using View Binding.

Example:-

 <Button
    android:id="@+id/Button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

when I change Button1 to Button2, the code breaks in the activity in case I'm using View binding.

Can anyone give me any way to properly rename the IDs so that the names in the activity get updated automatically while using View Binding.

Please, remember I do use (refactor) not f2.

If you agree with me that this is a very urging problem and it breaks our code, please vote this question up, so it will be suggested to more android developers. Maybe some already found a solution.


问:
Run GitHub workflow from non-gradle project
I have a non-gradle root project which should launch child gh action, but can’t figure out how to. File child.yml should generate apk artifact, since android/ dir is app directory.

Project structure:

```<code>root
    |
     --- .github/workflows/root.yml
     --- android/
                |
                 ___ .github/actions/apk/child.yml
</code>```

Closest I get was running a yaml on root level:

root.yml

name: use my action
on:
  push:
    branches:
      - ci_test
jobs:
  #Build job
  test_build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout the code
        uses: actions/checkout@v2
      - uses: ./android/.github/actions/apk
```
<p><em>child.yml</em></p>
<pre class="lang-yaml prettyprint-override"><code>name: Build of dev branch
on:
    push:
        branches:
        - develop
jobs:

  #Build job
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout the code
        uses: actions/checkout@v2

      - uses: actions/cache@v2
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
          key: ${{ runner.os }}-${{ hashFiles('**/*.gradle*') }}-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }}-${{ hashFiles('**/buildSrc/**/*.kt') }}

      - name: Set up JDK 11
        uses: actions/setup-java@v1
        with:
          java-version: '11'

      - name: Change wrapper permissions
        run: chmod +x ./gradlew
      - name: Build the app
        run: ./gradlew assembleDebug

      - name: Upload apk
        uses: actions/upload-artifact@v2
        with:
          name: debug apk
          path: ./app/build/outputs/apk/debug/app-debug.apk
</code>```

But I get an error with doubled "/my-root-dir/my-root-dir"

Can't find 'action.yml', 'action.yaml' or 'Dockerfile' under '/home/runner/work/my-root-dir/my-root-dir/android/.github/actions/child.yaml'. Did you forget to run actions/checkout before running your local action?

Body:
I have a non-gradle root project which should launch child gh action, but can’t figure out how to. File child.yml should generate apk artifact, since android/ dir is app directory.

Project structure:

root
    |
     --- .github/workflows/root.yml
     --- android/
                |
                 ___ .github/actions/apk/child.yml

Closest I get was running a yaml on root level:

root.yml

name: use my action
on:
  push:
    branches:
      - ci_test
jobs:
  #Build job
  test_build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout the code
        uses: actions/checkout@v2
      - uses: ./android/.github/actions/apk

child.yml

name: Build of dev branch
on:
    push:
        branches:
        - develop
jobs:

  #Build job
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout the code
        uses: actions/checkout@v2

      - uses: actions/cache@v2
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
          key: ${{ runner.os }}-${{ hashFiles('**/*.gradle*') }}-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }}-${{ hashFiles('**/buildSrc/**/*.kt') }}

      - name: Set up JDK 11
        uses: actions/setup-java@v1
        with:
          java-version: '11'

      - name: Change wrapper permissions
        run: chmod +x ./gradlew
      - name: Build the app
        run: ./gradlew assembleDebug

      - name: Upload apk
        uses: actions/upload-artifact@v2
        with:
          name: debug apk
          path: ./app/build/outputs/apk/debug/app-debug.apk

But I get an error with doubled "/my-root-dir/my-root-dir"

Can't find 'action.yml', 'action.yaml' or 'Dockerfile' under '/home/runner/work/my-root-dir/my-root-dir/android/.github/actions/child.yaml'. Did you forget to run actions/checkout before running your local action?


问:
libtorch: Is writing to non-overlapping slices of a torch::Tensor from different threads safe when using index_put_ method?
I want to write to different non-overlapping slices of a torch::Tensor object by calling libtorch's index_put_ method from different threads concurrently, i.e. each thread writes to a different part of the tensor. Is this safe without any synchronization (i.e. mutexes)? I cannot find any related documentation.


问:
how to require modules in electron
I tried to require some modules to be used in my electron app (using electron 22.0.0). However, I am receiving an error: "require" is not defined. The thing is, I've tried many different ways to require my modules:

-putting my function, along with requiring the needed modules

-setting node integration as true

-tried using import, which obviously didn't work

-creating a preload file

Unfortunately, none of these worked. If I'm doing anything wrong, please let me know.

My code:

main.js:

```<code>const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    minWidth: 640,
    width: 1280,
    minHeight: 480,
    height: 720,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
  });

  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  ipcMain.on('min', () => {
    mainWindow.minimize()
  })

  ipcMain.on('max', () => {
    mainWindow.isMaximized() ? mainWindow.unmaximize() : mainWindow.maximize()
  })
};

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});
</code>```

index.html:

```<code><html><head>
    <title>Javascript Function</title>
    </head>
    <body>
        <div id="button"><button>Click</button></div>
    <script>
    var AudioContext = require("web-audio-api").AudioContext;
    var MusicTempo = require("music-tempo");
    const fs = require('fs')
    const getMP3Duration = require('get-mp3-duration')
    const zlib = require('zlib')
    const bclick = document.getElementById('button')
    bclick.addEventListener('click', function() {
        console.log("e")
        function xor(str, key) {
        str = String(str).split('').map(letter => letter.charCodeAt());
        let res = "";
        for (let i = 0; i < str.length; i++) res += String.fromCodePoint(str[i] ^ key);
        return res;
    }

    function decode(data){
        console.log("Decoding...")
        if (data.startsWith('<?xml version="1.0"?>')) return data
        let decoded = xor(data, 11)
        decoded = Buffer.from(decoded, 'base64')
        try { return zlib.unzipSync(decoded).toString() }
        catch (e) { return console.log("Error! GD save file seems to be corrupt!") }
    }

let oldDate = new Date()

console.log('Initialised program')
console.log('Reading CCLocalLevels.dat')

let gdSave = process.env.HOME || process.env.USERPROFILE + "/AppData/Local/GeometryDash/CCLocalLevels.dat"

fs.readFile(gdSave, 'utf8', function (err, saveData) {
    if (err) return console.log("Could not open or find GD save file")
    let decoded = decode(saveData)
    if (!decoded) return
    fs.writeFileSync('CCLocalLevels.xml', decoded, 'utf8')
    console.log(`Decoded save file and written to CCLocalLevels.xml`)
    var xml = fs.readFileSync('CCLocalLevels.xml')

    console.log(xml)
    xml = xml.toString()

    console.log('Extracting created levels')

    let parsed = xml.match(/<k>LLM_01<\/k><d><k>_isArr<\/k><t \/>(.+)<\/d><k>LLM_02<\/k><i>35<\/i>/)
    parsed = parsed[1].match(/<k>k45<\/k><i>(\d+)<\/i>/g)

    console.log('Extracted songs from created levels and saved them to CClocalLevels.json')

    fs.writeFileSync('CCLocalLevels.json', JSON.stringify(parsed, null, 4))
    sav()
})

// find bpm
function sav() {

    findBPM()
    console.log(`\n${new Date() - oldDate}ms elapsed`)
    // add bpm to text file

    let colors = {o: 0.8, y: 0.9, g: 1.0}
    let gdLevels = process.env.HOME || process.env.USERPROFILE + "/AppData/Local/GeometryDash/CCLocalLevels.dat"
    let levelRegex = /(<k>k_0<\/k>.+?<k>k4<\/k><s>)(.+?)<\/s>/

    let localLevels = fs.readFileSync(gdLevels, 'utf8')
    console.log("Reading save...")

    if (!localLevels.startsWith('<?xml version="1.0"?>')) {
        function xor(str, key) {
            str = String(str).split('').map(letter => letter.charCodeAt());
            let res = "";
            for (i = 0; i < str.length; i++) res += String.fromCodePoint(str[i] ^ key);
            return res;
        }
        localLevels = xor(localLevels, 11)
        localLevels = Buffer.from(localLevels, 'base64')
        try { localLevels = zlib.unzipSync(localLevels).toString() }
        catch(e) { return console.log("Error! GD save file seems to be corrupt!") }
    }

    console.log("Parsing level data...")
    let foundLevel = localLevels.match(levelRegex)
    let foundData = foundLevel[2]
    let levelData = foundData.startsWith('kS38') ? foundData : zlib.unzipSync(Buffer.from(foundData, 'base64')).toString()
    levelData = levelData.replace(/kA14,.*?,/, "")  // clear old guidelined
    let guidelines = ""

    console.log("Adding guidelines...")
    let config = fs.readFileSync('./settings.txt', 'utf8').split("\n").map(x => x.replace(/\s/g, "").split(":")[1])
    let [BPM, songLength, offset, pattern] = config
    BPM = parseInt(fs.readFileSync('./tempo.json'))
    songLength = parseInt(fs.readFileSync('./duration.json'))

    pattern = pattern.toLowerCase().split("")
    let beatsPerBar = pattern.length
    let secondsPerBeat = Math.abs(60 / (+BPM || 100))

    let beatCount = 0
    let secs = (+offset || 0) / 1000

    while (secs <= (+songLength || 150)) {
        let beat = pattern[beatCount % beatsPerBar]
        if (colors[beat]) guidelines += `${Number(secs.toFixed(5))}~${colors[beat]}~`
        beatCount++
        secs += secondsPerBeat
    }

    console.log("Saving level...")
    let newData = levelData.replace(",kA6,", `,kA14,${guidelines.slice(0, -1)},kA6,`)
    let newLevels = localLevels.replace(levelRegex, `$1${newData}</s>`)
    fs.writeFileSync(gdLevels, newLevels, 'utf8')
    console.log("Saved!")
 }

function findBPM() {
    let rawdata = fs.readFileSync('CCLocalLevels.json');
    let songID = JSON.parse(rawdata)[0];
    songID = songID.toString()
    let songID2 =  songID.replace("<k>k45</k><i>", "")
    let songID3 = songID2.replace("</i>", "")
    songID3 += ".mp3"
    console.log(songID3);
    const buffer = fs.readFileSync(process.env.HOME || process.env.USERPROFILE + `/AppData/Local/GeometryDash/${songID3}`)
    const duration = getMP3Duration(buffer)
    let duras = duration/1000
    duras = Math.round(duras)
    fs.writeFileSync('./duration.json', JSON.stringify(duras, null, 4))

    var calcTempo = function (buffer) {
    var audioData = [];
    // Take the average of the two channels
    if (buffer.numberOfChannels == 2) {
    var channel1Data = buffer.getChannelData(0);
    var channel2Data = buffer.getChannelData(1);
    var length = channel1Data.length;
    for (var i = 0; i < length; i++) {
    audioData[i] = (channel1Data[i] + channel2Data[i]) / 2;
    }
    } else {
    audioData = buffer.getChannelData(0);
    }
    var mt = new MusicTempo(audioData);
    console.log(mt.tempo);
    jn = Math.round(mt.tempo)
    fs.writeFileSync('tempo.json', JSON.stringify(jn, null, 4))
    console.log(mt.beats);

    }

    console.log(duras)

    var data = fs.readFileSync(`${process.env.LOCALAPPDATA}\\GeometryDash\\${songID3}`);
    var context = new AudioContext();
    context.decodeAudioData(data, calcTempo);
 }
    })
    </script>
    </body></html>
</code>```

package.json:

```<code>{
  "name": "app",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "electron": "^22.0.0"
  },
  "dependencies": {}
}
</code>```

Thank you.

Title: how to require modules in electron

Body:
I tried to require some modules to be used in my electron app (using electron 22.0.0). However, I am receiving an error: "require" is not defined. The thing is, I've tried many different ways to require my modules:

-putting my function, along with requiring the needed modules

-setting node integration as true

-tried using import, which obviously didn't work

-creating a preload file

Unfortunately, none of these worked. If I'm doing anything wrong, please let me know.

My code:

main.js:

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    minWidth: 640,
    width: 1280,
    minHeight: 480,
    height: 720,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
  });

  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  ipcMain.on('min', () => {
    mainWindow.minimize()
  })

  ipcMain.on('max', () => {
    mainWindow.isMaximized() ? mainWindow.unmaximize() : mainWindow.maximize()
  })
};

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

index.html:

    <title>Javascript Function</title>

<button>Click</button>

package.json:

{
  "name": "app",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "electron": "^22.0.0"
  },
  "dependencies": {}
}

Thank you.


问:
Extract table from a PDF with multiple headers (R)
I am trying to get some epidemiological data stored in a pdf that is publicly available
link.
I am just looking at the data in page 9 (right table).

What I would like to achieve is to pass the data into a table, but since I have many headers, it's quite dificult to achieve this. Example: The column SIDA is divided in two further columns (SEM and ACUM). Would it be possible to split the SIDA cell?

So far I have tried to extract the data using pdftools and tabulizer.


问:
Two similar UPDATE statements in Redshift, one throws an error but the other doesn't
I have been working on converting some SQL scripts from T-SQL to Redshift and came across this error a few times: Error: Target table must be part of an equijoin predicate wit UPDATE statements using JOINs.

There are several questions on SO about this problem and I was able to use them to fix my UPDATE statements by using subqueries. (This question and this question specifically)

I thought I had this all figured out until just now when I was able to execute an UPDATE statement similar to the ones I was getting errors for without issue. I want to understand what is going on here so I can be better at writing queries for Redshift.

Here is an example of one of the UPDATE statements that threw the above error:

UPDATE billing_temp
SET spotlink = sl.spotlink
FROM billing_temp AS bt
LEFT JOIN spot_link AS sl
    ON bt.dupeid = sl.dupeid;
```
<p>And here is the UPDATE statement that is working without any changes:</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE public.billingcombined
SET revenue_type = r.revenue_type
FROM public.billingcombined AS b
JOIN public.revenuetype AS r
    ON b.contract_number = r.contract_number;
</code>```

These look exactly the same to me. The only difference I can see is that the first one is using two temporary tables, but I wouldn't think this would cause an issue.

EDIT: I just saw the LEFT JOIN in the first query vs the JOIN in the second. Is this the reason the second query works?

EDIT2: After trying another UPDATE statement with a JOIN rather than a LEFT JOIN I was able to confirm that using a JOIN allows it to run without error.

For reference, here is how I had to correct the first query to run without errors based on what I learned from the linked SO questions:

UPDATE billing_temp
SET spotlink = btsl.spotlink
FROM
(
    SELECT bt.dupeid,
           sl.spotlink
    FROM billing_temp AS bt
    LEFT JOIN spot_link AS sl
        ON bt.dupeid = sl.dupeid
) AS btsl
WHERE billing_temp.dupeid = btsl.dupeid;
```

The answers say the problem is you can't use the table getting updated directly in the FROM clause. But now that doesn't seem to be the case for my second UPDATE statement.

Body:
I have been working on converting some SQL scripts from T-SQL to Redshift and came across this error a few times: Error: Target table must be part of an equijoin predicate wit UPDATE statements using JOINs.

There are several questions on SO about this problem and I was able to use them to fix my UPDATE statements by using subqueries. (This question and this question specifically)

I thought I had this all figured out until just now when I was able to execute an UPDATE statement similar to the ones I was getting errors for without issue. I want to understand what is going on here so I can be better at writing queries for Redshift.

Here is an example of one of the UPDATE statements that threw the above error:

UPDATE billing_temp
SET spotlink = sl.spotlink
FROM billing_temp AS bt
LEFT JOIN spot_link AS sl
    ON bt.dupeid = sl.dupeid;

And here is the UPDATE statement that is working without any changes:

UPDATE public.billingcombined
SET revenue_type = r.revenue_type
FROM public.billingcombined AS b
JOIN public.revenuetype AS r
    ON b.contract_number = r.contract_number;

These look exactly the same to me. The only difference I can see is that the first one is using two temporary tables, but I wouldn't think this would cause an issue.

EDIT: I just saw the LEFT JOIN in the first query vs the JOIN in the second. Is this the reason the second query works?

EDIT2: After trying another UPDATE statement with a JOIN rather than a LEFT JOIN I was able to confirm that using a JOIN allows it to run without error.

For reference, here is how I had to correct the first query to run without errors based on what I learned from the linked SO questions:

UPDATE billing_temp
SET spotlink = btsl.spotlink
FROM
(
    SELECT bt.dupeid,
           sl.spotlink
    FROM billing_temp AS bt
    LEFT JOIN spot_link AS sl
        ON bt.dupeid = sl.dupeid
) AS btsl
WHERE billing_temp.dupeid = btsl.dupeid;

The answers say the problem is you can't use the table getting updated directly in the FROM clause. But now that doesn't seem to be the case for my second UPDATE statement.


问:
How to stop 2 digit numbers going to 00?
Making a cookie clicker I encountered some problems including the title. Here is my code:

```<code>
#imports

from getkey import getkey

#variables/strings/int whatever they're called

money = 0

cookies = 0

#loop

while True:

    print(f"{cookies}\n${money}\n\n[1]offer1: {offer1}")

    click = getkey()

    if click == "\n":

        cookies += 1

    if click == "1":

        for cookies in range(cookies):

            money += offer1

</code>```

If cookies are sold to offer1 and it has 2 or more digits, it will show 2 numbers that may or may not be 00 or 0 (random num)

Does anyone have any idea to fix this?

Body:
Making a cookie clicker I encountered some problems including the title. Here is my code:

#imports

from getkey import getkey

#variables/strings/int whatever they're called

money = 0

cookies = 0

#loop

while True:

    print(f"{cookies}\n${money}\n\n[1]offer1: {offer1}")

    click = getkey()

    if click == "\n":

        cookies += 1

    if click == "1":

        for cookies in range(cookies):

            money += offer1

If cookies are sold to offer1 and it has 2 or more digits, it will show 2 numbers that may or may not be 00 or 0 (random num)

Does anyone have any idea to fix this?


问:
Can Xcode Cloud trigger a PR build from a fork?
Xcode Cloud's PR start conditions is great - But what about PRs that are coming from a fork.  Not surprisingly I'm getting an error when XCC tries to checkout the source branch:

fatal: couldn't find remote ref BRANCH_NAME

Is there an easy way around this that doesn't include pushing those branches to upstream first?


问:
How do I make my function "def Button1_command(self):" correct?
```<code># -*- coding: utf-8 -*-

import tkinter as tk
from tkinter import messagebox
import tkinter.font as tkFont

class App:
    def __init__(self, root):
        #setting title
        root.title("")
        #setting window size
        width=800
        height=600
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        Label1=tk.Label(root)
        ft = tkFont.Font(family='Arial',size=10)
        Label1["font"] = ft
        Label1["fg"] = "#333333"
        Label1["justify"] = "left"
        Label1["text"] = "Id del Cambio*+"
        Label1.place(x=20,y=20,width=100,height=25)

        Entry1=tk.Entry(root)
        Entry1["borderwidth"] = "1px"
        ft = tkFont.Font(family='Arial',size=10)
        Entry1["font"] = ft
        Entry1["fg"] = "#333333"
        Entry1["justify"] = "left"
        Entry1["text"] = ""
        Entry1.place(x=130,y=20,width=100,height=25)

        Button1=tk.Button(root)
        Button1["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Arial',size=10)
        Button1["font"] = ft
        Button1["fg"] = "#000000"
        Button1["justify"] = "center"
        Button1["text"] = "Agregar"
        Button1.place(x=20,y=170,width=750,height=25)
        Button1["command"] = self.Button1_command

        Button2=tk.Button(root)
        Button2["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Arial',size=10)
        Button2["font"] = ft
        Button2["fg"] = "#000000"
        Button2["justify"] = "center"
        Button2["text"] = "Procesar"
        Button2.place(x=20,y=445,width=750,height=25)
        Button2["command"] = self.Button2_command

    def Button1_command(self):
        Entry1.focus()
        Entry1.delete(0, 'end')

    def Button2_command(self):
        messagebox.showinfo(message="Procesamiento terminado", title="Mensaje")

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()
</code>```
```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\\Python\\lib\\tkinter\\\__init_\_.py", line 1892, in \__call_\_
    return self.func(\*args)
  File "D:\\OKY\\Documents\\NetBeansProjects\\PythonTest\\src\\main.py", line 135, in Button1_command
    Entry1.focus()
NameError: name 'Entry1' is not defined
</code>```

Body:
# -*- coding: utf-8 -*-

import tkinter as tk
from tkinter import messagebox
import tkinter.font as tkFont

class App:
    def __init__(self, root):
        #setting title
        root.title("")
        #setting window size
        width=800
        height=600
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        Label1=tk.Label(root)
        ft = tkFont.Font(family='Arial',size=10)
        Label1["font"] = ft
        Label1["fg"] = "#333333"
        Label1["justify"] = "left"
        Label1["text"] = "Id del Cambio*+"
        Label1.place(x=20,y=20,width=100,height=25)

        Entry1=tk.Entry(root)
        Entry1["borderwidth"] = "1px"
        ft = tkFont.Font(family='Arial',size=10)
        Entry1["font"] = ft
        Entry1["fg"] = "#333333"
        Entry1["justify"] = "left"
        Entry1["text"] = ""
        Entry1.place(x=130,y=20,width=100,height=25)

        Button1=tk.Button(root)
        Button1["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Arial',size=10)
        Button1["font"] = ft
        Button1["fg"] = "#000000"
        Button1["justify"] = "center"
        Button1["text"] = "Agregar"
        Button1.place(x=20,y=170,width=750,height=25)
        Button1["command"] = self.Button1_command

        Button2=tk.Button(root)
        Button2["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Arial',size=10)
        Button2["font"] = ft
        Button2["fg"] = "#000000"
        Button2["justify"] = "center"
        Button2["text"] = "Procesar"
        Button2.place(x=20,y=445,width=750,height=25)
        Button2["command"] = self.Button2_command

    def Button1_command(self):
        Entry1.focus()
        Entry1.delete(0, 'end')

    def Button2_command(self):
        messagebox.showinfo(message="Procesamiento terminado", title="Mensaje")

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\\Python\\lib\\tkinter\\\__init_\_.py", line 1892, in \__call_\_
    return self.func(\*args)
  File "D:\\OKY\\Documents\\NetBeansProjects\\PythonTest\\src\\main.py", line 135, in Button1_command
    Entry1.focus()
NameError: name 'Entry1' is not defined


问:
I am trying to create an error bar on only one point in my graph?
I am trying to create an error bar on only one point (132, 172) in my graph, because it's the only one that matters for what I'm trying to show. I am not sure how to make it so that that is the only error bar that shows. Here's my regular code with traditional error bar:

```<code>ggplot(weather_data, aes(x = snow.melt.date, y = Speyeria.atalantis)) +
 geom_errorbar(aes(ymin=Speyeria.atalantis-12.09, ymax=Speyeria.atalantis + 12.09), width=.2, position=position_dodge(0.05)) +
geom_point(color = "grey35") +
geom_point(aes(x=132, y=172), colour="#00AFBB", shape = 17, size = 2.5) +
geom_point(aes(x=132, y=176), colour="#FFDB6D") +
stat_smooth(method = "lm", formula = y ~ x, geom = "smooth", color = "steelblue4", se=FALSE) +
theme_minimal() +labs(x="Snowmelt Date", y="Emergence Date") +
  stat_regline_equation(label.y = 150.0, aes(label = ..eq.label..) ) +
ggtitle("Speyeria atalantis")
</code>```

Any thoughts?

I could find no info on this problem so I haven't tried much. I considered grouping my data and then plotting by group? I tried putting arrows on the graph point instead of error bars but it wasn't the same.

Body:
I am trying to create an error bar on only one point (132, 172) in my graph, because it's the only one that matters for what I'm trying to show. I am not sure how to make it so that that is the only error bar that shows. Here's my regular code with traditional error bar:

ggplot(weather_data, aes(x = snow.melt.date, y = Speyeria.atalantis)) +
 geom_errorbar(aes(ymin=Speyeria.atalantis-12.09, ymax=Speyeria.atalantis + 12.09), width=.2, position=position_dodge(0.05)) +
geom_point(color = "grey35") +
geom_point(aes(x=132, y=172), colour="#00AFBB", shape = 17, size = 2.5) +
geom_point(aes(x=132, y=176), colour="#FFDB6D") +
stat_smooth(method = "lm", formula = y ~ x, geom = "smooth", color = "steelblue4", se=FALSE) +
theme_minimal() +labs(x="Snowmelt Date", y="Emergence Date") +
  stat_regline_equation(label.y = 150.0, aes(label = ..eq.label..) ) +
ggtitle("Speyeria atalantis")

Any thoughts?

I could find no info on this problem so I haven't tried much. I considered grouping my data and then plotting by group? I tried putting arrows on the graph point instead of error bars but it wasn't the same.


问:
Need help ending a program with a do while loop
I am creating a wordle project, where the word is set to "tyler". The user's guess is saved as a string, as is the wordle word, "tyler". Both the strings are saved as characters in an array, then the program checks whether each character in the arrays match.
My code is here:

```<code>
// Nelson's work
import java.util.Scanner;

class FinalProject {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        // Nelson's work
        int counter = 0;
        do {
            String word = "tyler";
            System.out.println("Press enter to begin");
            // Saves userInput as a string
            String userInput = input.nextLine();
            while (userInput.length() != 5) {
                System.out.println("Enter a 5 letter word: ");
                userInput = input.nextLine();
                counter++;
            }
            // End of Nelson's work
            // Tyler's work
            // Creates an array of length equal to string length
            char[] ch = new char[userInput.length()];

            // For loop to put characters into array
            for (int i = 0; i < userInput.length(); i++) {
                ch[i] = userInput.charAt(i);
            }
            // 'For each' loop to print each element of the array
            for (char c : ch) {
                System.out.println(c);
            }
            // Creates an array of the size of the wordle word
            char[] wordle = new char[word.length()];

            System.out.println(" ");
            // Characters of string wordle word which is 'tyler' are in an array
            for (int i = 0; i < word.length(); i++) {
                wordle[i] = word.charAt(i);
                // System.out.println(wordle[i]);
                if (wordle[i] == ch[i]) {
                    System.out.println("Letter " + ch[i] + " is correct");
                } else {
                    System.out.println("Letter " + ch[i] + " is not correct");
                }
            }
            System.out.println(" ");

        } while (counter <= 5);

        System.out.println("You lost!");

        // End of Tyler's work

    }

}
</code>```

I am trying to make a do while loop that reprompts the user for a word, giving the user 5 tries, and the program would end if A) the user has had all 5 tries, or B) the user gets the word right. Please help with the loop, or if there is additional code I should try.

I tried to put the variables inside the dowhile loop, but one of the variables is from a scanner (it is user input), but I need that inside the do while loop so it reprompts the user while the counter is less than or equal to 5.

Body:
I am creating a wordle project, where the word is set to "tyler". The user's guess is saved as a string, as is the wordle word, "tyler". Both the strings are saved as characters in an array, then the program checks whether each character in the arrays match.
My code is here:

// Nelson's work
import java.util.Scanner;

class FinalProject {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        // Nelson's work
        int counter = 0;
        do {
            String word = "tyler";
            System.out.println("Press enter to begin");
            // Saves userInput as a string
            String userInput = input.nextLine();
            while (userInput.length() != 5) {
                System.out.println("Enter a 5 letter word: ");
                userInput = input.nextLine();
                counter++;
            }
            // End of Nelson's work
            // Tyler's work
            // Creates an array of length equal to string length
            char[] ch = new char[userInput.length()];

            // For loop to put characters into array
            for (int i = 0; i < userInput.length(); i++) {
                ch[i] = userInput.charAt(i);
            }
            // 'For each' loop to print each element of the array
            for (char c : ch) {
                System.out.println(c);
            }
            // Creates an array of the size of the wordle word
            char[] wordle = new char[word.length()];

            System.out.println(" ");
            // Characters of string wordle word which is 'tyler' are in an array
            for (int i = 0; i < word.length(); i++) {
                wordle[i] = word.charAt(i);
                // System.out.println(wordle[i]);
                if (wordle[i] == ch[i]) {
                    System.out.println("Letter " + ch[i] + " is correct");
                } else {
                    System.out.println("Letter " + ch[i] + " is not correct");
                }
            }
            System.out.println(" ");

        } while (counter <= 5);

        System.out.println("You lost!");

        // End of Tyler's work

    }

}

I am trying to make a do while loop that reprompts the user for a word, giving the user 5 tries, and the program would end if A) the user has had all 5 tries, or B) the user gets the word right. Please help with the loop, or if there is additional code I should try.

I tried to put the variables inside the dowhile loop, but one of the variables is from a scanner (it is user input), but I need that inside the do while loop so it reprompts the user while the counter is less than or equal to 5.


问:
Is there a way to develop a website on WIX using custom CSS without it being live?
I am trying to build a new website for a client, replacing their current website which is built in Wix. I am new to Wix but they want to continue to use Wix for the site so I am trying to work out how to tweak an existing Wix templates to customise it a bit more than I can do natively in Wix.

I have searched a question here and figured out how to add some custom CSS but it seems you can only add it once the site is already published and assigned to a domain. I can't point their domain to the site until after it is signed off and ready to go live. Is my best option to buy a domain, purely as staging, to develop this site and then switch it over to their domain when development is complete, or am I missing something and there is a more straightforward solution.


问:
How to access the static method via MOQ in c sharp
I am using mock library in my .Net unit test and getting an error

cannot be accessed with an instance reference instead use type name.

I am getting this error at following line in my test method where it is calling cq.Instance. I am new to mock library. Could somebody let me know how do I call the static method?

```<code>attributeValue.Setup(cq => cq.Instance().CallQueryAsync(request, 1)).Returns(attrValue);
</code>```

Actual method to be tested

```<code> public static async Task<AttributeValueList> GetAttributeSecDateValueList(int attrId)
        {
            try
            {
                var request = AttributeValue.ResolveRequest(attrId);
                var response = await AsyncProxy<AttributeValue>.Instance().CallQueryAsync(request, (int)AttributeValue.OperationType.GetSecDateValues);

                var coll = new AttributeValueList();
                coll.AddRange(response);

                return coll;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
</code>```

Proxy class

```<code>public class AsyncProxy<RT> : IDisposable
    where RT : class, new()
  {
    readonly WebServiceProxy<RT> _wsProxy;

    private AsyncProxy(WebServiceProxy<RT> webServiceProxy)
    {
      _wsProxy = webServiceProxy;
    }

    public static async Task<IEnumerable<RT>> Load(object parameters)
    {

      return await Instance().CallQueryAsync(parameters);
    }

    public static AsyncProxy<RT> Instance()
    {
      return new AsyncProxy<RT>(WebServiceProxy<RT>.Instance());
    }

    /// <summary>
    /// Return result set of Poco as smartCollection
    /// </summary>
    public async Task<SmartCollection<RT>> CallQueryAsync(object request, int? uniqueIdentifier = null, bool isLongRunning = false, [CallerMemberName]string memberName = "")
    {
//#if DEBUG
//      var stopwatch = new Stopwatch();
//      stopwatch.Start();
//#endif
      try
      {
        // We want to get rid of the proxy as soon as we are done with it
        using (_wsProxy)
        {
          var awaited = await _wsProxy.CallQueryAsync(request, uniqueIdentifier, isLongRunning);
          if (awaited == null)
            return null;

          var observableCollection = new SmartCollection<RT>();

          foreach (var item in awaited)
            observableCollection.Add(item as RT);

          return observableCollection;
        }
      }
      finally
      {
        Dispose();

//#if DEBUG
//        stopwatch.Stop();

//        Debug.WriteLine(null);
//        Debug.WriteLine($"****>>>>> AsyncProxy {memberName} took {stopwatch.ElapsedMilliseconds} ms <<<<<<<<****");
//#endif
      }
    }
}
</code>```

test method

```<code>[TestMethod]
public void test()
{

    Task<SmartCollection<AttributeValue>> attrValue = null;
    var request = new AttributeValue();

    var attributeValue = new Mock<AsyncProxy<AttributeValue>>();

    attributeValue.Setup(cq => cq.Instance().CallQueryAsync(request, 1)).Returns(attrValue);

}
</code>```

Body:
I am using mock library in my .Net unit test and getting an error

cannot be accessed with an instance reference instead use type name.

I am getting this error at following line in my test method where it is calling cq.Instance. I am new to mock library. Could somebody let me know how do I call the static method?

attributeValue.Setup(cq => cq.Instance().CallQueryAsync(request, 1)).Returns(attrValue);

Actual method to be tested

 public static async Task<AttributeValueList> GetAttributeSecDateValueList(int attrId)
        {
            try
            {
                var request = AttributeValue.ResolveRequest(attrId);
                var response = await AsyncProxy<AttributeValue>.Instance().CallQueryAsync(request, (int)AttributeValue.OperationType.GetSecDateValues);

                var coll = new AttributeValueList();
                coll.AddRange(response);

                return coll;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

Proxy class

public class AsyncProxy<RT> : IDisposable
    where RT : class, new()
  {
    readonly WebServiceProxy<RT> _wsProxy;

    private AsyncProxy(WebServiceProxy<RT> webServiceProxy)
    {
      _wsProxy = webServiceProxy;
    }

    public static async Task<IEnumerable<RT>> Load(object parameters)
    {

      return await Instance().CallQueryAsync(parameters);
    }

    public static AsyncProxy<RT> Instance()
    {
      return new AsyncProxy<RT>(WebServiceProxy<RT>.Instance());
    }

    ///
    /// Return result set of Poco as smartCollection
    ///
    public async Task<SmartCollection<RT>> CallQueryAsync(object request, int? uniqueIdentifier = null, bool isLongRunning = false, [CallerMemberName]string memberName = "")
    {
//#if DEBUG
//      var stopwatch = new Stopwatch();
//      stopwatch.Start();
//#endif
      try
      {
        // We want to get rid of the proxy as soon as we are done with it
        using (_wsProxy)
        {
          var awaited = await _wsProxy.CallQueryAsync(request, uniqueIdentifier, isLongRunning);
          if (awaited == null)
            return null;

          var observableCollection = new SmartCollection<RT>();

          foreach (var item in awaited)
            observableCollection.Add(item as RT);

          return observableCollection;
        }
      }
      finally
      {
        Dispose();

//#if DEBUG
//        stopwatch.Stop();

//        Debug.WriteLine(null);
//        Debug.WriteLine($"****>>>>> AsyncProxy {memberName} took {stopwatch.ElapsedMilliseconds} ms <<<<<<<<****");
//#endif
      }
    }
}

test method

[TestMethod]
public void test()
{

    Task<SmartCollection<AttributeValue>> attrValue = null;
    var request = new AttributeValue();

    var attributeValue = new Mock<AsyncProxy<AttributeValue>>();

    attributeValue.Setup(cq => cq.Instance().CallQueryAsync(request, 1)).Returns(attrValue);

}


问:
Looking for an example that connects Graphql with solace
Is there any code example that shows how we can use the Solace pubsub+ as a source and watch for events such as insertion or update at the database at the graphql server level and leverage graphql subscription service ?

I came across example with rabbitmq to achieve this but I am looking for specifically solace.


问:
Find method using Full-Text search to be case and diacritic insensitive
Using the MongoDB driver for the .NET framework, I need to develop a way of creating a full-text search method that ignores string cases and diacritics.

I've already tried using a regex expression for that, but it does not work for strings that have accents and weird casings (diacritics).

```<code>var filterDefinition = new BsonDocument("$expr", new BsonDocument("$regexMatch", new BsonDocument
{
   { "input", new BsonDocument("$toString", "$field") },
   { "regex", searchTerm },
   { "options", "i" }
}));
</code>```

If I create a text index that ignores the diacritics, the full-text search method doesn't work.

```<code>db.BsonDocument.createIndex({name: 'text'},{default_language: 'pt'})
</code>```
```<code>var filter = Builders<BsonDocument>.Filter.Text(searchTerm);
</code>```

Is there any way of combining these two approaches into something that meets the desired criteria?

Body:
Using the MongoDB driver for the .NET framework, I need to develop a way of creating a full-text search method that ignores string cases and diacritics.

I've already tried using a regex expression for that, but it does not work for strings that have accents and weird casings (diacritics).

var filterDefinition = new BsonDocument("$expr", new BsonDocument("$regexMatch", new BsonDocument
{
   { "input", new BsonDocument("$toString", "$field") },
   { "regex", searchTerm },
   { "options", "i" }
}));

If I create a text index that ignores the diacritics, the full-text search method doesn't work.

db.BsonDocument.createIndex({name: 'text'},{default_language: 'pt'})

var filter = Builders<BsonDocument>.Filter.Text(searchTerm);

Is there any way of combining these two approaches into something that meets the desired criteria?


问:
org.springframework.dao.CannotAcquireLockException occurring while doing spring dao save in MYSQL DB
I have a mysql table referencing other tables. While performing spring dao to save operation in a transactional block on this table object, I am getting following exception:

2021-10-09 10:16:27,921 DEBUG [http-nio-8080-exec-446] [my.controller.error.RestResponseEntityExceptionHandler - Exception occurred:
org.springframework.dao.CannotAcquireLockException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.LockAcquisitionException: could not execute statement   org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:246)    org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:221)
... 9 lines omitted ...

Note that this started occurring heavily since a week and before that only some intermittent occurrences. Any leads what might be an issue here and how to resolve?

My hibernate cfg configuration is below:

```<code>    <bean id="dataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClassName}"/>
        <property name="jdbcUrl" value="${jdbc.databaseurl}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="acquireIncrement" value="1"/>
        <property name="minPoolSize" value="10"/>
        <property name="maxPoolSize" value="50"/>
        <property name="maxIdleTime" value="1000"/>
    </bean>
</code>```

Not sure if it should be fixed at Code level or Database level.

Body:
I have a mysql table referencing other tables. While performing spring dao to save operation in a transactional block on this table object, I am getting following exception:

2021-10-09 10:16:27,921 DEBUG [http-nio-8080-exec-446] [my.controller.error.RestResponseEntityExceptionHandler - Exception occurred:
org.springframework.dao.CannotAcquireLockException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.LockAcquisitionException: could not execute statement   org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:246)    org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:221)
... 9 lines omitted ...

Note that this started occurring heavily since a week and before that only some intermittent occurrences. Any leads what might be an issue here and how to resolve?

My hibernate cfg configuration is below:

    <bean id="dataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClassName}"/>
        <property name="jdbcUrl" value="${jdbc.databaseurl}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="acquireIncrement" value="1"/>
        <property name="minPoolSize" value="10"/>
        <property name="maxPoolSize" value="50"/>
        <property name="maxIdleTime" value="1000"/>
    </bean>

Not sure if it should be fixed at Code level or Database level.


问:
Load protected (Authorization header) images using QuillJs
It's pretty easy to upload the images to the server but what I want is to load the images from the server on the browser but as the images are protected using JWT access control the backend is throwing Access Denied error.

Is there any way by which we can add the authorization header to the requests going to the backed to load the images?

Did not find any way to solve this issue.


问:
Error while executing Maven project from Command prompt
While I try executing Maven project using any of the commands

maven clean install

maven compile

from command prompt I'm getting below error

The JAVA_HOME environment variable is not defined correctly, so Apache
Maven cannot be started. JAVA_HOME is set to "C:\Program
Files\AdoptOpenJDK\jdk-11.0.8.10", but "%JAVA_HOME%\bin\java.exe" does
not exist.


问:
Geopandas legend is not a continuous colour bar
I am plotting a geopandas choropleth plot, and the legend is not a continuous colour bar.

Here is the code:

```<code>fig, ax = plt.subplots(figsize = (10,10))
sm = gdf.plot(column = 'Average Crime',cmap = 'PuRd', ax = ax, legend = True, categorical = True)
ax.set(facecolor = 'white')

plt.show()
</code>```

Here is how the image is shown:

How do I make the legend so that the legend is a continuous colour bar?

Thanks.

Body:
I am plotting a geopandas choropleth plot, and the legend is not a continuous colour bar.

Here is the code:

fig, ax = plt.subplots(figsize = (10,10))
sm = gdf.plot(column = 'Average Crime',cmap = 'PuRd', ax = ax, legend = True, categorical = True)
ax.set(facecolor = 'white')

plt.show()

Here is how the image is shown:

How do I make the legend so that the legend is a continuous colour bar?

Thanks.


问:
Modify status check name of github reuseable workflow
All my ci workflows on github are currently managed in the respective repository. The jobs of those workflows are set as required status checks for PRs. I want to make use of reuseable workflows, extract them and manage them in a central place.

Problem is that the name of the status check changes. Before it only included the job id of the single job, it now is comprised of the job id of the caller and called workflow.
In this case "build" turns into "build / build".

This means that I would need to go through every repository and change the name of the required status check, which I would like to avoid since I don't have the neccessary permissions for all repositories to do so.

I could not find a way to manually set the name of the created status check.
Setting the job name does not help as it only replaces the job id. Meaning it turns into "caller-job-name / reuseable-job-name"


问:
2 Log4Net Config Within 2 Assembly Not working seperatly
I have two Project

Project A and B

A is first compiled i want a basic log4net appender inside it as a A_log4net.config inside that is call in AssemblyInfo.cs with

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "A_log4net.config")]

B is compiled way later and had a custom appender and stuff configured in B_log4net.config
Who is load later and programaticly with

```<code>using (Stream stream = type.Assembly.GetManifestResourceStream(log4netConfig))
{
    LogManager.ResetConfiguration();
    XmlConfigurator.Configure(stream);
}
</code>```

Thing is. When i use my Log in Project A the logging event are catch by Config A and B

In the same way log fire by B are catch by config A.

So what did i miss? Can i filter log in config? How to make this two config work without interacting with each other?

Body:
I have two Project

Project A and B

A is first compiled i want a basic log4net appender inside it as a A_log4net.config inside that is call in AssemblyInfo.cs with

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "A_log4net.config")]

B is compiled way later and had a custom appender and stuff configured in B_log4net.config
Who is load later and programaticly with

using (Stream stream = type.Assembly.GetManifestResourceStream(log4netConfig))
{
    LogManager.ResetConfiguration();
    XmlConfigurator.Configure(stream);
}

Thing is. When i use my Log in Project A the logging event are catch by Config A and B

In the same way log fire by B are catch by config A.

So what did i miss? Can i filter log in config? How to make this two config work without interacting with each other?


问:
How to use a third party c++ dll with pybind11
We have stepper motors from ARCUS Technology which are supplied by a another distributor who support is little to not existing. Sadly some sample code is written in python 2.7 and we are not willing to use unsupported software.

From the documentation of the stepper motor, we know that the communication to the motor is handled via a driver and a DLL API. The docu also provide the function declaration names and a description of the functions.

Further I was able to identify those function name inside a header file src/Arcus/Arcus.h as extern "C" __declspec(dllimport) and also inside a cpp file src/Arcus/Arcus.cpp.

Also I was able to read the partially human readable src/Arcus/PerformaxCom.lib file to identify, that this lib is linking to PerformaxCom.DLL.

Okay, with this knowledge in the backpack, we want to use pyside11 to create python bindings for those functions. So far as I worked through the first step pyside11 example I was able to create the basic module, with the add and subtract method successful.

So my structural attempt would look like the following:

```<code>performax
 ┣ src
 ┃ ┣ lib
 ┃ ┃ ┗ PerformaxCom.dll
 ┃ ┣ module.cpp
 ┃ ┣ module.hpp
 ┃ ┗ PerformaxCom.lib
 ┣ pybind11(repo/submodule)
 ┣ CMakeLists.txt
 ┣ pyproject.toml
 ┗ setup.py
</code>```

So as far as I understand I need to update the CMakeLists.txt to link the PerformaxCom.lib with my module.cpp. So my basic CmakeLists.txt looks like the following:

```<code>cmake_minimum_required(VERSION 3.4...3.18)
project(performax)

add_subdirectory(pybind11)
pybind11_add_module(performax src/module.cpp)

# EXAMPLE_VERSION_INFO is defined by setup.py and passed into the C++ code as a
# define (VERSION_INFO) here.
target_compile_definitions(cmake_example
                           PRIVATE VERSION_INFO=${EXAMPLE_VERSION_INFO})
</code>```

AS far as I understand this would work if I declarate and define my functions directly inside src/module.cpp and src/module.hpp, but since I get the functions from the dll I am not sure how to update correctly.

So at the moment I would declarate the functions in the src/module.hpp file similar as they did in src/Arcus/Arcus.h and would bind the them inside src/module.cpp similar to the cmake_example for pybind11.

At the end what bothers me also: why do they use extern "C" __declspec(dllimport), does this mean the dll is written in C instead of C++?

Body:
We have stepper motors from ARCUS Technology which are supplied by a another distributor who support is little to not existing. Sadly some sample code is written in python 2.7 and we are not willing to use unsupported software.

From the documentation of the stepper motor, we know that the communication to the motor is handled via a driver and a DLL API. The docu also provide the function declaration names and a description of the functions.

Further I was able to identify those function name inside a header file src/Arcus/Arcus.h as extern "C" __declspec(dllimport) and also inside a cpp file src/Arcus/Arcus.cpp.

Also I was able to read the partially human readable src/Arcus/PerformaxCom.lib file to identify, that this lib is linking to PerformaxCom.DLL.

Okay, with this knowledge in the backpack, we want to use pyside11 to create python bindings for those functions. So far as I worked through the first step pyside11 example I was able to create the basic module, with the add and subtract method successful.

So my structural attempt would look like the following:

performax
 ┣ src
 ┃ ┣ lib
 ┃ ┃ ┗ PerformaxCom.dll
 ┃ ┣ module.cpp
 ┃ ┣ module.hpp
 ┃ ┗ PerformaxCom.lib
 ┣ pybind11(repo/submodule)
 ┣ CMakeLists.txt
 ┣ pyproject.toml
 ┗ setup.py

So as far as I understand I need to update the CMakeLists.txt to link the PerformaxCom.lib with my module.cpp. So my basic CmakeLists.txt looks like the following:

cmake_minimum_required(VERSION 3.4...3.18)
project(performax)

add_subdirectory(pybind11)
pybind11_add_module(performax src/module.cpp)

# EXAMPLE_VERSION_INFO is defined by setup.py and passed into the C++ code as a
# define (VERSION_INFO) here.
target_compile_definitions(cmake_example
                           PRIVATE VERSION_INFO=${EXAMPLE_VERSION_INFO})

AS far as I understand this would work if I declarate and define my functions directly inside src/module.cpp and src/module.hpp, but since I get the functions from the dll I am not sure how to update correctly.

So at the moment I would declarate the functions in the src/module.hpp file similar as they did in src/Arcus/Arcus.h and would bind the them inside src/module.cpp similar to the cmake_example for pybind11.

At the end what bothers me also: why do they use extern "C" __declspec(dllimport), does this mean the dll is written in C instead of C++?


问:
Write set of sql files to same table
I have a set of *.sql files (>2000) which contain table creation scripts per file. My goal is to write all of the sql files to one table. I want to accomplish this by creating the table before reading and writing the files. Each file I read I want to filter to only contain the INSERT INTO lines.

I currently read the files as follows:
with open(file) as f:
sql = f.read()

This returns a string which holds the table creation string as well as the INSERT statements. Is there any simple string filtering way to only return the lines containing the INSERT statements?

Title: Write set of sql files to same table


问:
Microsoft Graph upload large files
I am developing an aplication that send and email with one or multiple attachments via Microsoft Graph, but when try to upload file send me an error: ": Invalid total bytes specified in the Content-Range header"
i asume that i must specifi Range Value in same where, but no idea.

This is my code:

```<code>private static async void SenMailUsingMicrosoftGraph(List<String>Destinations, List<String>Cc, string HidenCopy, string Body, string Title, List<FileInfo>Filess);
{
ClientSecretCredential credential = new ClientSecretCredential("MyTenantID", "MyClientId", "MyClientSecret");

        List<Recipient> recipientsDestinatarios = new List<Recipient>();
        List<Recipient> recipientsCopias = new List<Recipient>();

        foreach (var c in Destinations)
        {
            recipientsDestinatarios.Add(
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = c
                    }
                });
        }

        foreach (var mail in Cc)
        {

            recipientsCopias.Add(
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = mail
                    }
                });
        }
        #endregion

        var message = new Microsoft.Graph.Message
        {
            Subject = Title,
            Body = new ItemBody
            {
                ContentType = BodyType.Html,
                Content = Body
            },
            ToRecipients = recipientsDestinatarios
            ,
            CcRecipients = recipientsCopias
            ,
            BccRecipients = new List<Recipient>()
            {
                new Recipient
                {
                    EmailAddress=new EmailAddress{Address=Hiden}
                }
            }

        };

        GraphServiceClient graphClient = new GraphServiceClient(credential);
        #endregion

        #region adjuntar ficheros
        var msgResult = await graphClient.Users["myemail@mycompany.com"].MailFolders.Drafts.Messages
                                    .Request()
                                    .WithMaxRetry(9)
                                    .AddAsync(message);
        foreach (var Archivo in Filess)
        {
            var attachmentContentSize = Archivo.Length;
            var attachmentItem = new AttachmentItem
            {
                AttachmentType = AttachmentType.File,
                Name = Archivo.Name,
                Size = attachmentContentSize,
            };

            //initiate the upload session for large files
            var uploadSession = await graphClient.Users["myemail@mycompany.com"].Messages[msgResult.Id].Attachments
                                                                    .CreateUploadSession(attachmentItem)
                                                                    .Request()
                                                                    .PostAsync();

            var maxChunkSize = 1024 * 320;
            var allBytes = System.IO.File.ReadAllBytes(Archivo.FullName);

            using (var stream = new MemoryStream(allBytes))
            {
                stream.Position = 0;
                LargeFileUploadTask<FileAttachment> largeFileUploadTask = new LargeFileUploadTask<FileAttachment>(uploadSession, stream, maxChunkSize);

                await largeFileUploadTask.UploadAsync();
            }
        }
        await graphClient.Users["myemail@mycompany.com"].Messages[msgResult.Id].Send().Request().PostAsync();

}
</code>```

I try something like this:

```<code>var content = new System.Net.Http.Headers.ContentRangeHeaderValue(0,MyFile.Length-1,MyFile.Length);
</code>```

but i dont now how to asign this content variable, i think that must go in the uploadSession but dont know how.

------------------------------------EDIT------------------------------
included a Picture where see that the size of the attachment is not zero

Title: Microsoft Graph upload large files

Body:
I am developing an aplication that send and email with one or multiple attachments via Microsoft Graph, but when try to upload file send me an error: ": Invalid total bytes specified in the Content-Range header"
i asume that i must specifi Range Value in same where, but no idea.

This is my code:

private static async void SenMailUsingMicrosoftGraph(List<String>Destinations, List<String>Cc, string HidenCopy, string Body, string Title, List<FileInfo>Filess);
{
ClientSecretCredential credential = new ClientSecretCredential("MyTenantID", "MyClientId", "MyClientSecret");

        List<Recipient> recipientsDestinatarios = new List<Recipient>();
        List<Recipient> recipientsCopias = new List<Recipient>();

        foreach (var c in Destinations)
        {
            recipientsDestinatarios.Add(
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = c
                    }
                });
        }

        foreach (var mail in Cc)
        {

            recipientsCopias.Add(
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = mail
                    }
                });
        }
        #endregion

        var message = new Microsoft.Graph.Message
        {
            Subject = Title,
            Body = new ItemBody
            {
                ContentType = BodyType.Html,
                Content = Body
            },
            ToRecipients = recipientsDestinatarios
            ,
            CcRecipients = recipientsCopias
            ,
            BccRecipients = new List<Recipient>()
            {
                new Recipient
                {
                    EmailAddress=new EmailAddress{Address=Hiden}
                }
            }

        };

        GraphServiceClient graphClient = new GraphServiceClient(credential);
        #endregion

        #region adjuntar ficheros
        var msgResult = await graphClient.Users["myemail@mycompany.com"].MailFolders.Drafts.Messages
                                    .Request()
                                    .WithMaxRetry(9)
                                    .AddAsync(message);
        foreach (var Archivo in Filess)
        {
            var attachmentContentSize = Archivo.Length;
            var attachmentItem = new AttachmentItem
            {
                AttachmentType = AttachmentType.File,
                Name = Archivo.Name,
                Size = attachmentContentSize,
            };

            //initiate the upload session for large files
            var uploadSession = await graphClient.Users["myemail@mycompany.com"].Messages[msgResult.Id].Attachments
                                                                    .CreateUploadSession(attachmentItem)
                                                                    .Request()
                                                                    .PostAsync();

            var maxChunkSize = 1024 * 320;
            var allBytes = System.IO.File.ReadAllBytes(Archivo.FullName);

            using (var stream = new MemoryStream(allBytes))
            {
                stream.Position = 0;
                LargeFileUploadTask<FileAttachment> largeFileUploadTask = new LargeFileUploadTask<FileAttachment>(uploadSession, stream, maxChunkSize);

                await largeFileUploadTask.UploadAsync();
            }
        }
        await graphClient.Users["myemail@mycompany.com"].Messages[msgResult.Id].Send().Request().PostAsync();

}

I try something like this:

var content = new System.Net.Http.Headers.ContentRangeHeaderValue(0,MyFile.Length-1,MyFile.Length);

but i dont now how to asign this content variable, i think that must go in the uploadSession but dont know how.

------------------------------------EDIT------------------------------
included a Picture where see that the size of the attachment is not zero


问:
Keycloak returns 403 code after authentication
I have keycloak and another spring boot application in docker compose.

Keycloak and my application both start and run correctly. I added a realm, client and a role using keycloak admin console. Then I assigned the role to the user.

I tried to access my application's endpoint which is protected by keycloak, and after providing the correct credentials in the keycloak login pop-up, I see 403 - forbidden status in F12 network tab.

docker-compose keycloak part:

```<code>  keycloak:
    restart: on-failure
    image: quay.io/keycloak/keycloak:12.0.4
    container_name: keycloak
    networks:
      - network1
    environment:
      DB_VENDOR: MYSQL
      DB_ADDR: mysql
      DB_DATABASE: keycloak
      DB_USER: user
      DB_PASSWORD: password
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: password
      WAIT_HOSTS: mysql:3306
      TZ: Europe/Zagreb
    ports:
      - 8080:8080
    depends_on:
      - mysql
</code>```

application.properties:

```<code>#Client registration
spring.security.oauth2.client.registration.keycloak.client-id=test2
spring.security.oauth2.client.registration.keycloak.client-secret=secret
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.keycloak.scope=openid

#OIDC provider
spring.security.oauth2.client.provider.keycloak.issuer-uri=http://keycloak:8080/auth/realms/test
spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username

spring.security.oauth2.client.provider.keycloak.authorization-uri=http://keycloak:8080/auth/realms/test/protocol/openid-connect/auth
spring.security.oauth2.client.provider.keycloak.token-uri=http://keycloak:8080/auth/realms/test/protocol/openid-connect/token
</code>```

SecurityConfig class:

```<code>@EnableWebSecurity
class SecurityConfig {

    private final KeycloakLogoutHandler keycloakLogoutHandler;

    SecurityConfig(KeycloakLogoutHandler keycloakLogoutHandler) {
        this.keycloakLogoutHandler = keycloakLogoutHandler;
    }

    @Bean
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/public/**").permitAll().anyRequest()
                .hasRole("test");
                http.csrf().disable();
        http.oauth2Login()
                .and()
                .logout()
                .addLogoutHandler(keycloakLogoutHandler)
                .logoutSuccessUrl("/");
        return http.build();
    }
}
</code>```

In hosts file on path C:\Windows\System32\drivers\etc\hosts i added this alias:127.0.0.1 keycloak.
I did this because of communication problems between my app and keycloak in docker containers.

Endpoints which are not protected by keycloak can be accessed without problem.
Any help is appreciated.

Body:
I have keycloak and another spring boot application in docker compose.

Keycloak and my application both start and run correctly. I added a realm, client and a role using keycloak admin console. Then I assigned the role to the user.

I tried to access my application's endpoint which is protected by keycloak, and after providing the correct credentials in the keycloak login pop-up, I see 403 - forbidden status in F12 network tab.

docker-compose keycloak part:

  keycloak:
    restart: on-failure
    image: quay.io/keycloak/keycloak:12.0.4
    container_name: keycloak
    networks:
      - network1
    environment:
      DB_VENDOR: MYSQL
      DB_ADDR: mysql
      DB_DATABASE: keycloak
      DB_USER: user
      DB_PASSWORD: password
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: password
      WAIT_HOSTS: mysql:3306
      TZ: Europe/Zagreb
    ports:
      - 8080:8080
    depends_on:
      - mysql

application.properties:

#Client registration
spring.security.oauth2.client.registration.keycloak.client-id=test2
spring.security.oauth2.client.registration.keycloak.client-secret=secret
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.keycloak.scope=openid

#OIDC provider
spring.security.oauth2.client.provider.keycloak.issuer-uri=http://keycloak:8080/auth/realms/test
spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username

spring.security.oauth2.client.provider.keycloak.authorization-uri=http://keycloak:8080/auth/realms/test/protocol/openid-connect/auth
spring.security.oauth2.client.provider.keycloak.token-uri=http://keycloak:8080/auth/realms/test/protocol/openid-connect/token

SecurityConfig class:

@EnableWebSecurity
class SecurityConfig {

    private final KeycloakLogoutHandler keycloakLogoutHandler;

    SecurityConfig(KeycloakLogoutHandler keycloakLogoutHandler) {
        this.keycloakLogoutHandler = keycloakLogoutHandler;
    }

    @Bean
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/public/**").permitAll().anyRequest()
                .hasRole("test");
                http.csrf().disable();
        http.oauth2Login()
                .and()
                .logout()
                .addLogoutHandler(keycloakLogoutHandler)
                .logoutSuccessUrl("/");
        return http.build();
    }
}

In hosts file on path C:\Windows\System32\drivers\etc\hosts i added this alias:127.0.0.1 keycloak.
I did this because of communication problems between my app and keycloak in docker containers.

Endpoints which are not protected by keycloak can be accessed without problem.
Any help is appreciated.