问:
Bad JSON escape sequence in powershell trying to edit a wiql
I've been struggeling all day trying to make a script that changes the value of wiql.

After som debugging and testing I found out that it's actually the wiql that fails, even tho I get it from Azure Devops rest api.

select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] from WorkItems where [System.TeamProject] = @project and [System.WorkItemType] = 'User Story' and [System.AreaPath] under 'error\wrong\folder' and [System.CreatedDate] <= '2022-12-16T00:00:00.0000000' and ([System.IterationPath] under '
folder\folder' or [System.IterationPath] under 'folder\folder')

It fails at "and [System.AreaPath] under 'error\wrong\folder' "

I removed one and one line and after I remove this I only got select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] from WorkItems where [System.TeamProject] = @project and [System.WorkItemType] = 'User Story' it works.

Else I just get

```<code>Invoke-RestMethod : {"count":1,"value":{"Message":"Bad JSON escape sequence: \\S. Path 'wiql', line 2, position 245.\r\nUnexpected character encountered while parsing value: A. Path 'wiql', line 2, position 245.\r\n"}}
At line:1 char:13
+ $response = Invoke-RestMethod -Method Patch -Uri $testurl -Body $body ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
</code>```

Help`?

Tried every combo but cant get it to work

Body:
I've been struggeling all day trying to make a script that changes the value of wiql.

After som debugging and testing I found out that it's actually the wiql that fails, even tho I get it from Azure Devops rest api.

select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] from WorkItems where [System.TeamProject] = @project and [System.WorkItemType] = 'User Story' and [System.AreaPath] under 'error\wrong\folder' and [System.CreatedDate] <= '2022-12-16T00:00:00.0000000' and ([System.IterationPath] under '
folder\folder' or [System.IterationPath] under 'folder\folder')

It fails at "and [System.AreaPath] under 'error\wrong\folder' "

I removed one and one line and after I remove this I only got select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] from WorkItems where [System.TeamProject] = @project and [System.WorkItemType] = 'User Story' it works.

Else I just get

Invoke-RestMethod : {"count":1,"value":{"Message":"Bad JSON escape sequence: \\S. Path 'wiql', line 2, position 245.\r\nUnexpected character encountered while parsing value: A. Path 'wiql', line 2, position 245.\r\n"}}
At line:1 char:13
+ $response = Invoke-RestMethod -Method Patch -Uri $testurl -Body $body ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Help`?

Tried every combo but cant get it to work


来源: stackexchange

问:
Unable to sort bars by value in ggplot
I have tried everything to sort my bars in geom(bar) in ggplot by spending. This is my code:
I have tried manually ordering the data, forcats, changing as an aes in ggplot and can't get it to work.

```<code>#Load any packages
library(ggplot2)
library(dplyr)
library(readr)
library(janitor)
library(RColorBrewer)
library(forcats)

#Create data frame
MarketSize <- data.frame(Country = c("United States", "Japan", "Germany", "France", "Italy", "United Kingdom", "Spain", "Canada", "South Korea",
                                     "Australia", "China", "Brazil", "Russia", "India", "Other"),
                            Spending_2020 = c(528.7, 88.2, 54.9, 36.3, 33.3, 30.2, 25.7, 22.8, 16.2, 11.8, 134.4, 28.7, 17.5, 21.5, 15)
)

# Arrange by Spending outside ggplot
MarketSize$Country <- fct_rev(fct_infreq(MarketSize$Country))

#Create plot, labels etc.
MarketSize_2020 <- ggplot(MarketSize, aes(x = Country, y = Spending_2020)) +
  geom_col(fill="steelblue", width=0.75) +
  geom_text(aes(label=Spending_2020), vjust=0.5, hjust=-0.01, size=3.5) +
  coord_flip() +
  labs(title = "Market Spending on pharmaceuticals, 2020",
       x = "Country or region",
       y = "Total spending on pharmaceuticals (US $BN)") +
  theme_classic()

#View plot
MarketSize_2020
</code>```

Can anyone help? Thanks in advance

I have tried ordering using forcats package and cannot get it to work!

ContentLicense: CC BY-SA 4.0

Title: Unable to sort bars by value in ggplot

Body:
I have tried everything to sort my bars in geom(bar) in ggplot by spending. This is my code:
I have tried manually ordering the data, forcats, changing as an aes in ggplot and can't get it to work.

#Load any packages
library(ggplot2)
library(dplyr)
library(readr)
library(janitor)
library(RColorBrewer)
library(forcats)

#Create data frame
MarketSize <- data.frame(Country = c("United States", "Japan", "Germany", "France", "Italy", "United Kingdom", "Spain", "Canada", "South Korea",
                                     "Australia", "China", "Brazil", "Russia", "India", "Other"),
                            Spending_2020 = c(528.7, 88.2, 54.9, 36.3, 33.3, 30.2, 25.7, 22.8, 16.2, 11.8, 134.4, 28.7, 17.5, 21.5, 15)
)

# Arrange by Spending outside ggplot
MarketSize$Country <- fct_rev(fct_infreq(MarketSize$Country))

#Create plot, labels etc.
MarketSize_2020 <- ggplot(MarketSize, aes(x = Country, y = Spending_2020)) +
  geom_col(fill="steelblue", width=0.75) +
  geom_text(aes(label=Spending_2020), vjust=0.5, hjust=-0.01, size=3.5) +
  coord_flip() +
  labs(title = "Market Spending on pharmaceuticals, 2020",
       x = "Country or region",
       y = "Total spending on pharmaceuticals (US $BN)") +
  theme_classic()

#View plot
MarketSize_2020

Can anyone help? Thanks in advance

I have tried ordering using forcats package and cannot get it to work!


问:
how to split Git Client/Server for Updating/uploading on AWS
I have a project, in which I have two folders: Server / Client.

When I push/commit to git, both folder will be updated.

Now, I want to upload my server to AWS and build a Pipeline. But with connection to git, it will be Server and Client uploaded. How can I change things, that only one folder get uploaded?


问:
PostgreSQL encoding problem with greek characters
I have made a database with utf8 encoding and some greek characters are not recognized in the values that I insert. I use this to create the database:

```<code>CREATE DATABASE greek WITH ENCODING 'UTF-8' LC_COLLATE='el_GR.utf8' LC_CTYPE='el_GR.utf8' TEMPLATE=template0;
</code>```

I have this table:

```<code>CREATE TABLE IF NOT EXISTS products(
    id SERIAL PRIMARY KEY,
    name VARCHAR(50),
    category VARCHAR(50),
    subcategory  VARCHAR(50),
    photo VARCHAR(100),
    UNIQUE (name)
);

</code>```

And then with this insert I try to put in the datbase these values here is how it looks in the windows insert command command prompt:

```<code>INSERT INTO products VALUES
    (0,'Κύκνος Τομάτες Αποφλ Ολoκλ 400γρ','ee0022e7b1b34eb2b834ea334cda52e7','a02951b1c083449b9e7fab2fabd67198'),
    (1,'Elite Φρυγανιές Ολικής Άλεσης 180γρ','ee0022e7b1b34eb2b834ea334cda52e7','a483dd538ecd4ce0bdbba36e99ab5eb1'),
    (2,'Trata Σαρδέλα Λαδιού 100γρ','ee0022e7b1b34eb2b834ea334cda52e7','df10062ca2a04789bd43d18217008b5f'),
    (3,'Μεβγάλ Τυρί Ημισκλ Μακεδ 420γρ','ee0022e7b1b34eb2b834ea334cda52e7','4c73d0eccd1e4dde8bb882e436a64ebb');
</code>```

when I do the select query to see the values

```<code>select * from products;
</code>```

What I get is these unrecognized characters:
enter image description here

What should I try so that all the characters are recognized inside the database?

I tried changing the encoding of the database to WIN1252 but it did not work.

Body:
I have made a database with utf8 encoding and some greek characters are not recognized in the values that I insert. I use this to create the database:

CREATE DATABASE greek WITH ENCODING 'UTF-8' LC_COLLATE='el_GR.utf8' LC_CTYPE='el_GR.utf8' TEMPLATE=template0;

I have this table:

CREATE TABLE IF NOT EXISTS products(
    id SERIAL PRIMARY KEY,
    name VARCHAR(50),
    category VARCHAR(50),
    subcategory  VARCHAR(50),
    photo VARCHAR(100),
    UNIQUE (name)
);

And then with this insert I try to put in the datbase these values here is how it looks in the windows insert command command prompt:

INSERT INTO products VALUES
    (0,'Κύκνος Τομάτες Αποφλ Ολoκλ 400γρ','ee0022e7b1b34eb2b834ea334cda52e7','a02951b1c083449b9e7fab2fabd67198'),
    (1,'Elite Φρυγανιές Ολικής Άλεσης 180γρ','ee0022e7b1b34eb2b834ea334cda52e7','a483dd538ecd4ce0bdbba36e99ab5eb1'),
    (2,'Trata Σαρδέλα Λαδιού 100γρ','ee0022e7b1b34eb2b834ea334cda52e7','df10062ca2a04789bd43d18217008b5f'),
    (3,'Μεβγάλ Τυρί Ημισκλ Μακεδ 420γρ','ee0022e7b1b34eb2b834ea334cda52e7','4c73d0eccd1e4dde8bb882e436a64ebb');

when I do the select query to see the values

select * from products;

What I get is these unrecognized characters:
enter image description here

What should I try so that all the characters are recognized inside the database?

I tried changing the encoding of the database to WIN1252 but it did not work.


问:
Call WordPress API and print result to Laravel Project
I am new to API development.

Currently I am trying to build a small dashboard that can read data such as installed plugins, plugin version and theme name. My question is how to configure JWT in Laravel so I can fill my template with the data there. Or is there another way?

I have already set up a test environment with WordPress and installed a JWT plugin. With Postman I get data output and can query different endpoints.


问:
My request body becomes undefined on frontend side with React
I'm heading here today because I have a problem that I can't seem to solve, and I don't see where the error is. I'm developing a corporate social network, so far so good. Now I'm trying to implement a comment space for posts and that's where it's bugging. I establish my function to create a back side comment (with nodeJs and express) which is:

Function commentaire back

When I run this back function with postman everything goes fine and the comment is created.

commenter with postman

But on the other hand when I execute this function on the front side (with React) my request body becomes undefined while I use the exact same function to create a post and it works very well. Here is the run function on the front side:

Fonction commentaire front

and the response I get:

commenter with React

And also what I get in the console:

console

So I already tried to remove the required: true from the information but that didn't change anything, and then as I said before I used the exact same syntax on the back and front side for the function that creates a new post and it works very well.

If someone can enlighten me, I really can't see what's stuck.
Thanks in advance


问:
What is this c++ template syntax
In STL, I saw the following template definitions:

```<code>template <class _Ty>
struct remove_reference {
    using type                 = _Ty;
    using _Const_thru_ref_type = const _Ty;
};

template <class _Ty>
struct remove_reference<_Ty&> {
    using type                 = _Ty;
    using _Const_thru_ref_type = const _Ty&;
};
</code>```

I have not seen struct remove_reference<_Ty&> this kind of syntax before at the definition of a struct. The syntax similar to this that I know is that when you create a new object e.g. remove_reference<_Ty&> newObject.

What does it mean to use struct remove_reference<_Ty&> at the definition of a struct?

This is not like a template specialization either, as it will resemble the format like template<> struct remove_reference<_Ty&>. Could anyone let me know what c++ feature this is, and the official link, please?

Please note: this is not a duplicate of the common specification questions. As they didn't discuss the syntax of keeping both the generic template parameter on the top and in the struct at the same time.

Title: What is this c++ template syntax

Body:
In STL, I saw the following template definitions:

template <class _Ty>
struct remove_reference {
    using type                 = _Ty;
    using _Const_thru_ref_type = const _Ty;
};

template <class _Ty>
struct remove_reference<_Ty&> {
    using type                 = _Ty;
    using _Const_thru_ref_type = const _Ty&;
};

I have not seen struct remove_reference<_Ty&> this kind of syntax before at the definition of a struct. The syntax similar to this that I know is that when you create a new object e.g. remove_reference<_Ty&> newObject.

What does it mean to use struct remove_reference<_Ty&> at the definition of a struct?

This is not like a template specialization either, as it will resemble the format like template<> struct remove_reference<_Ty&>. Could anyone let me know what c++ feature this is, and the official link, please?

Please note: this is not a duplicate of the common specification questions. As they didn't discuss the syntax of keeping both the generic template parameter on the top and in the struct at the same time.


问:
Why doesnt check the count? Still counting but doesnt check
if (nextActionTime == timeToEngineProblem && !generateProblem) // I need to check this, but it doesn't work
the "timer" is still counting but doesn't check

This is what I do:
...

```<code> [SerializeField] float nextActionTime = 0f;
    [SerializeField] private float periodTime = 0.1f;
    [SerializeField] float timeToEngineProblem = 10f;
    [SerializeField] bool generateProblem;
</code>```
```<code>void Update ()
{
  if (Time.time > nextActionTime)
   {  nextActionTime += periodTime;
     Debug.Log("Time: " + nextActionTime);
     if (nextActionTime == timeToEngineProblem && !generateProblem) // There is what i need to check
        {
            Debug.Log("The problems begin");
            generateProblem = true;
            TruckEngineProblem();
        }

    }

}
</code>```

Body:
if (nextActionTime == timeToEngineProblem && !generateProblem) // I need to check this, but it doesn't work
the "timer" is still counting but doesn't check

This is what I do:
...

 [SerializeField] float nextActionTime = 0f;
    [SerializeField] private float periodTime = 0.1f;
    [SerializeField] float timeToEngineProblem = 10f;
    [SerializeField] bool generateProblem;

void Update ()
{
  if (Time.time > nextActionTime)
   {  nextActionTime += periodTime;
     Debug.Log("Time: " + nextActionTime);
     if (nextActionTime == timeToEngineProblem && !generateProblem) // There is what i need to check
        {
            Debug.Log("The problems begin");
            generateProblem = true;
            TruckEngineProblem();
        }

    }

}


问:
Javascript: multiple fetches
I have the following problem. I have a server who implemented his own authentication process. For that they take the credentials as body.

async function authenticate(){
    var cred = JSON.stringify({
        "email": "user@test.de",
        "password": "1234"
      });

    const response = await fetch("http://.../rest/auth/login", {
        method: 'POST',
        mode: 'cors',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        body: cred
    })
}

```
<p>The response has the code 200 and says "login successfull!" and has a SET-COOKIE header has<br />
the session cookie.</p>
<p>Now I've a second request with which I load the actual data. But when I try this and I get the response code  401: Unauthorized.</p>
<pre class="lang-js prettyprint-override"><code>async function getData(){
    const now = new Date()
    const response = await fetch(`http://.../rest/....`)
    console.log(response)
    const data = await JSON.parse(response)
    console.log(data)
}
authenticate()
.then((res) => {
    console.log(res)
    getData().then(reso => console.log(reso))
})

</code>```

Im not sure how to handle this problem.

I've already checked all responses and everything worked except that the second request doesnt use the Cookie in their request. I've also tried to use the WithCredentials=true option but without success.

EDIT

I changed the credentials from

```<code>credentials: 'cross-origin' -> credentials: 'include'
</code>```

Since im calling an extern Server from localhost.
But i get still an 401 Error.

Title: Javascript: multiple fetches

Body:
I have the following problem. I have a server who implemented his own authentication process. For that they take the credentials as body.

async function authenticate(){
    var cred = JSON.stringify({
        "email": "user@test.de",
        "password": "1234"
      });

    const response = await fetch("http://.../rest/auth/login", {
        method: 'POST',
        mode: 'cors',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        body: cred
    })
}

The response has the code 200 and says "login successfull!" and has a SET-COOKIE header has

the session cookie.

Now I've a second request with which I load the actual data. But when I try this and I get the response code  401: Unauthorized.

async function getData(){
    const now = new Date()
    const response = await fetch(`http://.../rest/....`)
    console.log(response)
    const data = await JSON.parse(response)
    console.log(data)
}
authenticate()
.then((res) => {
    console.log(res)
    getData().then(reso => console.log(reso))
})

Im not sure how to handle this problem.

I've already checked all responses and everything worked except that the second request doesnt use the Cookie in their request. I've also tried to use the WithCredentials=true option but without success.

EDIT

I changed the credentials from

credentials: 'cross-origin' -> credentials: 'include'

Since im calling an extern Server from localhost.
But i get still an 401 Error.


问:
Why is php-fpm ignoring a PHP_INI_PERDIR setting in .user.ini?
Running on Ubuntu 20.04, I have php8.2-fpm installed and running under Apache 2.4 with the following call: SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost".

I have a vhost, with <Directory /var/www/html/somesite/>. There also exists a file /var/www/html/somesite/.user.ini which contains the following:

```<code>mail.force_extra_parameters="-f me@mydomain.com"
mail.log="/tmp/dmail.log"
</code>```

But when I view the details on the web page using phpinfo() I see that only mail.log has changed.

In the docs I see that:

PHP_INI_PERDIR    Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini

Also both these settings share the same permissions in terms of where they're allowed to be set:

mail.log  PHP_INI_SYSTEM|PHP_INI_PERDIR

mail.force_extra_parameters   PHP_INI_SYSTEM|PHP_INI_PERDIR

I have tested other settings, such as mail.add_x_header, max_execution_time, etc, and these have worked as expected, but for some reason the mail.force_extra_parameters one just won't change from no value (null) in the phpinfo(); output.

I have also tested this in other versions of php-fpm. I've also set it manually in the main php.ini file and that did change it in the output, leading me to believe it's also not any loaded mods/config - though I also grepped those directories searching for references to this setting too with no luck.

Why is PHP ignoring this particular setting from .user.ini?

Body:
Running on Ubuntu 20.04, I have php8.2-fpm installed and running under Apache 2.4 with the following call: SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost".

I have a vhost, with <Directory /var/www/html/somesite/>. There also exists a file /var/www/html/somesite/.user.ini which contains the following:

mail.force_extra_parameters="-f me@mydomain.com"
mail.log="/tmp/dmail.log"

But when I view the details on the web page using phpinfo() I see that only mail.log has changed.

In the docs I see that:

PHP_INI_PERDIR    Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini

Also both these settings share the same permissions in terms of where they're allowed to be set:

mail.log  PHP_INI_SYSTEM|PHP_INI_PERDIR

mail.force_extra_parameters   PHP_INI_SYSTEM|PHP_INI_PERDIR

I have tested other settings, such as mail.add_x_header, max_execution_time, etc, and these have worked as expected, but for some reason the mail.force_extra_parameters one just won't change from no value (null) in the phpinfo(); output.

I have also tested this in other versions of php-fpm. I've also set it manually in the main php.ini file and that did change it in the output, leading me to believe it's also not any loaded mods/config - though I also grepped those directories searching for references to this setting too with no luck.

Why is PHP ignoring this particular setting from .user.ini?


问:
Using callback function in tkinter entry through buttons and StringVar
I am using tkinter to browse json files and pass them into an Entry with the intention of using them later on.

However, I would like each json file passed to be processed in some way using a callback function that gets the entry's text. Because other buttons are also changing this entry (clear button, etc.) I want it to be 'readonly' so that the user cannot mess up the format with the keyboard. StringVar conveniently solves this without having to change the state of the widget in order to change it.

I'm trying to just print the content of the entry every time it changes (json_entry_callback) but my code seems to print it only when the UI initializes. Here's my app:

```<code>import customtkinter as ctk

class AppConfigurationGui(ctk.CTk):
    ctk.set_appearance_mode('dark')
    ctk.set_default_color_theme('dark-blue')
    window_width = 800
    window_height = 480

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.geometry('{}x{}'.format(self.window_width, self.window_height))
        self.resizable(False, False)

        # Create JSON Loader widgets
        self.json_frame = ctk.CTkFrame(self, width=200, corner_radius=0, fg_color='transparent')
        self.json_frame.grid(row=0, column=1, sticky="nsew")
        self.json_top_label = ctk.CTkLabel(self.json_frame,
                                           text='JSON File Loader',
                                           font=ctk.CTkFont(size=13, weight='bold'))
        self.json_top_label.grid(row=0, column=0, columnspan=3, padx=20, pady=(10, 0), sticky='wn')
        self.json_browse_button = ctk.CTkButton(self.json_frame,
                                                text='Browse',
                                                width=5,
                                                command=self.browse_for_json)
        self.json_browse_button.grid(row=1, column=0, padx=(20, 0), pady=(5, 10))
        self.json_entry_sv = ctk.StringVar(self.json_frame, value='... search for a json file')
        self.json_entry = ctk.CTkEntry(self.json_frame,
                                       textvariable=self.json_entry_sv,
                                       validate='focus',
                                       validatecommand=self.json_entry_callback,
                                       state='readonly',
                                       width=200,
                                       height=8,
                                       font=ctk.CTkFont(size=13, slant='italic'))
        self.json_entry.grid(row=1, column=1, padx=10, pady=(5, 10))
        self.json_clear_button = ctk.CTkButton(self.json_frame,
                                               text='Clear',
                                               width=25,
                                               height=25,
                                               anchor='center',
                                               command=self.clear_json_entry)
        self.json_clear_button.grid(row=1, column=2, padx=0, pady=(5, 10))

    def write_in_json_entry(self, text: str):
        self.json_entry_sv.set(text)

    def browse_for_json(self):
        filename = 'test.json'
        self.write_in_json_entry(filename)

    def clear_json_entry(self):
        self.write_in_json_entry('... search for a json file')

    def json_entry_callback(self):
        print(self.json_entry_sv.get())

if __name__ == "__main__":
    configurator = AppConfigurationGui()
    configurator.mainloop()

</code>```

As soon as the code runs, '... search for a json file' is printed but when I click 'Browse' and the entry text changes, 'test.json' is not printed, as if the callback function is not called at all. I suspect this has to do with the validation condition not being met, since I am changing the StringVar and not using the entry directly.

So basically my questions are:

Why is the content of the entry printed in initialization but not in runtime?

What is the correct way to run the callback function while keeping the StringVar? (Let me know if there is a better alternative)

(Side question) Why is the 'Clear' button not centered within the row like the other widgets? :D

Thanks in advance

Body:
I am using tkinter to browse json files and pass them into an Entry with the intention of using them later on.

However, I would like each json file passed to be processed in some way using a callback function that gets the entry's text. Because other buttons are also changing this entry (clear button, etc.) I want it to be 'readonly' so that the user cannot mess up the format with the keyboard. StringVar conveniently solves this without having to change the state of the widget in order to change it.

I'm trying to just print the content of the entry every time it changes (json_entry_callback) but my code seems to print it only when the UI initializes. Here's my app:

import customtkinter as ctk

class AppConfigurationGui(ctk.CTk):
    ctk.set_appearance_mode('dark')
    ctk.set_default_color_theme('dark-blue')
    window_width = 800
    window_height = 480

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.geometry('{}x{}'.format(self.window_width, self.window_height))
        self.resizable(False, False)

        # Create JSON Loader widgets
        self.json_frame = ctk.CTkFrame(self, width=200, corner_radius=0, fg_color='transparent')
        self.json_frame.grid(row=0, column=1, sticky="nsew")
        self.json_top_label = ctk.CTkLabel(self.json_frame,
                                           text='JSON File Loader',
                                           font=ctk.CTkFont(size=13, weight='bold'))
        self.json_top_label.grid(row=0, column=0, columnspan=3, padx=20, pady=(10, 0), sticky='wn')
        self.json_browse_button = ctk.CTkButton(self.json_frame,
                                                text='Browse',
                                                width=5,
                                                command=self.browse_for_json)
        self.json_browse_button.grid(row=1, column=0, padx=(20, 0), pady=(5, 10))
        self.json_entry_sv = ctk.StringVar(self.json_frame, value='... search for a json file')
        self.json_entry = ctk.CTkEntry(self.json_frame,
                                       textvariable=self.json_entry_sv,
                                       validate='focus',
                                       validatecommand=self.json_entry_callback,
                                       state='readonly',
                                       width=200,
                                       height=8,
                                       font=ctk.CTkFont(size=13, slant='italic'))
        self.json_entry.grid(row=1, column=1, padx=10, pady=(5, 10))
        self.json_clear_button = ctk.CTkButton(self.json_frame,
                                               text='Clear',
                                               width=25,
                                               height=25,
                                               anchor='center',
                                               command=self.clear_json_entry)
        self.json_clear_button.grid(row=1, column=2, padx=0, pady=(5, 10))

    def write_in_json_entry(self, text: str):
        self.json_entry_sv.set(text)

    def browse_for_json(self):
        filename = 'test.json'
        self.write_in_json_entry(filename)

    def clear_json_entry(self):
        self.write_in_json_entry('... search for a json file')

    def json_entry_callback(self):
        print(self.json_entry_sv.get())

if __name__ == "__main__":
    configurator = AppConfigurationGui()
    configurator.mainloop()

As soon as the code runs, '... search for a json file' is printed but when I click 'Browse' and the entry text changes, 'test.json' is not printed, as if the callback function is not called at all. I suspect this has to do with the validation condition not being met, since I am changing the StringVar and not using the entry directly.

So basically my questions are:

Why is the content of the entry printed in initialization but not in runtime?

What is the correct way to run the callback function while keeping the StringVar? (Let me know if there is a better alternative)

(Side question) Why is the 'Clear' button not centered within the row like the other widgets? :D

Thanks in advance


问:
APIs not visible in Publisher portal and Devportal in WSO2 API Manager
So I have been working on this issue for quite a while now. Earlier we thought its a re_indexing issue so kept re_indexing it which didn't helped at all.

So We started looking into roles and permission and noticed that the APIs are not Visible to admin only.
I tried creating another user account and just gave admin role to it and it worked. Every Single API is visible to this new user with admin role both in publisher and devportal.
Also checked visibility of APIs and its access is set to ALL in publisher portal and public in devportal.
This is getting annoying as admin is supposed to have all the permissions right but here its opposite. Please help someone


问:
A question has four option how to select the correct option and print on the widget in a python
a question has three or four options how to select the correct option and print on the widget in a python.
I want to add one more questions and their options. how can I do it ? and I want to add correct answer.

```<code>from tkinter import *
from tkinter import ttk

def sel():
   selection = "Your score is " + str(var.get())
   label.config(text = selection)

root = Tk()
root.geometry("800x450")

var = IntVar()

label1 = ttk.Label(root, text='1. Select correct your name')
label1.place(x=0, y=20)

R1 = Radiobutton(root, text="Ajay", variable=var, value=1,
                  command=sel)
R1.place(x=0,y=50)

R2 = Radiobutton(root, text="Vijay", variable=var, value=2,
                  command=sel)
R2.place( x=0,y=80 )

R3 = Radiobutton(root, text="Sandeep", variable=var, value=3,
                  command=sel)
R3.place( x=0,y=110)

#answer:sandeep

label1 = ttk.Label(root, text='2. Select the correct city')
label1.place(x=0, y=140)

R1 = Radiobutton(root, text="Mumbai", variable=var, value=1,
                  command=sel)
R1.place(x=0,y=170)

R2 = Radiobutton(root, text="Delhi", variable=var, value=2,
                  command=sel)
R2.place( x=0,y=200 )

R3 = Radiobutton(root, text="Bhopal", variable=var, value=3,
                  command=sel)
R3.place( x=0,y=230)

#answer: Bhopal

label = Label(root)
label.pack()

root.mainloop()
</code>```

Please help how I can do it.

Body:
a question has three or four options how to select the correct option and print on the widget in a python.
I want to add one more questions and their options. how can I do it ? and I want to add correct answer.

from tkinter import *
from tkinter import ttk

def sel():
   selection = "Your score is " + str(var.get())
   label.config(text = selection)

root = Tk()
root.geometry("800x450")

var = IntVar()

label1 = ttk.Label(root, text='1. Select correct your name')
label1.place(x=0, y=20)

R1 = Radiobutton(root, text="Ajay", variable=var, value=1,
                  command=sel)
R1.place(x=0,y=50)

R2 = Radiobutton(root, text="Vijay", variable=var, value=2,
                  command=sel)
R2.place( x=0,y=80 )

R3 = Radiobutton(root, text="Sandeep", variable=var, value=3,
                  command=sel)
R3.place( x=0,y=110)

#answer:sandeep

label1 = ttk.Label(root, text='2. Select the correct city')
label1.place(x=0, y=140)

R1 = Radiobutton(root, text="Mumbai", variable=var, value=1,
                  command=sel)
R1.place(x=0,y=170)

R2 = Radiobutton(root, text="Delhi", variable=var, value=2,
                  command=sel)
R2.place( x=0,y=200 )

R3 = Radiobutton(root, text="Bhopal", variable=var, value=3,
                  command=sel)
R3.place( x=0,y=230)

#answer: Bhopal

label = Label(root)
label.pack()

root.mainloop()

Please help how I can do it.


问:
Is Gloo Edge supports adding custom EnvoyFilters
Istio allows to use CRD EnvoyFilter to have a fine grained control over the envoy filters configuration.
Does Gloo Edge supports the same? Could not find it in the documentation.</p>


问:
The response to CMD8 on the SD card is split on line CMD & line D0
I send the CMD8 command to find out what version my Sd card has, but the answer is split between CMD and D0 so the dirver goes into timeout. I don't understand what it could be.

right reply

enter image description here

response I receive on my board from the same sd card

CMD orange; D0 green

enter image description here

Thanks
G


问:
how do you extract files from a mhtml file
so i was have a MHTML file someone gave me, i looked it up figured out what it holdsm it holds all the assets of a webpage, how do i decompress this (i use linix just incase if you need to know) i dont know if i would just run a script on my device or would use a website to do it for me (either works)

i am hoping do decompress a mhtml file using either shell commands or a website


问:
function is returning junk data
I am trying this program

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

class stringTest
{
    char* p;
    int len;
public:
    stringTest() { len = 0; p = 0; }
    stringTest(const char* s);
    stringTest(const stringTest& s);
    ~stringTest() { delete p; }

    friend stringTest operator+(const stringTest& s, const stringTest& t);
    friend int operator<=(const stringTest& s, const stringTest& t);
    friend void show(const stringTest s);
};

stringTest::stringTest(const char* s)
{
    len = strlen(s);
    p = new char[len + 1];
    strcpy(p, s);
}
stringTest::stringTest(const stringTest& s)
{
    len = s.len;
    p = new char[len + 1];
    strcpy(p, s.p);
}

stringTest operator+(const stringTest &s, const stringTest &t)
{
    stringTest temp;
    temp.len = s.len + t.len;
    temp.p = new char[temp.len + 1];
    strcpy(temp.p, s.p);
    strcat(temp.p, t.p);
    return (temp);
}
int operator<=(const stringTest& s, const stringTest& t)
{
    int m = strlen(s.p);
    int n = strlen(t.p);

    if (m <= n) return (1);
    else return (0);
}

void show(const stringTest s)
{
    cout << s.p;
}

int main()
{
    stringTest s1 = "New ";
    stringTest s2 = "York";
    stringTest s3 = "Delhi";
    stringTest string1, string2, string3;
    string1 = s1;
    string2 = s2;
    string3 = s1+s2;

    cout << "\nstirng1 = "; show(string1);
    cout << "\nstring2 = "; show(string2);
    cout << "\n";
    cout << "\nstring3 = "; show(string3);
    cout << "\n\n";
    if (string1 <= string3)
    {
        show(string1);
        cout << " smaller than ";
        show(string3);
        cout << "\n";
    }
    else
    {
        show(string3);
        cout << " smaller than ";
        show(string1);
        cout << "\n";
    }
    return 0;
}
</code>```

here in the function operator+ I am providing two string and getting an junk character in return.

```<code>stringTest operator+(const stringTest &s, const stringTest &t)
{
    stringTest temp;
    temp.len = s.len + t.len;
    temp.p = new char[temp.len + 1];
    strcpy(temp.p, s.p);
    strcat(temp.p, t.p);
    return (temp);
}
</code>```

I debugged  the code and saw in the memory i am able to get the proper data in temp.p but when i return it become junk character .
Please help me if i am missing something.

Thanks in advance

Vivek

Title: function is returning junk data

Body:
I am trying this program

#include<iostream>
#include<string.h>

class stringTest
{
    char* p;
    int len;
public:
    stringTest() { len = 0; p = 0; }
    stringTest(const char* s);
    stringTest(const stringTest& s);
    ~stringTest() { delete p; }

    friend stringTest operator+(const stringTest& s, const stringTest& t);
    friend int operator<=(const stringTest& s, const stringTest& t);
    friend void show(const stringTest s);
};

stringTest::stringTest(const char* s)
{
    len = strlen(s);
    p = new char[len + 1];
    strcpy(p, s);
}
stringTest::stringTest(const stringTest& s)
{
    len = s.len;
    p = new char[len + 1];
    strcpy(p, s.p);
}

stringTest operator+(const stringTest &s, const stringTest &t)
{
    stringTest temp;
    temp.len = s.len + t.len;
    temp.p = new char[temp.len + 1];
    strcpy(temp.p, s.p);
    strcat(temp.p, t.p);
    return (temp);
}
int operator<=(const stringTest& s, const stringTest& t)
{
    int m = strlen(s.p);
    int n = strlen(t.p);

    if (m <= n) return (1);
    else return (0);
}

void show(const stringTest s)
{
    cout << s.p;
}

int main()
{
    stringTest s1 = "New ";
    stringTest s2 = "York";
    stringTest s3 = "Delhi";
    stringTest string1, string2, string3;
    string1 = s1;
    string2 = s2;
    string3 = s1+s2;

    cout << "\nstirng1 = "; show(string1);
    cout << "\nstring2 = "; show(string2);
    cout << "\n";
    cout << "\nstring3 = "; show(string3);
    cout << "\n\n";
    if (string1 <= string3)
    {
        show(string1);
        cout << " smaller than ";
        show(string3);
        cout << "\n";
    }
    else
    {
        show(string3);
        cout << " smaller than ";
        show(string1);
        cout << "\n";
    }
    return 0;
}

here in the function operator+ I am providing two string and getting an junk character in return.

stringTest operator+(const stringTest &s, const stringTest &t)
{
    stringTest temp;
    temp.len = s.len + t.len;
    temp.p = new char[temp.len + 1];
    strcpy(temp.p, s.p);
    strcat(temp.p, t.p);
    return (temp);
}

I debugged  the code and saw in the memory i am able to get the proper data in temp.p but when i return it become junk character .
Please help me if i am missing something.

Thanks in advance

Vivek


问:
Chart.js datalabels bring label to foreground on hover
I'm using the Datalabels plugin to provide labels to points on a Chart.js scatter graph.

My Chart.js / Datalabels configuration looks like this:

(Full example: https://codepen.io/LondonAppDev/pen/oNyReVr)

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'scatter',
    data: {
        datasets: [{
            label: '# of Votes',
            data: [
              {x: 10, y: 10},
              {x: 100, y: 100},
              {x: 50, y: 50},
              {x: 51, y: 51},
            ]
        }]
    },
    plugins: [ChartDataLabels],
    options: {
      elements: {
        point: {
          radius: 5,
          hoverRadius: 8
        }
      },
      plugins: {
        tooltip: {
          enabled: false
        },
        datalabels: {
          labels: {
            value: {
              align: 'top',
              color: '#000',
              borderColor: '#000',
              borderWidth: 1,
              offset: 20,
              padding: 10,
              backgroundColor: '#fff',
            }
          }
        }

      }
    }
});
```
<p>The default behaviour is that labels will overlap. I want to make the labels come to the forefront when they are hovered over. So if I hover over a label or point, it comes to the foreground.</p>
<p><img src="https://i.stack.imgur.com/qdZeX.png" alt="enter image description here" /></p>
<p>I attempted to add this to <code>options.plugins.datalabels.labels.value</code>:</p>
```            listeners: {
                enter: function(context) {
                  context.dataIndex = 999;
                  context.datasetIndex = 999;
                  return true;
                },
                leave: function(context) {
                  context.dataIndex = 0;
                  context.datasetIndex = 0;
                  return true;
                }
              }
```

However it doesn't have the desired effect.

Anyone know how I can make the label come to the foreground on hover?

Body:
I'm using the Datalabels plugin to provide labels to points on a Chart.js scatter graph.

My Chart.js / Datalabels configuration looks like this:

(Full example: https://codepen.io/LondonAppDev/pen/oNyReVr)

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'scatter',
    data: {
        datasets: [{
            label: '# of Votes',
            data: [
              {x: 10, y: 10},
              {x: 100, y: 100},
              {x: 50, y: 50},
              {x: 51, y: 51},
            ]
        }]
    },
    plugins: [ChartDataLabels],
    options: {
      elements: {
        point: {
          radius: 5,
          hoverRadius: 8
        }
      },
      plugins: {
        tooltip: {
          enabled: false
        },
        datalabels: {
          labels: {
            value: {
              align: 'top',
              color: '#000',
              borderColor: '#000',
              borderWidth: 1,
              offset: 20,
              padding: 10,
              backgroundColor: '#fff',
            }
          }
        }

      }
    }
});

The default behaviour is that labels will overlap. I want to make the labels come to the forefront when they are hovered over. So if I hover over a label or point, it comes to the foreground.

I attempted to add this to options.plugins.datalabels.labels.value:

            listeners: {
                enter: function(context) {
                  context.dataIndex = 999;
                  context.datasetIndex = 999;
                  return true;
                },
                leave: function(context) {
                  context.dataIndex = 0;
                  context.datasetIndex = 0;
                  return true;
                }
              }

However it doesn't have the desired effect.

Anyone know how I can make the label come to the foreground on hover?


问:
Passing value object to a Job makes the unit tests fail
I'm using the latest of the Lucid architecture approach. Now I want to test a Feature with a few Jobs and Operations.

I'm also using value objects. I've rolled my own but followed some best practices. It shouldn't matter since Jobs can accept any class in both the constructor and the handle() method.

If I pass a value object to the constructor, testing the Job calls from the Feature are failing.

I mock the Job with use of the mock() static method that comes with the provided Job unit from which I extend the other jobs. I pass the arguments correct, otherwise it would fail. So that's working.

But the test fails when I pass a value object and the UnitDispatcher (part of Lucid) detects it's about a unit test.

Here's the Job:

```<code>class RetrieveMessageJob extends Job
{
    private UniqueId $uniqueId;

    public function __construct(UniqueId $uniqueId)
    {
        $this->uniqueId = $uniqueId;
    }

    public function handle(ServiceProvider $provider)
    {
        return $provider->retrieveMessage($this->uniqueId);
    }
}
</code>```

This is the value object:

```<code>class UniqueId
{
    public string $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function __toString()
    {
        return (string) $this->value;
    }

    public function value()
    {
        return (string) $this->value;
    }
}
</code>```

Since UnitDispatcher is using reflection to resolve the properties to compare, it tries to find the value of the property in a different way. None the less, it tries to compare some values in the
getConstructorExpectationsForInstance() method:

```<code>public function getConstructorExpectationsForInstance($unit)
{
    foreach ($this->constructorExpectations as $index => $args) {
        $expected = new $unit(...$args);

        $ref = new ReflectionClass($unit);

        // we start by assuming that the unit instance and the $expected one are equal
        // until proven otherwise when we find differences between properties.
        $isEqual = true;
        foreach ($ref->getProperties() as $property) {
            if ($property->getValue($unit) !== $property->getValue($expected)) {
                $isEqual = false;
                break;
            }
        }

        if ($isEqual) {
            return $this->constructorExpectations[$index];
        }
    }
}
</code>```

Both $property->getValue($unit) and $property->getValue($expected) return a UniqueId object with exact the same value as expected by me. Changing the visibility of the property has no effect.

Technically the !== should not be true because of the same value. So I have no idea what else the comparison tries to find.

I'm a bit lost on why this keeps failing.

Here's the test I'm trying to pass:

```<code>class SyncMessagesFeatureTest extends TestCase
{
    protected function setUp(): void
    {
        $this->feature = new SyncMessagesFeature();
    }

    public function testHandle()
    {
         $result = 'Irrelevant for this problem';

         RetrieveMessageJob::mock(['uniqueId' => new UniqueId('uniqueId-1')])->shouldReturn($result);

         $this->feature->handle();
    }
}
</code>```

Thanks for your time to read this.

Body:
I'm using the latest of the Lucid architecture approach. Now I want to test a Feature with a few Jobs and Operations.

I'm also using value objects. I've rolled my own but followed some best practices. It shouldn't matter since Jobs can accept any class in both the constructor and the handle() method.

If I pass a value object to the constructor, testing the Job calls from the Feature are failing.

I mock the Job with use of the mock() static method that comes with the provided Job unit from which I extend the other jobs. I pass the arguments correct, otherwise it would fail. So that's working.

But the test fails when I pass a value object and the UnitDispatcher (part of Lucid) detects it's about a unit test.

Here's the Job:

class RetrieveMessageJob extends Job
{
    private UniqueId $uniqueId;

    public function __construct(UniqueId $uniqueId)
    {
        $this->uniqueId = $uniqueId;
    }

    public function handle(ServiceProvider $provider)
    {
        return $provider->retrieveMessage($this->uniqueId);
    }
}

This is the value object:

class UniqueId
{
    public string $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function __toString()
    {
        return (string) $this->value;
    }

    public function value()
    {
        return (string) $this->value;
    }
}

Since UnitDispatcher is using reflection to resolve the properties to compare, it tries to find the value of the property in a different way. None the less, it tries to compare some values in the
getConstructorExpectationsForInstance() method:

public function getConstructorExpectationsForInstance($unit)
{
    foreach ($this->constructorExpectations as $index => $args) {
        $expected = new $unit(...$args);

        $ref = new ReflectionClass($unit);

        // we start by assuming that the unit instance and the $expected one are equal
        // until proven otherwise when we find differences between properties.
        $isEqual = true;
        foreach ($ref->getProperties() as $property) {
            if ($property->getValue($unit) !== $property->getValue($expected)) {
                $isEqual = false;
                break;
            }
        }

        if ($isEqual) {
            return $this->constructorExpectations[$index];
        }
    }
}

Both $property->getValue($unit) and $property->getValue($expected) return a UniqueId object with exact the same value as expected by me. Changing the visibility of the property has no effect.

Technically the !== should not be true because of the same value. So I have no idea what else the comparison tries to find.

I'm a bit lost on why this keeps failing.

Here's the test I'm trying to pass:

class SyncMessagesFeatureTest extends TestCase
{
    protected function setUp(): void
    {
        $this->feature = new SyncMessagesFeature();
    }

    public function testHandle()
    {
         $result = 'Irrelevant for this problem';

         RetrieveMessageJob::mock(['uniqueId' => new UniqueId('uniqueId-1')])->shouldReturn($result);

         $this->feature->handle();
    }
}

Thanks for your time to read this.


问:
Dynamic key names from generic/object type
I'm using react-hook-form package, which is neat.

One of the things you can do is watch changes on input fields by calling useForm() and using one of the events returned named watch like so:

```<code>const methods = useForm()

console.log('test watch', methods.watch("myrandominpuitname"))
</code>```

which works great, however, if I would like to have autocomplete available on that watch method I have to pass some arguments to the useForm hook like so:

```<code>const methods = useForm<{
    'myrandominpuitname': string,
}>()

console.log('test watch', methods.watch("myrandominpuitname"))
</code>```

That will provide me with autocomplete when trying to call the methods.watch("...")

My question is, is it possible to generate an object from a nested dataset and use that as the type for the useForm?

Sample Looped Dataset:

```<code>function useFormInputs(arrDataset: any[]) {
    let oInputs = {};
    arrDataset.map(dataset => {
        oInputs = Object.assign(oInputs, {[dataset.oField.oProps.name]: ''});
    });

    return useForm<typeof oInputs>();
}
</code>```

Sample Object Result:

```<code>let test = {
    'myrandominpuitname1': '',
    'myrandominpuitname2': '',
    'myrandominpuitname3': '',
}
</code>```

Is it possible to make that object into a type looking like this:

```<code>type myInputs = {
    'myrandominpuitname1': string,
    'myrandominpuitname2': string,
    'myrandominpuitname3': string,
};
</code>```

I would like to generate it automatically,I have tried stuff like

```<code>type TestType<T> = {
    [index in T as string]: string;
};
</code>```

The above sample with not recognize the unique names and will not provide me with autocomplete.

Does anyone know how to do this? My feeling is that it is prob very easy for someone who is experienced with Typescript. :)

Body:
I'm using react-hook-form package, which is neat.

One of the things you can do is watch changes on input fields by calling useForm() and using one of the events returned named watch like so:

const methods = useForm()

console.log('test watch', methods.watch("myrandominpuitname"))

which works great, however, if I would like to have autocomplete available on that watch method I have to pass some arguments to the useForm hook like so:

const methods = useForm<{
    'myrandominpuitname': string,
}>()

console.log('test watch', methods.watch("myrandominpuitname"))

That will provide me with autocomplete when trying to call the methods.watch("...")

My question is, is it possible to generate an object from a nested dataset and use that as the type for the useForm?

Sample Looped Dataset:

function useFormInputs(arrDataset: any[]) {
    let oInputs = {};
    arrDataset.map(dataset => {
        oInputs = Object.assign(oInputs, {[dataset.oField.oProps.name]: ''});
    });

    return useForm<typeof oInputs>();
}

Sample Object Result:

let test = {
    'myrandominpuitname1': '',
    'myrandominpuitname2': '',
    'myrandominpuitname3': '',
}

Is it possible to make that object into a type looking like this:

type myInputs = {
    'myrandominpuitname1': string,
    'myrandominpuitname2': string,
    'myrandominpuitname3': string,
};

I would like to generate it automatically,I have tried stuff like

type TestType<T> = {
    [index in T as string]: string;
};

The above sample with not recognize the unique names and will not provide me with autocomplete.

Does anyone know how to do this? My feeling is that it is prob very easy for someone who is experienced with Typescript. :)


问:
How do I go about updating service deployed with HELM chart in kubernetes?
I have a few services, for example one of them is Nexus - how do I got about updating it, while it was deployed using HELM chart? Should I just insert newer version into values.yaml or should i update to HELM chart which consists newer version of Nexus ?

I was thinking about either changing version for Nexus in values.yaml file that consists values for all HELM charts deployed or go with installing and deploying new HELM chart that consists newer version of Nexus


问:
Blazor update and insert data at the same time
Im working on a project where i have two different tables. Ingredient and Item. Ingredient is the collection of items. Like if you have 4 single instances of carrot in item, its the sum in ingredient. Just like an inventory.

Ive got this code that inserts an item into the item table:

```<code>//insert item data
    private async Task InsertItem()
    {
        ItemModel a = new ItemModel
        {
            Expiration = new DateTime(addItem.Expiration.Year,addItem.Expiration.Month,addItem.Expiration.Day),
            Quantity = (addItem.Quantity),
            Qtype = (addItem.Qtype),
            fk_ingredient_id = (addItem.fk_key)
        };

        string sql = "INSERT INTO item (Expiration,Quantity,Qtype,fk_ingredient_id) VALUES (@Expiration,@Quantity,@Qtype,@fk_ingredient_id);";

        await _data.SaveData(sql, a, _config.GetConnectionString("MySQLConnection"));

        await OnInitializedAsync();
        a = new ItemModel();
        addItem = new AddItem();
    }

</code>```

And some the item model in the blazor code:

```<code>namespace BlazorApp.Models
{
    public class ItemModel
    {
        public int ItemId { get; set; }
        public DateTime Expiration { get; set; }
        public int Quantity { get; set; }
        public string? Qtype { get; set; }
        public int fk_ingredient_id { get; set; }

    }
}
</code>```

What i want to achieve is to update the quantity in the ingredient table after each time i insert a new instance of an item. But i dont know what code to include. The ingredient model:

```<code>namespace BlazorApp.Models
{
    public class IngredientModel
    {
        public int IngId { get; set; }

        public string? IngredientName { get; set; }

        public int? Quantity { get; set; }

        public string? Qtype { get; set; }
    }
}

</code>```

The lists and such on the add item page:

```<code>List<ItemModel> itemModels;
    List<IngredientModel> currentIngredients;

    private ItemModel newItem = new ItemModel();

    public class AddItem
    {
        public DateOnly Expiration { get; set; }
        public int Quantity { get; set; }
        public string? Qtype { get; set; }
        public int fk_key { get; set; }
    }

    private AddItem addItem = new AddItem();

</code>```

My idea is to copy alot from the insert item function but cant get it to work.

and i think that the sql query for the update should be this:

```<code>string sql2 = "UPDATE ingredient SET Quantity = Quantity + @Quantity WHERE IngId = @fk_ingredient_id";
</code>```

As mentioned i tried to copy some of the code and stuff from the insertitem function, but didnt have any luck. I've also tried making 2 sql strings inside insertitem() but without luck

Body:
Im working on a project where i have two different tables. Ingredient and Item. Ingredient is the collection of items. Like if you have 4 single instances of carrot in item, its the sum in ingredient. Just like an inventory.

Ive got this code that inserts an item into the item table:

//insert item data
    private async Task InsertItem()
    {
        ItemModel a = new ItemModel
        {
            Expiration = new DateTime(addItem.Expiration.Year,addItem.Expiration.Month,addItem.Expiration.Day),
            Quantity = (addItem.Quantity),
            Qtype = (addItem.Qtype),
            fk_ingredient_id = (addItem.fk_key)
        };

        string sql = "INSERT INTO item (Expiration,Quantity,Qtype,fk_ingredient_id) VALUES (@Expiration,@Quantity,@Qtype,@fk_ingredient_id);";

        await _data.SaveData(sql, a, _config.GetConnectionString("MySQLConnection"));

        await OnInitializedAsync();
        a = new ItemModel();
        addItem = new AddItem();
    }

And some the item model in the blazor code:

namespace BlazorApp.Models
{
    public class ItemModel
    {
        public int ItemId { get; set; }
        public DateTime Expiration { get; set; }
        public int Quantity { get; set; }
        public string? Qtype { get; set; }
        public int fk_ingredient_id { get; set; }

    }
}

What i want to achieve is to update the quantity in the ingredient table after each time i insert a new instance of an item. But i dont know what code to include. The ingredient model:

namespace BlazorApp.Models
{
    public class IngredientModel
    {
        public int IngId { get; set; }

        public string? IngredientName { get; set; }

        public int? Quantity { get; set; }

        public string? Qtype { get; set; }
    }
}

The lists and such on the add item page:

List<ItemModel> itemModels;
    List<IngredientModel> currentIngredients;

    private ItemModel newItem = new ItemModel();

    public class AddItem
    {
        public DateOnly Expiration { get; set; }
        public int Quantity { get; set; }
        public string? Qtype { get; set; }
        public int fk_key { get; set; }
    }

    private AddItem addItem = new AddItem();

My idea is to copy alot from the insert item function but cant get it to work.

and i think that the sql query for the update should be this:

string sql2 = "UPDATE ingredient SET Quantity = Quantity + @Quantity WHERE IngId = @fk_ingredient_id";

As mentioned i tried to copy some of the code and stuff from the insertitem function, but didnt have any luck. I've also tried making 2 sql strings inside insertitem() but without luck


问:
Notifications which repeat every 5 minutes after a fire date
I was playing around with notifications on iOS. How do you think Due implements persistent reminders? If a reminder is overdue it will remind every 5 minutes until marked as done. Here are some potential strategies:

They schedule a local notification with UNCalendarNotificationTrigger repeats:YES. I don’t really understand how this API works. I don’t understand how I could schedule a trigger for 25Dec and repeat every minute. I’m actually pretty sure it’s impossible to set a repeat of every 5 minutes with UNCalendarNotificationTrigger. This was the best explanation I could find on how triggers work but even then it’s just confusing?

Schedule only the first notification and then recursively schedule the next notification for this reminder. This would work great with willPresentNotification except this will only work when the app is in foreground so I can’t see how they could do this.

Schedule all the individual notifications on each 5 minute interval up front. There is a limit of 64 notifications so it seems like a poor strategy as a background task of some kind would have to be scheduled to run. If the background task never runs at the discretion of the OS, notifications will stop firing. Notifications firing is critical to the app, so surely this can’t be the strategy?

Remote notifications. Would work but won’t work offline.


问:
MUI5 Table Cell and Column Width
I am using a MUI5 React table and have a hard time figuring out how to adjust the column and cell width. The table needs to span 100% but the fields have to stay together and not spread out automatically like they are doing now. Ideally, I need to set the width of the cell to the width of the content, or at least to a fixed width. Here are my components:

```<code>const StyledTableCell = styled(TableCell)(({ theme }) => ({
  height: "44px",
  padding: "5px 12px",

  [`&.${tableCellClasses.head}`]: {
    color: theme.palette.gray.main,
    fontWeight: 700,
    fontSize: "12px",
    lineHeight: "14px",
    height: "20px",
  },
  [`&.${tableCellClasses.body}`]: {
    fontWeight: 400,
    fontSize: "13px",
    color: theme.palette.darkGray.main,
  },
}));

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  "&:nth-of-type(even)": {
    backgroundColor: theme.palette.action.hover,
  },
  border: 0,
}));

function DataTable({data}) {
   function createData(fields) {
    const res = { ...fields };
    return res;
  }

  const rows = data.map((el) => {
    return createData(el);
  });

  return (
    <TableContainer sx={{ width: "100%", marginBottom: "25px" }}>
      <Table
        sx={{
          [`& .${tableCellClasses.root}`]: {
            borderBottom: "none",
          },
        }}
      >
        <TableHead>
          <TableRow>
            {SectionTitles.container.fields.map((field, index) => {
              return (
                <StyledTableCell key={index} align="left">
                {field}
                </StyledTableCell>
              );
            })}
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row, index) => (
            <StyledTableRow key={index}>
              {Object.keys(row).map((el, index) => {
                return (
                  <StyledTableCell key={index} align="left">
                    {row[el]}
                  </StyledTableCell>
                );
              })}
            </StyledTableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}
</code>```

I have tried setting the width in the styled components and tried to set it in sx as well but nothing is working, the columns still spread out. I have explored pretty much every solution I could find on SO and on google and nothing is making it change the width.

Title: MUI5 Table Cell and Column Width

Body:
I am using a MUI5 React table and have a hard time figuring out how to adjust the column and cell width. The table needs to span 100% but the fields have to stay together and not spread out automatically like they are doing now. Ideally, I need to set the width of the cell to the width of the content, or at least to a fixed width. Here are my components:

const StyledTableCell = styled(TableCell)(({ theme }) => ({
  height: "44px",
  padding: "5px 12px",

  [`&.${tableCellClasses.head}`]: {
    color: theme.palette.gray.main,
    fontWeight: 700,
    fontSize: "12px",
    lineHeight: "14px",
    height: "20px",
  },
  [`&.${tableCellClasses.body}`]: {
    fontWeight: 400,
    fontSize: "13px",
    color: theme.palette.darkGray.main,
  },
}));

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  "&:nth-of-type(even)": {
    backgroundColor: theme.palette.action.hover,
  },
  border: 0,
}));

function DataTable({data}) {
   function createData(fields) {
    const res = { ...fields };
    return res;
  }

  const rows = data.map((el) => {
    return createData(el);
  });

  return (
    <TableContainer sx={{ width: "100%", marginBottom: "25px" }}>
      <Table
        sx={{
          [`& .${tableCellClasses.root}`]: {
            borderBottom: "none",
          },
        }}
      >
        <TableHead>
          <TableRow>
            {SectionTitles.container.fields.map((field, index) => {
              return (

              );
            })}
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row, index) => (

                );
              })}
            </StyledTableRow>
          ))}
        </TableBody>

    </TableContainer>
  );
}

I have tried setting the width in the styled components and tried to set it in sx as well but nothing is working, the columns still spread out. I have explored pretty much every solution I could find on SO and on google and nothing is making it change the width.


问:
How do I verify a self-signed server's TLS certificate in a OpenSSL C client application?
I write a C program using OpenSSL to connect to (my) server using TLS.

The server has a self-signed certificate. How do I tell the client application to accept this?


问:
Unexpected result of `train_function` (Empty logs). Please use `Model.compile(, run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)`
classifier.add(Conv2D(32, (3, 3), input_shape = (150, 150, 3), activation = 'relu'))

classifier.add(MaxPooling2D(pool_size = (2,2)))

classifier.add(Conv2D(32, (3, 3), activation = 'relu'))

classifier.add(MaxPooling2D(pool_size = (2,2)))

classifier.add(Conv2D(64, (3, 3), activation = 'relu'))

classifier.add(MaxPooling2D(pool_size = (2,2)))

I'm trying to make food detection system using CNN


问:
Redhat shell script - OpenSSL x509
I am relatively new to scripting and would like to know how I can add more options in my for loop. Currently my script only checks the -enddate of a certificate, but I would like to get more information like: -serial, -subject, -issuer in a orderly output.

What I have currently is:

```<code>#! /bin/bash

FOLDER_LIST=/etc/httpd/certs

for FOLDER in $FOLDER_LIST
do
  for pem in $FOLDER/*.crt; do
    printf '%s: %s\n' \
      "$(date --date="$(openssl x509 -enddate -noout -in "$pem" | cut -d= -f 2)" --iso-8601)" \
      "$pem"
  done | sort
done

</code>```

I tried adding the extra options like this: "$(openssl x509 -enddate -subject -serial -issuer -noout -in "$pem" | cut -d= -f 2)" --iso-8601)"

But the output is not orderly.

Title: Redhat shell script - OpenSSL x509

Body:
I am relatively new to scripting and would like to know how I can add more options in my for loop. Currently my script only checks the -enddate of a certificate, but I would like to get more information like: -serial, -subject, -issuer in a orderly output.

What I have currently is:

#! /bin/bash

FOLDER_LIST=/etc/httpd/certs

for FOLDER in $FOLDER_LIST
do
  for pem in $FOLDER/*.crt; do
    printf '%s: %s\n' \
      "$(date --date="$(openssl x509 -enddate -noout -in "$pem" | cut -d= -f 2)" --iso-8601)" \
      "$pem"
  done | sort
done

I tried adding the extra options like this: "$(openssl x509 -enddate -subject -serial -issuer -noout -in "$pem" | cut -d= -f 2)" --iso-8601)"

But the output is not orderly.


问:
Is there any way to delay Async NIO server response in Java?
Having trouble 'delaying' the response of server, which is passed to client side.

What I'm trying to do is, just make an echoing, asynchronous, Non-blocking server with NIO package.
Then, I want to manually delay the response sent to Client, to confirm that this server handles multiple response, while not blocked by any of its clients, delays observable by naked eyes.

The main server code is :

package AsyncServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import AsyncServer.AsyncHandler.*;

public class AsyncServer {
    int port = 40000;
    public AsyncServer () {}
    public AsyncServer(int port) {this.port = port;}
    protected void start()
    {
        System.out.println("Async Server running at port "+this.port);
        try {
            AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();
            server.bind(new InetSocketAddress(this.port));
            AcceptCompletionHandler ach = new AcceptCompletionHandler(server);
            server.accept(null, ach);
            System.in.read();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
```
<pre class="lang-java prettyprint-override"><code>package AsyncServer.AsyncHandler;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Void> {
    private final AsynchronousServerSocketChannel ssc;
    public AcceptCompletionHandler(AsynchronousServerSocketChannel in_ssc) {
        this.ssc = in_ssc;
    }
    @Override
    public void completed (AsynchronousSocketChannel sc, Void attachment) {

        /*
        This context was used in attempt to delay response sent to async client.
        Does not work properly, only delaying server console output
        try {
            int amount = (int) (Math.random() * 20);
            Thread.sleep(amount*1000);
            System.out.println("slept for "+amount);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        */
        ssc.accept(null, this);
        System.out.println("Connection Established");
        ByteBuffer buffer = ByteBuffer.allocate(512);
        ReadCompletionHandler rch = new ReadCompletionHandler(sc, buffer);
        sc.read(buffer, null, rch);
        //System.out.println("Received "+buffer.toString());
    }

    @Override
    public void failed (Throwable T, Void attachment){
        T.printStackTrace();
    }
}
</code>```

package AsyncServer.AsyncHandler;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.*;

public class ReadCompletionHandler implements CompletionHandler<Integer, Void> {
        private final AsynchronousSocketChannel sc;
        private final ByteBuffer buffer;

    ReadCompletionHandler (AsynchronousSocketChannel in_sc, ByteBuffer in_buffer) {
        this.sc = in_sc;
        this.buffer = in_buffer;
    }

    @Override
    public void completed (Integer bytes, Void attachment) {

        WriteCompletionHandler wch = new WriteCompletionHandler(this.sc);

        this.buffer.flip();
        this.sc.write(this.buffer, null, wch);
        Charset charset = Charset.forName("UTF-8");
        String outputStr = new String(this.buffer.array()).trim();
        System.out.println("Writing "+outputStr+" into return buffer");

    }

    @Override
    public void failed (Throwable T, Void attachment) {
        T.printStackTrace();
    }
}

```
<pre class="lang-java prettyprint-override"><code>package AsyncServer.AsyncHandler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class WriteCompletionHandler implements CompletionHandler<Integer, Void> {
    private final AsynchronousSocketChannel sc;

    WriteCompletionHandler (AsynchronousSocketChannel in_sc) {
        this.sc = in_sc;
    }

    @Override
    public void completed (Integer bytes, Void attachment) {
        try {
            sc.close();
            System.out.println("Socket closed");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void failed (Throwable T, Void attachment) {
        T.printStackTrace();
    }
}

</code>```

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AsyncClient {

    private String ip = "localhost";
    private int port = 40000;
    private String payload = "00209999997778222223";
    AsyncClient(String in_ip, int in_port, String in_payload)
    {
        this.ip = in_ip;
        this.port = in_port;
        this.payload = in_payload;
    }
    AsyncClient() {}
    void start()
    {
        try {
            AsynchronousSocketChannel sc = AsynchronousSocketChannel.open();
            SocketAddress serverAddr = new InetSocketAddress(this.ip, this.port);
            Future<Void> res = sc.connect(serverAddr);
            System.out.println("Will connect to remote");

            res.get();
            System.out.println("Connection Established");

            String outStr = this.payload;
            ByteBuffer buffer = ByteBuffer.wrap(outStr.getBytes());
            Future<Integer> sender = sc.write(buffer);
            sender.get();

            buffer.flip();
            Future<Integer> receiver = sc.read(buffer);
            System.out.println("Received : "+new String(buffer.array()).trim());
            receiver.get();
            buffer.clear();

        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
```

Client Code components are also available in here.

So this code calls on Custom completionHandler three times.

Control flow goes to AcceptCompletionHandler -> ReadCompletionHandler -> WriteCompletionHandler, when each accept, read, write is called.

As I mentioned earlier, what I wanted to achieve was delaying whole asynchronous receive-response stream of each client thread. By running Client code on multiple threads, Say, some delays 11s, other delay less than 10s, my bare eye could catch this asynchronous operation.

However, If I run multiple threads of AsyncClient, It appears that no delay happens. Almost Instantly, the response arrives at client side. However, delays are really delaying console output of server side. Like this one. Sorry for missing timestamps!

I added semaphore acquire&release to server object itself, wrap delay syntax with semaphore acquire&release. It seems that asyncSocketStream passes their work to any other Idle thread if it meets delay. So I wrapped whole server in ExecutorService package, limiting maximum thread to one. Still, the client gets its reponse right away, and meaningless waiting of server console output happens...

Please enlighten me if I'm doing what is very bad, since I'm new to Async socket programming.

Body:
Having trouble 'delaying' the response of server, which is passed to client side.

What I'm trying to do is, just make an echoing, asynchronous, Non-blocking server with NIO package.
Then, I want to manually delay the response sent to Client, to confirm that this server handles multiple response, while not blocked by any of its clients, delays observable by naked eyes.

The main server code is :

package AsyncServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import AsyncServer.AsyncHandler.*;

public class AsyncServer {
    int port = 40000;
    public AsyncServer () {}
    public AsyncServer(int port) {this.port = port;}
    protected void start()
    {
        System.out.println("Async Server running at port "+this.port);
        try {
            AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();
            server.bind(new InetSocketAddress(this.port));
            AcceptCompletionHandler ach = new AcceptCompletionHandler(server);
            server.accept(null, ach);
            System.in.read();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

package AsyncServer.AsyncHandler;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Void> {
    private final AsynchronousServerSocketChannel ssc;
    public AcceptCompletionHandler(AsynchronousServerSocketChannel in_ssc) {
        this.ssc = in_ssc;
    }
    @Override
    public void completed (AsynchronousSocketChannel sc, Void attachment) {

        /*
        This context was used in attempt to delay response sent to async client.
        Does not work properly, only delaying server console output
        try {
            int amount = (int) (Math.random() * 20);
            Thread.sleep(amount*1000);
            System.out.println("slept for "+amount);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        */
        ssc.accept(null, this);
        System.out.println("Connection Established");
        ByteBuffer buffer = ByteBuffer.allocate(512);
        ReadCompletionHandler rch = new ReadCompletionHandler(sc, buffer);
        sc.read(buffer, null, rch);
        //System.out.println("Received "+buffer.toString());
    }

    @Override
    public void failed (Throwable T, Void attachment){
        T.printStackTrace();
    }
}

package AsyncServer.AsyncHandler;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.*;

public class ReadCompletionHandler implements CompletionHandler<Integer, Void> {
        private final AsynchronousSocketChannel sc;
        private final ByteBuffer buffer;

    ReadCompletionHandler (AsynchronousSocketChannel in_sc, ByteBuffer in_buffer) {
        this.sc = in_sc;
        this.buffer = in_buffer;
    }

    @Override
    public void completed (Integer bytes, Void attachment) {

        WriteCompletionHandler wch = new WriteCompletionHandler(this.sc);

        this.buffer.flip();
        this.sc.write(this.buffer, null, wch);
        Charset charset = Charset.forName("UTF-8");
        String outputStr = new String(this.buffer.array()).trim();
        System.out.println("Writing "+outputStr+" into return buffer");

    }

    @Override
    public void failed (Throwable T, Void attachment) {
        T.printStackTrace();
    }
}

package AsyncServer.AsyncHandler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class WriteCompletionHandler implements CompletionHandler<Integer, Void> {
    private final AsynchronousSocketChannel sc;

    WriteCompletionHandler (AsynchronousSocketChannel in_sc) {
        this.sc = in_sc;
    }

    @Override
    public void completed (Integer bytes, Void attachment) {
        try {
            sc.close();
            System.out.println("Socket closed");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void failed (Throwable T, Void attachment) {
        T.printStackTrace();
    }
}

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AsyncClient {

    private String ip = "localhost";
    private int port = 40000;
    private String payload = "00209999997778222223";
    AsyncClient(String in_ip, int in_port, String in_payload)
    {
        this.ip = in_ip;
        this.port = in_port;
        this.payload = in_payload;
    }
    AsyncClient() {}
    void start()
    {
        try {
            AsynchronousSocketChannel sc = AsynchronousSocketChannel.open();
            SocketAddress serverAddr = new InetSocketAddress(this.ip, this.port);
            Future<Void> res = sc.connect(serverAddr);
            System.out.println("Will connect to remote");

            res.get();
            System.out.println("Connection Established");

            String outStr = this.payload;
            ByteBuffer buffer = ByteBuffer.wrap(outStr.getBytes());
            Future<Integer> sender = sc.write(buffer);
            sender.get();

            buffer.flip();
            Future<Integer> receiver = sc.read(buffer);
            System.out.println("Received : "+new String(buffer.array()).trim());
            receiver.get();
            buffer.clear();

        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

Client Code components are also available in here.

So this code calls on Custom completionHandler three times.

Control flow goes to AcceptCompletionHandler -> ReadCompletionHandler -> WriteCompletionHandler, when each accept, read, write is called.

As I mentioned earlier, what I wanted to achieve was delaying whole asynchronous receive-response stream of each client thread. By running Client code on multiple threads, Say, some delays 11s, other delay less than 10s, my bare eye could catch this asynchronous operation.

However, If I run multiple threads of AsyncClient, It appears that no delay happens. Almost Instantly, the response arrives at client side. However, delays are really delaying console output of server side. Like this one. Sorry for missing timestamps!

I added semaphore acquire&release to server object itself, wrap delay syntax with semaphore acquire&release. It seems that asyncSocketStream passes their work to any other Idle thread if it meets delay. So I wrapped whole server in ExecutorService package, limiting maximum thread to one. Still, the client gets its reponse right away, and meaningless waiting of server console output happens...

Please enlighten me if I'm doing what is very bad, since I'm new to Async socket programming.


问:
How do I generate Touch Events in Windows 7 with C#?
In the past I've used the p/invoke SendInput function to generate keyboard and mouse events but apparently touch is a whole new beast. Is there any way in Windows 7 that I can generate a touch event with C#? </p>

ContentLicense: CC BY-SA 3.0


问:
Count total rows in last row when the last row will not be known
I have some data which once has gone through some additional vba changes I need to count how many rows now remain. The count will always need to go in the very last row, offset 1 for column B, but as I dont know how many records to expect I dont think I can use the R1C1 formula method, does anyone have a better solution?

This is what I am currently attempting to write:

```<code>'Create new count after remove error rows
    Range("B1").End(xlDown).Select
    ActiveCell.WorksheetFunction.CountA (Range("B2").End(xlDown))
</code>```

Body:
I have some data which once has gone through some additional vba changes I need to count how many rows now remain. The count will always need to go in the very last row, offset 1 for column B, but as I dont know how many records to expect I dont think I can use the R1C1 formula method, does anyone have a better solution?

This is what I am currently attempting to write:

'Create new count after remove error rows
    Range("B1").End(xlDown).Select
    ActiveCell.WorksheetFunction.CountA (Range("B2").End(xlDown))


问:
Quasar Error Reading External Library Component
I have installed an external library (vuejs-progress-bar) in Quasar and I'm getting an error which says:

```<code>boot error: TypeError: Cannot read properties of undefined (reading 'component')
</code>```

I'm not quite sure what went wrong, here's what I did in my boot file:

```<code>import { boot } from "quasar/wrappers";

import { ProgressBar } from "vuejs-progress-bar";

export default boot(async ({ app }) => {
  app.use(ProgressBar);
});
</code>```

here's my progress-bar code (I followed from their docs https://github.com/larsmars/vuejs-progress-bar):

```<code><progress-bar :options="options" value="0" />
</code>```

script:

```<code>export default {
  data() {
    return {

      options: {
        text: {
          color: "#FFFFFF",
          shadowEnable: true,
          shadowColor: "#000000",
          fontSize: 14,
          fontFamily: "Helvetica",
          dynamicPosition: false,
          hideText: false,
        },
        progress: {
          color: "#2dbd2d",
          backgroundColor: "#333333",
          inverted: false,
        },
        layout: {
          height: 35,
          width: 140,
          verticalTextAlign: 61,
          horizontalTextAlign: 43,
          zeroOffset: 0,
          strokeWidth: 30,
          progressPadding: 0,
          type: "line",
        },
      },
    };
  },

  methods: {},
  created() {},
};
</code>```

Body:
I have installed an external library (vuejs-progress-bar) in Quasar and I'm getting an error which says:

boot error: TypeError: Cannot read properties of undefined (reading 'component')

I'm not quite sure what went wrong, here's what I did in my boot file:

import { boot } from "quasar/wrappers";

import { ProgressBar } from "vuejs-progress-bar";

export default boot(async ({ app }) => {
  app.use(ProgressBar);
});

here's my progress-bar code (I followed from their docs https://github.com/larsmars/vuejs-progress-bar):

<progress-bar :options="options" value="0" />

script:

export default {
  data() {
    return {

      options: {
        text: {
          color: "#FFFFFF",
          shadowEnable: true,
          shadowColor: "#000000",
          fontSize: 14,
          fontFamily: "Helvetica",
          dynamicPosition: false,
          hideText: false,
        },
        progress: {
          color: "#2dbd2d",
          backgroundColor: "#333333",
          inverted: false,
        },
        layout: {
          height: 35,
          width: 140,
          verticalTextAlign: 61,
          horizontalTextAlign: 43,
          zeroOffset: 0,
          strokeWidth: 30,
          progressPadding: 0,
          type: "line",
        },
      },
    };
  },

  methods: {},
  created() {},
};


问:
angular generic type inside standalone component
Dynamic icon standalone component

I try to create dynamic icon component that at any module fill with a new set of assets.
I want to send it new enum and get appropriate input type intelligence.

import { CommonModule } from '@angular/common';
import { Component, Input } from '@angular/core';

type StandardEnum = object;

@Component({
  selector: 'fnx-nx-client-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],
  standalone: true,
  imports: [CommonModule],
})
export class AppIconComponent<T extends StandardEnum> {
  static iconClass?: StandardEnum;
  @Input() iconName: keyof T;
  @Input() disabled: boolean;
  get iconClass(): T {
    return AppIconComponent.iconClass as T;
  }
  public static forRoot(
    iconEnum?: U
  ): typeof AppIconComponent {
    AppIconComponent.iconClass = iconEnum;
    return this;
  }
}

```
<p>The component write as expected
When useing in app module the below error appear</p>
<pre class="lang-js prettyprint-override"><code>enum myEnum {
  ONE = 1,
}

@NgModule({
  imports: [
    AppIconComponent.forRoot<myEnum>(myEnum),
 ]
}) export class AppModule {}
</code>```

error :

```<code>    new (): AppIconComponent<typeof t>;
    prototype: AppIconComponent<any>;
    iconClass?: object;
    forRoot<U extends object>(iconEnum?: U): {
        ...;
    };
}
Value at position 0 in the NgModule.imports of AppModule is not a reference
  Value could not be determined statically.(-991010)
app.module.ts(16, 5): Unable to evaluate function call of complex function. A function must have exactly one return statement.
test.component.ts(17, 2): Function is declared here.
</code>```

Body:
Dynamic icon standalone component

I try to create dynamic icon component that at any module fill with a new set of assets.
I want to send it new enum and get appropriate input type intelligence.

import { CommonModule } from '@angular/common';
import { Component, Input } from '@angular/core';

type StandardEnum = object;

@Component({
  selector: 'fnx-nx-client-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],
  standalone: true,
  imports: [CommonModule],
})
export class AppIconComponent<T extends StandardEnum> {
  static iconClass?: StandardEnum;
  @Input() iconName: keyof T;
  @Input() disabled: boolean;
  get iconClass(): T {
    return AppIconComponent.iconClass as T;
  }
  public static forRoot(
    iconEnum?: U
  ): typeof AppIconComponent {
    AppIconComponent.iconClass = iconEnum;
    return this;
  }
}

The component write as expected
When useing in app module the below error appear

enum myEnum {
  ONE = 1,
}

@NgModule({
  imports: [
    AppIconComponent.forRoot<myEnum>(myEnum),
 ]
}) export class AppModule {}

error :

    new (): AppIconComponent<typeof t>;
    prototype: AppIconComponent<any>;
    iconClass?: object;
    forRoot(iconEnum?: U): {
        ...;
    };
}
Value at position 0 in the NgModule.imports of AppModule is not a reference
  Value could not be determined statically.(-991010)
app.module.ts(16, 5): Unable to evaluate function call of complex function. A function must have exactly one return statement.
test.component.ts(17, 2): Function is declared here.


问:
GWT MaterialDataTable handle Resize and Horizontal Scroll
on first loadData scrollbar horizontal is visible an working
but as soon as i hit search again to load data + the scroller is hidden invisible (is there some way to always display scrollbars ?)

if i resize the window scrollbar returns to be visible

the Table is in

```<code>    <g:HTMLPanel>
        <div style="clear:both;"></div>
        <m:MaterialPanel>
            <m:table.MaterialDataTable ui:field="table" shadow="1" height="440px"/>
        </m:MaterialPanel>
    </g:HTMLPanel>
</code>```

And the resize 100% Code

```<code>    private void continuousAdaptTableHeight() {
    Timer t = new Timer() {
        @Override
        public void run() {
            if(isInDialog()){
                Integer windowHeight=getMaterialWindow().asWidget().getElement().getClientHeight();
                Integer tableAbsoluteTop = genericListPresenter.getTable().asWidget().getElement().getAbsoluteTop();
                Integer newTableHeight = windowHeight - tableAbsoluteTop-40;
                genericListPresenter.getTable().setHeight(newTableHeight + "px");
            }
            else{
                Integer tableAbsoluteTop = genericListPresenter.getTable().asWidget().getElement().getAbsoluteTop();
                Integer windowHeight= Window.getClientHeight();
                Integer newTableHeight = windowHeight - tableAbsoluteTop-100;
                genericListPresenter.getTable().setHeight(newTableHeight + "px");
            }

        }

    };
    t.scheduleRepeating(200);
}
</code>```

Body:
on first loadData scrollbar horizontal is visible an working
but as soon as i hit search again to load data + the scroller is hidden invisible (is there some way to always display scrollbars ?)

if i resize the window scrollbar returns to be visible

the Table is in

    <g:HTMLPanel>

        <m:MaterialPanel>
            <m:table.MaterialDataTable ui:field="table" shadow="1" height="440px"/>
        </m:MaterialPanel>
    </g:HTMLPanel>

And the resize 100% Code

    private void continuousAdaptTableHeight() {
    Timer t = new Timer() {
        @Override
        public void run() {
            if(isInDialog()){
                Integer windowHeight=getMaterialWindow().asWidget().getElement().getClientHeight();
                Integer tableAbsoluteTop = genericListPresenter.getTable().asWidget().getElement().getAbsoluteTop();
                Integer newTableHeight = windowHeight - tableAbsoluteTop-40;
                genericListPresenter.getTable().setHeight(newTableHeight + "px");
            }
            else{
                Integer tableAbsoluteTop = genericListPresenter.getTable().asWidget().getElement().getAbsoluteTop();
                Integer windowHeight= Window.getClientHeight();
                Integer newTableHeight = windowHeight - tableAbsoluteTop-100;
                genericListPresenter.getTable().setHeight(newTableHeight + "px");
            }

        }

    };
    t.scheduleRepeating(200);
}


问:
MAUI: floating element that transitions across pages
I need to create floating view element that sits on top of the page and transistions between pages.

This quick example: the pink "Paw" button on top of the page, same button on next page.

One option that I found is to use ControlTemplate on ALL pages and append new button each time it is opened. But I want it to be single across pages or attached to my MainPage (FlyoutPage).

My real goal is to make small panel with ongoing call, that shows timer and hang/mute buttons, so user could use application and browse pages and menus, but that panel would be always on top.

Need any advice or best practice.


问:
Rxjs Observable is not updating value correctly
Inside a service which stores the state of a user shoppingcart I have a BehaviorSubject of an Array. This array contains Items that the user has put in his shoppingcart. Each ordered item inside this array contains the quantity, baseprice and the current price (quantity * baseprice).

The user can change the quantity of each item with a +/- button. The State in the BehaviorSubject gets updated according to the selected quantity.

private orderedProducts = new BehaviorSubject<OrderItem[]>([]);

I have writte a method to calculate the current order sum based on the BehaviorSubject like this:

```<code>getOrderSum$(): Observable<number> {
  return this.orderedProducts$.pipe(
    map((orderItems) => orderItems.reduce((accTotal, orderItem) => accTotal + (orderItem.currentPrice), 0)),
    tap((price) => console.log('Current Order Sum', price)));
}
</code>```

I subscribe to this Observable in different parts of the appliction with the async Pipe.
On the firtst subscribe of the stream, the observable behaves as I expected. The tap Operator logs the correct value once and my UI refreshes accordingly.

If I now navigate to a different part of the app (order overview) where I also subscribed with the async Pipe, two values get logged when the user changs the quantity of an item (using +/- button): the current (correct) order sum and then immidiatly after that the old (incorrect) order sum.

I tried to manually subscribe calling the .subscribe() method and then manually unsubscribing from it when the component gets destroyed. This didnt solve the problem and from my understanding the asyncpipe handles automatic sub/unsubbing from observables. Thats why I dont really understand why the value gets logged twice when navigating to the other component and why it always displays the old value.

Additional Info:
The serivce is injected using provideIn: root.

The method that updates the quantity of ordered Items finds the item with the correct ID and then changes the quantity. The new array gets emitted on the BehaviorSubject :

```<code> updateQuantityOfOrderItem(orderItem: OrderItem, quant: number) {
    if (quant >= 1) {
      this.orderedProducts.pipe(
        mergeMap((items) => items),
        filter((itemProd) => itemProd.id === orderItem.id),
        map((item) => {
          item.quantity = quant;
          item.orderItemPrice = item.product.basePrice * quant;
        }),
        distinctUntilChanged()).subscribe(() => this.orderedProducts.next([...this.orderedProducts.value]));
    } else {
      //Delete Product
      this.orderedProducts.pipe(
        take(1),
        map((prod) => prod.filter(p => p.id !== orderItem.id)))
        .subscribe(this.orderedProducts.next.bind(this.orderedProducts));
    }
  }
</code>```

This all works as expected in one component. But when I subscribe to the value in another component on another page the value isnt updated until I completly delete a product from the cart (quantity = 0). Then the value changes to the correct value and doesnt change anymore.

What I dont understand is that when I change the quantity of an item on the page where the calculation isnt working and then navigate back to the other page where it is working. The correct updated value is displayed.

Body:
Inside a service which stores the state of a user shoppingcart I have a BehaviorSubject of an Array. This array contains Items that the user has put in his shoppingcart. Each ordered item inside this array contains the quantity, baseprice and the current price (quantity * baseprice).

The user can change the quantity of each item with a +/- button. The State in the BehaviorSubject gets updated according to the selected quantity.

private orderedProducts = new BehaviorSubject<OrderItem[]>([]);

I have writte a method to calculate the current order sum based on the BehaviorSubject like this:

getOrderSum$(): Observable<number> {
  return this.orderedProducts$.pipe(
    map((orderItems) => orderItems.reduce((accTotal, orderItem) => accTotal + (orderItem.currentPrice), 0)),
    tap((price) => console.log('Current Order Sum', price)));
}

I subscribe to this Observable in different parts of the appliction with the async Pipe.
On the firtst subscribe of the stream, the observable behaves as I expected. The tap Operator logs the correct value once and my UI refreshes accordingly.

If I now navigate to a different part of the app (order overview) where I also subscribed with the async Pipe, two values get logged when the user changs the quantity of an item (using +/- button): the current (correct) order sum and then immidiatly after that the old (incorrect) order sum.

I tried to manually subscribe calling the .subscribe() method and then manually unsubscribing from it when the component gets destroyed. This didnt solve the problem and from my understanding the asyncpipe handles automatic sub/unsubbing from observables. Thats why I dont really understand why the value gets logged twice when navigating to the other component and why it always displays the old value.

Additional Info:
The serivce is injected using provideIn: root.

The method that updates the quantity of ordered Items finds the item with the correct ID and then changes the quantity. The new array gets emitted on the BehaviorSubject :

 updateQuantityOfOrderItem(orderItem: OrderItem, quant: number) {
    if (quant >= 1) {
      this.orderedProducts.pipe(
        mergeMap((items) => items),
        filter((itemProd) => itemProd.id === orderItem.id),
        map((item) => {
          item.quantity = quant;
          item.orderItemPrice = item.product.basePrice * quant;
        }),
        distinctUntilChanged()).subscribe(() => this.orderedProducts.next([...this.orderedProducts.value]));
    } else {
      //Delete Product
      this.orderedProducts.pipe(
        take(1),
        map((prod) => prod.filter(p => p.id !== orderItem.id)))
        .subscribe(this.orderedProducts.next.bind(this.orderedProducts));
    }
  }

This all works as expected in one component. But when I subscribe to the value in another component on another page the value isnt updated until I completly delete a product from the cart (quantity = 0). Then the value changes to the correct value and doesnt change anymore.

What I dont understand is that when I change the quantity of an item on the page where the calculation isnt working and then navigate back to the other page where it is working. The correct updated value is displayed.