问:
Choose one in pair from array and find minimum total
You receive an array of integers and must choose one value from each pair of adjacent values. For example, given {1,0,5} you can pick 1 and 5 or just 0. The goal is to find the minimum total sum you can get from all the chosen values, print it, and print each chosen value from the array.

For example, given {1,0,5} you want to choose 0 since it's the lowest in the pairs (1,0) and (0,5), and the minimum total sum is 0.

Another example: given {10,30,90,50,30} the minimum sum is 30 + 50 = 80 and we made sure that for each pair of adjacent values at least one was chosen (10,30), (30,90), (90,50), (50,30).

I used dynamic programming to find the minimum total sum, but I'm not sure how to print each chosen value to create that sum.

```<code>public static void main(String[] args) {
        // Define the input array
        int[] arr = {50, 30, 40, 60, 10, 30, 10};
        // Define the array to store the minimum sum for each index
        int[] dp = new int[arr.length];
        // Initialize the first element of the dp array
        dp[0] = arr[0];
        dp[1] = arr[1];
        // Loop over the input array from the second index to the last index
        int choice1 = 0, choice2;
        for(int i = 2; i<arr.length; i++) {
            // Choose the previous index and add its minimum sum to the current element
             choice1 = dp[i-1] + arr[i];
            // Choose the index before the previous index and add its minimum sum to the current element
             choice2 = dp[i-2] + arr[i];
            // Compare the two choices and choose the one with the lower sum
             dp[i] = Math.min(choice1, choice2);
        }
        // Print the minimum sum and the chosen values
        if(dp[arr.length - 1] > dp[arr.length - 2]) {
            System.out.println(dp[arr.length - 2]);
        }else {
            System.out.println(dp[arr.length - 1]);
        }
    }
</code>```

Body:
You receive an array of integers and must choose one value from each pair of adjacent values. For example, given {1,0,5} you can pick 1 and 5 or just 0. The goal is to find the minimum total sum you can get from all the chosen values, print it, and print each chosen value from the array.

For example, given {1,0,5} you want to choose 0 since it's the lowest in the pairs (1,0) and (0,5), and the minimum total sum is 0.

Another example: given {10,30,90,50,30} the minimum sum is 30 + 50 = 80 and we made sure that for each pair of adjacent values at least one was chosen (10,30), (30,90), (90,50), (50,30).

I used dynamic programming to find the minimum total sum, but I'm not sure how to print each chosen value to create that sum.

public static void main(String[] args) {
        // Define the input array
        int[] arr = {50, 30, 40, 60, 10, 30, 10};
        // Define the array to store the minimum sum for each index
        int[] dp = new int[arr.length];
        // Initialize the first element of the dp array
        dp[0] = arr[0];
        dp[1] = arr[1];
        // Loop over the input array from the second index to the last index
        int choice1 = 0, choice2;
        for(int i = 2; i<arr.length; i++) {
            // Choose the previous index and add its minimum sum to the current element
             choice1 = dp[i-1] + arr[i];
            // Choose the index before the previous index and add its minimum sum to the current element
             choice2 = dp[i-2] + arr[i];
            // Compare the two choices and choose the one with the lower sum
             dp[i] = Math.min(choice1, choice2);
        }
        // Print the minimum sum and the chosen values
        if(dp[arr.length - 1] > dp[arr.length - 2]) {
            System.out.println(dp[arr.length - 2]);
        }else {
            System.out.println(dp[arr.length - 1]);
        }
    }


来源: stackexchange

问:
How do I pass attributes of first class to another class inside a class
I have a class. Inside this is another class. Inside a function of this class. How can I pass attributes (self) of first class to second class

for example

```<code>class FirstClass():
    def __init__(self, e) -> None:
        self.e = e
        # lots of other attributes...

    def e(self):
        pass

    def App(self):

        class myapp(overview.App):
            def __init__(self) -> None:
                super().__init__()
                self.geometry("450x650")
                print(self.e))

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

print(self.e) one of the attributes of the first class. How do I do this?

It is important for me. Thanks.

ContentLicense: CC BY-SA 4.0

Body:
I have a class. Inside this is another class. Inside a function of this class. How can I pass attributes (self) of first class to second class

for example

class FirstClass():
    def __init__(self, e) -> None:
        self.e = e
        # lots of other attributes...

    def e(self):
        pass

    def App(self):

        class myapp(overview.App):
            def __init__(self) -> None:
                super().__init__()
                self.geometry("450x650")
                print(self.e))

        myapp().mainloop()

print(self.e) one of the attributes of the first class. How do I do this?

It is important for me. Thanks.


问:
NestJs return entity defined with jsonb column as the value of a certain key
I have an entity defined:

```<code>@Entity('my_entity')
export class MyEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column("jsonb")
    title: object;
}
</code>```

My Controller defined:

```<code>@Get(':id')
async getEntity(@Param('id') id: string, @Headers('Accept-Language') locale: string) {
    return this.myEntityService.get(id);
}
</code>```

My service defined:

```<code>async get(id) {
    return await this.myEntityRepository.findOne(id);
}
</code>```

The result is:

{"id": 1, "title": { "en": "home", "sp": "casa",....}}

I want to return the value of the title according to the locale
For example: receiving locale "en":

{"id": 1, title": "home"}

What is the right way to perform the transformation?
Thanks

Body:
I have an entity defined:

@Entity('my_entity')
export class MyEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column("jsonb")
    title: object;
}

My Controller defined:

@Get(':id')
async getEntity(@Param('id') id: string, @Headers('Accept-Language') locale: string) {
    return this.myEntityService.get(id);
}

My service defined:

async get(id) {
    return await this.myEntityRepository.findOne(id);
}

The result is:

{"id": 1, "title": { "en": "home", "sp": "casa",....}}

I want to return the value of the title according to the locale
For example: receiving locale "en":

{"id": 1, title": "home"}

What is the right way to perform the transformation?
Thanks


问:
is there anyway to change PHP Basic authentication text?

Can I change or edit the link area?

I couldn't find a solution directly with PHP.


问:
How to fix : Domain does not resolve to the GitHub Pages server. For more information (NotServedByPagesError)
So I am trying to setup a custom domain with my github pages site. I have followed the steps as in Github Docs. I am using Freenom for the domain.

I have added the A record to my DNS records at the registrar pointing to all of the four IP addresses

I have added the CNAME record

and I have checked them too

but I am still getting this error

UPDATE: it just loads into a white screen now

My site link is https://xharuke.github.io/haruke/ and not https://xharuke.github.io is that what might be causing the problem?


问:
Tkinter window not closing until python program ends
I got a behavior that I don't understand in my test program;

I'm using tkinter to display a window that show some radio box, and sent back the value to the python program that will continue to execute.

But I've noticed that after the Tkwindow is asked to close with a destroy() command :

IF the following of my code is asking an input() the window is closing as requested,
BUT if the following of my code continue to execute without any user input, the window will not close until all the code ends.

the code after the maintop is basically some selenium based code that fills an online webpage.

But as I wrote earlier, if I ask an input() (after the maintop here), the window does close, but if I don't ak an input and let the code with selenium fills a webpage, the window will not close until the webpage fills (and it can take some times as it has multiple pages calls.)

```<code>def Close():
    window.destroy()
    window.quit()
def selection():
    global bsiInput
    bsiInput=str(value.get())

window = Tk()
window.geometry("350x350")
value = StringVar()

label = Label(window, text="Choose :   ")
bouton1 = Radiobutton(window, text="   A   ", variable=value, value='a',command=selection)
bouton2 = Radiobutton(window, text="   B   "  , variable=value, value='b',command=selection)
boutonOk = Button(window, text="Valider", command=Close)
label.pack()
bouton1.pack()
bouton2.pack()
boutonOk.pack()

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

Edit: I try both remarks suggested:
So, as I tried what you both suggest, I defines all my code in a MainProgram function.To be clear I just put a print("closed") after the mainloop(), and in my MainProgram() I start it with a print("prog starts"), from there:

```<code>def Close():
    window.destroy()
    window.after(0,MainProgram)
</code>```

//outputs "closed" and end program as if MainProgram is never called

```<code>def Close():
    window.destroy()
...
window.mainloop()
window.after(0,MainProgram)
</code>```

//outputs "closed" and end programs as if MainProgram is never called

and

```<code>window.mainloop()
MainProgram()
</code>```

//outputs "closed""prog starts" but don't close the window until the end of the program

Body:
I got a behavior that I don't understand in my test program;

I'm using tkinter to display a window that show some radio box, and sent back the value to the python program that will continue to execute.

But I've noticed that after the Tkwindow is asked to close with a destroy() command :

IF the following of my code is asking an input() the window is closing as requested,
BUT if the following of my code continue to execute without any user input, the window will not close until all the code ends.

the code after the maintop is basically some selenium based code that fills an online webpage.

But as I wrote earlier, if I ask an input() (after the maintop here), the window does close, but if I don't ak an input and let the code with selenium fills a webpage, the window will not close until the webpage fills (and it can take some times as it has multiple pages calls.)

def Close():
    window.destroy()
    window.quit()
def selection():
    global bsiInput
    bsiInput=str(value.get())

window = Tk()
window.geometry("350x350")
value = StringVar()

label = Label(window, text="Choose :   ")
bouton1 = Radiobutton(window, text="   A   ", variable=value, value='a',command=selection)
bouton2 = Radiobutton(window, text="   B   "  , variable=value, value='b',command=selection)
boutonOk = Button(window, text="Valider", command=Close)
label.pack()
bouton1.pack()
bouton2.pack()
boutonOk.pack()

window.mainloop()

Edit: I try both remarks suggested:
So, as I tried what you both suggest, I defines all my code in a MainProgram function.To be clear I just put a print("closed") after the mainloop(), and in my MainProgram() I start it with a print("prog starts"), from there:

def Close():
    window.destroy()
    window.after(0,MainProgram)

//outputs "closed" and end program as if MainProgram is never called

def Close():
    window.destroy()
...
window.mainloop()
window.after(0,MainProgram)

//outputs "closed" and end programs as if MainProgram is never called

and

window.mainloop()
MainProgram()

//outputs "closed""prog starts" but don't close the window until the end of the program


问:
Amazon lightsail container service ssh
Is it possible to gain ssh access to an amazon lightsail container service? I have some containers running properly, but it would be great to have ssh access to either the individual containers (I have nginx and a php application running in separate containers) or the container service machine itself.</p>

Title: Amazon lightsail container service ssh


问:
connection fail for the jupyter notebook
I am trying to connect to my project in jyputer notebook. However, it pop up connection failed.
So far I have reinstall the whole anaconda, but it doesn't work.

This is the application launch error I also received


问:
Implementation for ar_flutter_plugin 0.7.3 in flutter android in flutter version 3.3.9 null safety
Need help for implementation of ar_flutter_plugin in Flutter version 3.3.9 ??

https://pub.dev/packages/ar_flutter_plugin


问:
403 Forbidden media file django, nginx, aws
The images are not displayed in my project. If the static files.

This is how my nginx configuration looks

```<code>

    server{
    listen 80;
    server_name domain;

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static/ {
    autoindex on;
    alias /var/www/html/static/;
    }

    location /media/ {
    autoindex on;
    alias /home/user/project/var/www/html/media;
    }

    location / {
        include proxy_params;
        proxy_pass http://ip:8000;

    }

</code>```

my settings.py

```<code>
    DEBUG = False

    MEDIA_ROOT ='var/www/html/media'
    MEDIA_URL = '/media/'

</code>```

the permmission this path: /home/user/project/var/www/html/media

```<code>drwxrwxr-x  3 www-data  www-data
</code>```

I need the images to be displayed to the user or other solutions with other services with aws.

Body:
The images are not displayed in my project. If the static files.

This is how my nginx configuration looks

    server{
    listen 80;
    server_name domain;

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static/ {
    autoindex on;
    alias /var/www/html/static/;
    }

    location /media/ {
    autoindex on;
    alias /home/user/project/var/www/html/media;
    }

    location / {
        include proxy_params;
        proxy_pass http://ip:8000;

    }

my settings.py

    DEBUG = False

    MEDIA_ROOT ='var/www/html/media'
    MEDIA_URL = '/media/'

the permmission this path: /home/user/project/var/www/html/media

drwxrwxr-x  3 www-data  www-data

I need the images to be displayed to the user or other solutions with other services with aws.


问:
pcmanfm-qt place multiple custom actions in one custom action file
NOTE: This relates to pcmanfm-qt not pcmanfm but I don't have enough rep to create the pcmanfm-qt tag.

I use kdesvn for my svn work which in addition to providing a gui interface to svn, also provides a kde custom action that contains multiple context menu items.

That custom action works in Dolphin, but it does not work in pcmanfm-qt which sucks as I use that as my main fm.

So I want to create a custom action to do the same thing but for pcmanfm-qt.

I've struggled to work out how, and now have managed to create a custom action that contains two sub menu items which point to separate custom actions, and that solution works.

However the original kdesvn context menu that works for Dolphin contains all the sub menu items in one custom action file which is a lot easier to maintain, but I cannot work out how to do that for my pcmanfm-qt custom action.

So this is what I have so far, the first custom action contains the context menu item and links to the two sub menu item custom actions.

This is the main custom action called my-context-menu.desktop

```<code>[Desktop Entry]
Type=Menu
Name[en]=KDESVN
Comment=This is my context menu
Icon=utilities-terminal
ItemsList=my-context-sub-one;my-context-sub-two
</code>```

It is the ItemsList entry that points to the sub menu items which have to be in their own custom action files, such as my-context-sub-two.desktop which contains this content

```<code>[Desktop Entry]
Type=Action
Name[en]=kdesvn info
Comment=Performs svn info
Icon=kdesvninfo
Profiles=profile-zero;

[X-Action-Profile profile-zero]
Exec=kdesvn exec info %U
</code>```

So my question is how can I combine the content of all the sub menu custom actions like my-context-sub-two.desktop in the main custom action my-context-menu.desktop, so I only have one file to maintain?

Body:
NOTE: This relates to pcmanfm-qt not pcmanfm but I don't have enough rep to create the pcmanfm-qt tag.

I use kdesvn for my svn work which in addition to providing a gui interface to svn, also provides a kde custom action that contains multiple context menu items.

That custom action works in Dolphin, but it does not work in pcmanfm-qt which sucks as I use that as my main fm.

So I want to create a custom action to do the same thing but for pcmanfm-qt.

I've struggled to work out how, and now have managed to create a custom action that contains two sub menu items which point to separate custom actions, and that solution works.

However the original kdesvn context menu that works for Dolphin contains all the sub menu items in one custom action file which is a lot easier to maintain, but I cannot work out how to do that for my pcmanfm-qt custom action.

So this is what I have so far, the first custom action contains the context menu item and links to the two sub menu item custom actions.

This is the main custom action called my-context-menu.desktop

[Desktop Entry]
Type=Menu
Name[en]=KDESVN
Comment=This is my context menu
Icon=utilities-terminal
ItemsList=my-context-sub-one;my-context-sub-two

It is the ItemsList entry that points to the sub menu items which have to be in their own custom action files, such as my-context-sub-two.desktop which contains this content

[Desktop Entry]
Type=Action
Name[en]=kdesvn info
Comment=Performs svn info
Icon=kdesvninfo
Profiles=profile-zero;

[X-Action-Profile profile-zero]
Exec=kdesvn exec info %U

So my question is how can I combine the content of all the sub menu custom actions like my-context-sub-two.desktop in the main custom action my-context-menu.desktop, so I only have one file to maintain?


问:
How can I invoke python' class dunder method in C?
I'm writing some Python Module using the C extension API. And I want to implement insert() and is_greater() methods.
both methods should take an argument of int type or any user-defined object which has implemented __gt__() method.
To make it simple, need the interface like below.

mc = MyClass()
mc.insert(1)
isGreater = mc.is_greater(2)
```
<pre class="lang-py prettyprint-override"><code>mc = MyClass()
obj1 = MyObject(1)
mc.insert(obj1)
obj2 = MyObject(2)
isGreater = mc.is_greater(obj2)
</code>```

I'm using the PyArg_ParseTuple function to parse the variable into a raw C Pointer　like below.

typedef int(* COMPARE_FUNCP)(PyObject * , PyObject * );

typedef struct
{
    PyObject_HEAD
    PyObject * objp;
    COMPARE_FUNCP * is_greater;
} MyClassObject;

static PyObject *
myClass_insert(MyClassObject * self, PyObject * args)
{
    PyObject * objp1;
    if (!PyArg_ParseTuple(args, "O", &objp1))
    {
        return NULL;
    }
    self->objp = objp1;
    // here I want to register MyObject class's __gt__() method.
    self->is_greater =
}

static PyObject *
myClass_compare(MyClassObject * self, PyObject * args)
{
    PyObject * objp2;
    if (!PyArg_ParseTuple(args, "O", &objp2))
    {
        return NULL;
    }
    if (self->is_greater(self->objp, objp2)>0)
        return Py_True;
}

```

I guess I need to register __gt__() method in C somehow, but How can I do this?

Someone please give me a clue. Thank you.

Body:
I'm writing some Python Module using the C extension API. And I want to implement insert() and is_greater() methods.
both methods should take an argument of int type or any user-defined object which has implemented __gt__() method.
To make it simple, need the interface like below.

mc = MyClass()
mc.insert(1)
isGreater = mc.is_greater(2)

mc = MyClass()
obj1 = MyObject(1)
mc.insert(obj1)
obj2 = MyObject(2)
isGreater = mc.is_greater(obj2)

I'm using the PyArg_ParseTuple function to parse the variable into a raw C Pointer　like below.

typedef int(* COMPARE_FUNCP)(PyObject * , PyObject * );

typedef struct
{
    PyObject_HEAD
    PyObject * objp;
    COMPARE_FUNCP * is_greater;
} MyClassObject;

static PyObject *
myClass_insert(MyClassObject * self, PyObject * args)
{
    PyObject * objp1;
    if (!PyArg_ParseTuple(args, "O", &objp1))
    {
        return NULL;
    }
    self->objp = objp1;
    // here I want to register MyObject class's __gt__() method.
    self->is_greater =
}

static PyObject *
myClass_compare(MyClassObject * self, PyObject * args)
{
    PyObject * objp2;
    if (!PyArg_ParseTuple(args, "O", &objp2))
    {
        return NULL;
    }
    if (self->is_greater(self->objp, objp2)>0)
        return Py_True;
}

I guess I need to register __gt__() method in C somehow, but How can I do this?

Someone please give me a clue. Thank you.


问:
auto generate same column in 4 tables using hibernate
I have an event table with four columns. there is one column named event_id. it is auto-generating in the entry table. when I create an event the data populates in 4 tables. rest three tables have also the event_id column. I want the rest three tables to auto-generate the same value from the event table. is that possible?  I have defined the ManyToMany relationship to the rest three tables with the event table. I want the same value should also generate in rest three tables.</p>


问:
MetroLog in Maui app - be able to provide custom log name
MetroLog generates the log name of its own in my android app, something like 'Log - 20221211'. But I want to rename to something else that would contain the user name who is logged in, something like 'Log - 20221211-tim' for 'Tim' or 'Log - 20221211-donald' for 'Donald'. How can I do that.

in MauiProgram.cs, I added below line, but here you can add only the folder path, not the file name.

```<code>            builder.Logging
            .AddStreamingFileLogger(options =>
            {
                options.MinLevel = Microsoft.Extensions.Logging.LogLevel.Information;
                options.MaxLevel = Microsoft.Extensions.Logging.LogLevel.Critical;
                options.FolderPath = Android.OS.Environment.ExternalStorageDirectory + "/Android/data/com.companyname.salestracking/files/Logs";
            });
</code>```

Body:
MetroLog generates the log name of its own in my android app, something like 'Log - 20221211'. But I want to rename to something else that would contain the user name who is logged in, something like 'Log - 20221211-tim' for 'Tim' or 'Log - 20221211-donald' for 'Donald'. How can I do that.

in MauiProgram.cs, I added below line, but here you can add only the folder path, not the file name.

            builder.Logging
            .AddStreamingFileLogger(options =>
            {
                options.MinLevel = Microsoft.Extensions.Logging.LogLevel.Information;
                options.MaxLevel = Microsoft.Extensions.Logging.LogLevel.Critical;
                options.FolderPath = Android.OS.Environment.ExternalStorageDirectory + "/Android/data/com.companyname.salestracking/files/Logs";
            });


问:
Don't know how to read XML values description
In the XML values description for specific elements,
I received description of what possible values can exists there:
0;1,
1:n,
0.1,
0..1,
0...1,
0..n,

What do they mean?
Sometimes there are three 'dots' between, sometimes two or one dot.
Is semicolon the same as dot?
What is 'n'? Is it any natural number?

It is confusing to me. Seems like there is some mistake when it comes to amount of dots.


问:
Visual Studio - code not being recognised after system clock change
I made some code changes in Visual Studio after setting my system clock forward a week.

After changing the clock back, the recent code is now not recognized as VS seems to think there is newer code and will not reflect changes.

Any way to tidy this up?


问:
Python ‘numpy.ndarray’ object is not callable Solution
I'm doing a simple linear regression task for predicting house prices, using RMSE, with the following code

```<code># A function that take one input of the dataset and return the RMSE (of the test data), and the intercept and coefficient
def simple_linear_model(train, test, input_feature):
    regr = linear_model.LinearRegression() # Create a linear regression object
    regr.fit(train.values(columns = [input_feature]), train.as_matrix(columns = ['Price'])) # Train the model
    RMSE = mean_squared_error(test.values(columns = ['Price']),
                              regr.predict(test.values(columns = [input_feature])))**0.5 # Calculate the RMSE on test data
    return RMSE, regr.intercept_[0], regr.coef_[0][0]

input_list = data.columns.values.tolist() # list of column name
input_list.remove('Price')
simple_linear_result = pd.DataFrame(columns = ['feature', 'RMSE', 'intercept', 'coefficient'])

# loop that calculate the RMSE of the test data for each input

for p in input_list:
    RMSE, w1, w0 = simple_linear_model(train_data, test_data, p)
    simple_linear_result = simple_linear_result.append({'feature':p, 'RMSE':RMSE, 'intercept':w0, 'coefficient': w1}
                                                       ,ignore_index=True)
simple_linear_result.sort_values('RMSE').head(10) # display the 10 best estimators

</code>```

This error is coming:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [12], in <cell line: 6>()
      5 # loop that calculate the RMSE of the test data for each input
      6 for p in input_list:
----> 7     RMSE, w1, w0 = simple_linear_model(train_data, test_data, p)
      8     simple_linear_result = simple_linear_result.append({'feature':p, 'RMSE':RMSE, 'intercept':w0, 'coefficient': w1}
      9                                                        ,ignore_index=True)
     10 simple_linear_result.sort_values('RMSE').head(10)

Input In [11], in simple_linear_model(train, test, input_feature)
      2 def simple_linear_model(train, test, input_feature):
      3     regr = linear_model.LinearRegression() # Create a linear regression object
----> 4     regr.fit(train.values(columns = [input_feature]), train.as_matrix(columns = ['Price'])) # Train the model
      5     RMSE = mean_squared_error(test.values(columns = ['Price']),
      6                               regr.predict(test.values(columns = [input_feature])))**0.5 # Calculate the RMSE on test data
      7     return RMSE, regr.intercept_[0], regr.coef_[0][0]

TypeError: 'numpy.ndarray' object is not callable
</code>```

Not sure which part is coming out to be an array honestly.

Body:
I'm doing a simple linear regression task for predicting house prices, using RMSE, with the following code

# A function that take one input of the dataset and return the RMSE (of the test data), and the intercept and coefficient
def simple_linear_model(train, test, input_feature):
    regr = linear_model.LinearRegression() # Create a linear regression object
    regr.fit(train.values(columns = [input_feature]), train.as_matrix(columns = ['Price'])) # Train the model
    RMSE = mean_squared_error(test.values(columns = ['Price']),
                              regr.predict(test.values(columns = [input_feature])))**0.5 # Calculate the RMSE on test data
    return RMSE, regr.intercept_[0], regr.coef_[0][0]

input_list = data.columns.values.tolist() # list of column name
input_list.remove('Price')
simple_linear_result = pd.DataFrame(columns = ['feature', 'RMSE', 'intercept', 'coefficient'])

# loop that calculate the RMSE of the test data for each input

for p in input_list:
    RMSE, w1, w0 = simple_linear_model(train_data, test_data, p)
    simple_linear_result = simple_linear_result.append({'feature':p, 'RMSE':RMSE, 'intercept':w0, 'coefficient': w1}
                                                       ,ignore_index=True)
simple_linear_result.sort_values('RMSE').head(10) # display the 10 best estimators

This error is coming:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [12], in <cell line: 6>()
      5 # loop that calculate the RMSE of the test data for each input
      6 for p in input_list:
----> 7     RMSE, w1, w0 = simple_linear_model(train_data, test_data, p)
      8     simple_linear_result = simple_linear_result.append({'feature':p, 'RMSE':RMSE, 'intercept':w0, 'coefficient': w1}
      9                                                        ,ignore_index=True)
     10 simple_linear_result.sort_values('RMSE').head(10)

Input In [11], in simple_linear_model(train, test, input_feature)
      2 def simple_linear_model(train, test, input_feature):
      3     regr = linear_model.LinearRegression() # Create a linear regression object
----> 4     regr.fit(train.values(columns = [input_feature]), train.as_matrix(columns = ['Price'])) # Train the model
      5     RMSE = mean_squared_error(test.values(columns = ['Price']),
      6                               regr.predict(test.values(columns = [input_feature])))**0.5 # Calculate the RMSE on test data
      7     return RMSE, regr.intercept_[0], regr.coef_[0][0]

TypeError: 'numpy.ndarray' object is not callable

Not sure which part is coming out to be an array honestly.


问:
Openshift - $HOSTNAME terminal command not found
In Openshift when writing $HOSTNAME I do not get the Hostname/Pod name. However doing echo $HOSTNAME, then the pod name is returned.

I need to use $HOSTNAME in my Deployment.yaml as seen below but it does not work and I wonder how come $HOSTNAME doesn't exist?

```<code>kind: Deployment
apiVersion: apps/v1
metadata:
  namespace: my-namespace
  labels:
    app: my-service
spec:
  selector:
    matchLabels:
      ...
  template:
    metadata:
      ...
    spec:
      containers:
        - name: my-service
          image: 'myservice.myrepo.com/my-service:latest'
          env:
            - name: USERS
              value: >-
                -javaagent:/opt/project/javaagent.jar
                -Users.exist=true
                -Users.first=John
                -Users.specialone=$(HOSTNAME)
                ...
</code>```

I tried using $(echo $HOSTNAME) in deployment yaml but it does not work.
I believe there is also ways to achieve this result but i.e. Python commands to get the $HOSTNAME but I wish for a more simplified method.

Body:
In Openshift when writing $HOSTNAME I do not get the Hostname/Pod name. However doing echo $HOSTNAME, then the pod name is returned.

I need to use $HOSTNAME in my Deployment.yaml as seen below but it does not work and I wonder how come $HOSTNAME doesn't exist?

kind: Deployment
apiVersion: apps/v1
metadata:
  namespace: my-namespace
  labels:
    app: my-service
spec:
  selector:
    matchLabels:
      ...
  template:
    metadata:
      ...
    spec:
      containers:
        - name: my-service
          image: 'myservice.myrepo.com/my-service:latest'
          env:
            - name: USERS
              value: >-
                -javaagent:/opt/project/javaagent.jar
                -Users.exist=true
                -Users.first=John
                -Users.specialone=$(HOSTNAME)
                ...

I tried using $(echo $HOSTNAME) in deployment yaml but it does not work.
I believe there is also ways to achieve this result but i.e. Python commands to get the $HOSTNAME but I wish for a more simplified method.


问:
Plotly Express - How to remove unwanted line after update?
I am trying to create a graph of sales using px.line. I create an initial plot and then repeatedly update the same one with forecasted data. The issue is that once I make the update, the line that was part of the previous forecast seems to remain although it doesn't point to any real data.

Couldn't figure out what to search for online. Is there a way to maybe reset the graph each time before plotting?

Relative beginner in this, Any help is appreciated.

```<code>app.layout = html.Div(children=[
    html.Div("----  Overall"),
        html.Div(
            children=[
                html.Div(children="ids"),
                dcc.Dropdown(id='idx'),
            ]
        ),
    html.Div("----  One"),
    dcc.Input(
            id="one",
            # value=0,
            type='number',
            debounce=True,
            placeholder="one",style=dict(width='10%')
        ),
    dcc.Input(
            id="two",
            # value=0,
            type='number',
            debounce=True,
            placeholder="two",style=dict(width='10%')
        ),
    dcc.Input(
            id="three",
            # value=0,
            type='number',
            debounce=True,
            placeholder="three",style=dict(width='10%')
        ),
    dcc.Input(
            id="four",
            # value=0,
            type='number',
            debounce=True,
            placeholder="four",style=dict(width='10%')
        ),
    dcc.Input(
            id="five",
            # value=0,
            type='number',
            debounce=True,
            placeholder="five",style=dict(width='10%')
        ),
    dcc.Graph(
        id='test',
        # animate=True,
    )
])

@app.callback(
    Output('test', 'figure'),
    [Input('idx', 'value'),Input('one', 'value'),Input('two', 'value'),Input('three', 'value')
    ,Input('four', 'value'),Input('five', 'value')])
def update_graph(idx,one,two,three,four,five):
    # yy = input dataframe formatted as [year,month,qty] (other inputs handled here too)
    fig = px.line(yy , x='month', y="qty",
              color="year",
              text='qty',
              custom_data=['year'],
             )
    fig.update_layout(hovermode='x unified')
    fig.update_traces(
    hovertemplate="<br>".join([
        "qty: %{y}",
    ])
)
</code>```

-before

-after

Body:
I am trying to create a graph of sales using px.line. I create an initial plot and then repeatedly update the same one with forecasted data. The issue is that once I make the update, the line that was part of the previous forecast seems to remain although it doesn't point to any real data.

Couldn't figure out what to search for online. Is there a way to maybe reset the graph each time before plotting?

Relative beginner in this, Any help is appreciated.

app.layout = html.Div(children=[
    html.Div("----  Overall"),
        html.Div(
            children=[
                html.Div(children="ids"),
                dcc.Dropdown(id='idx'),
            ]
        ),
    html.Div("----  One"),
    dcc.Input(
            id="one",
            # value=0,
            type='number',
            debounce=True,
            placeholder="one",style=dict(width='10%')
        ),
    dcc.Input(
            id="two",
            # value=0,
            type='number',
            debounce=True,
            placeholder="two",style=dict(width='10%')
        ),
    dcc.Input(
            id="three",
            # value=0,
            type='number',
            debounce=True,
            placeholder="three",style=dict(width='10%')
        ),
    dcc.Input(
            id="four",
            # value=0,
            type='number',
            debounce=True,
            placeholder="four",style=dict(width='10%')
        ),
    dcc.Input(
            id="five",
            # value=0,
            type='number',
            debounce=True,
            placeholder="five",style=dict(width='10%')
        ),
    dcc.Graph(
        id='test',
        # animate=True,
    )
])

@app.callback(
    Output('test', 'figure'),
    [Input('idx', 'value'),Input('one', 'value'),Input('two', 'value'),Input('three', 'value')
    ,Input('four', 'value'),Input('five', 'value')])
def update_graph(idx,one,two,three,four,five):
    # yy = input dataframe formatted as [year,month,qty] (other inputs handled here too)
    fig = px.line(yy , x='month', y="qty",
              color="year",
              text='qty',
              custom_data=['year'],
             )
    fig.update_layout(hovermode='x unified')
    fig.update_traces(
    hovertemplate="
".join([
        "qty: %{y}",
    ])
)

-before

-after


问:
Convert PowerShell to Java
How can I convert this command to java code?

powershell -command "$bytes = [System.IO.File]::ReadAllBytes('%2'); [Convert]::ToBase64String($bytes) | Out-File -append -FilePath '%2.base64' -Encoding ASCII -NoNewline"

I am afraid if I convert to base64 will not be the same output.

Title: Convert PowerShell to Java


问:
How to do count down timer for each room in Socket.io, Nodejs, react
I am developing an auction website using Nodejs and react and socket.io. So, the bidding starts at a specific time which will be set at the backend this is not the issue. My question is how to show a countdown timer when a user sends a bid every time. The timer should reset when a new bid is sent. Let's say there are 3 users that join the auction. So when the first user sends a bid the timer should start counting. Then if another user sends a bid before the timer reaches 0 then the timer should reset to 60 seconds and the bid will be changed to the current bid and the auction shall continue. If the timer reaches 0 then the auction is ended. The issue comes here, the timer should come from the backend through socket.io since it is required to show the same countdown for every user in the room.

This is the socket io implementation and the countdown is not showing the correct value. sometime it skips 2 seconds and sometimes it displays a repeated value

```<code>
io.on("connection", (socket) => {

  var countdown = 60;

  socket.on("joinAuctionRoom", async ({ user, auctionRoomId }) => {
    socket.join(auctionRoomId);
  });

  socket.on("getTimers", async ({ auctionRoomId }) => {
    var WinnerCountdown = setInterval(function () {
      io.sockets.to(auctionRoomId).emit("countdown", countdown);
      countdown--;
      if (counter === 0) {
        io.sockets.to(auctionRoomId).emit("aucntionDone", "Acution Completed");
        clearInterval(WinnerCountdown);
      }
    }, 1000);
  });

  socket.on("sendBid", ({ auctionRoomId, chat, user }) => {
    counter = 60;
    io.sockets.to(auctionRoomId).emit("recieveBid", { chat, counter, user });
  });

  socket.on("leaveAuctionRoom", ({ roomId, user }) => {
    socket.leave(roomId?.toString());
    console.log(`${user.firstName} left room`);
  });

  socket.on("disconnect", () => {
    console.log("Disconnected");
  });
});
</code>```

Body:
I am developing an auction website using Nodejs and react and socket.io. So, the bidding starts at a specific time which will be set at the backend this is not the issue. My question is how to show a countdown timer when a user sends a bid every time. The timer should reset when a new bid is sent. Let's say there are 3 users that join the auction. So when the first user sends a bid the timer should start counting. Then if another user sends a bid before the timer reaches 0 then the timer should reset to 60 seconds and the bid will be changed to the current bid and the auction shall continue. If the timer reaches 0 then the auction is ended. The issue comes here, the timer should come from the backend through socket.io since it is required to show the same countdown for every user in the room.

This is the socket io implementation and the countdown is not showing the correct value. sometime it skips 2 seconds and sometimes it displays a repeated value

io.on("connection", (socket) => {

  var countdown = 60;

  socket.on("joinAuctionRoom", async ({ user, auctionRoomId }) => {
    socket.join(auctionRoomId);
  });

  socket.on("getTimers", async ({ auctionRoomId }) => {
    var WinnerCountdown = setInterval(function () {
      io.sockets.to(auctionRoomId).emit("countdown", countdown);
      countdown--;
      if (counter === 0) {
        io.sockets.to(auctionRoomId).emit("aucntionDone", "Acution Completed");
        clearInterval(WinnerCountdown);
      }
    }, 1000);
  });

  socket.on("sendBid", ({ auctionRoomId, chat, user }) => {
    counter = 60;
    io.sockets.to(auctionRoomId).emit("recieveBid", { chat, counter, user });
  });

  socket.on("leaveAuctionRoom", ({ roomId, user }) => {
    socket.leave(roomId?.toString());
    console.log(`${user.firstName} left room`);
  });

  socket.on("disconnect", () => {
    console.log("Disconnected");
  });
});


问:
How to plot Contour frequency altitude diagram using text file?
I have several text files, each file containing 0-64 columns (no header), in which columns 4-63 represent the vertical profile of at every 250m (the 63rd column is at the surface) and I want to create a contour frequency altitude diagram.

Below is the code so far I did, and how my data looks like. I am not getting how to do the plotting.

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from glob import glob #to concatinate files
filesA = glob ('AS gpm data\\DPR_FS_precipRate_VER_PROFILE\\*txt')
dfA = pd.concat((pd.read_csv(file,sep='\t',index_col=False,header = None,)
             for file in filesA),ignore_index=False)
print(dfA.columns.tolist())`
</code>```

Data structure:

Reference plot:

Body:
I have several text files, each file containing 0-64 columns (no header), in which columns 4-63 represent the vertical profile of at every 250m (the 63rd column is at the surface) and I want to create a contour frequency altitude diagram.

Below is the code so far I did, and how my data looks like. I am not getting how to do the plotting.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from glob import glob #to concatinate files
filesA = glob ('AS gpm data\\DPR_FS_precipRate_VER_PROFILE\\*txt')
dfA = pd.concat((pd.read_csv(file,sep='\t',index_col=False,header = None,)
             for file in filesA),ignore_index=False)
print(dfA.columns.tolist())`

Data structure:

Reference plot:


问:
I'm getting error in emulator running when running React native app
I deleted node js react native and reinstalled it. I watched solution videos on the internet but I couldn't find a solution. I reviewed all the documentation properly and did everything as described, but when I try to run the emulator, the project gives this error.</p>
```<code>> test@0.0.1 android
> react-native run-android

info JS server already running.
info Installing the app...
Starting a Gradle Daemon, 1 incompatible Daemon could not be reused, use --status for details

FAILURE: Build failed with an exception.

* What went wrong:
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/7.5.1/userguide/gradle_daemon.html
Process command line: C:\Program Files (x86)\Java\jre1.8.0_351\bin\java.exe -XX:MaxMetaspaceSize=512m -Xmx2048m -Dfile.encoding=windows-1254 -Duser.country=TR -Duser.language=tr -Duser.variant -cp C:\Users\Taha\.gradle\wrapper\dists\gradle-7.5.1-all\1ehga6e77gqps5uk2kc5kf1vc\gradle-7.5.1\lib\gradle-launcher-7.5.1.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 7.5.1
Please read the following process output to find out more:
-----------------------
Error occurred during initialization of VM
Could not reserve enough space for 2097152KB object heap

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/7.5.1/userguide/gradle_daemon.html
Process command line: C:\Program Files (x86)\Java\jre1.8.0_351\bin\java.exe -XX:MaxMetaspaceSize=512m -Xmx2048m -Dfile.encoding=windows-1254 -Duser.country=TR -Duser.language=tr -Duser.variant -cp C:\Users\Taha\.gradle\wrapper\dists\gradle-7.5.1-all\1ehga6e77gqps5uk2kc5kf1vc\gradle-7.5.1\lib\gradle-launcher-7.5.1.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 7.5.1
Please read the following process output to find out more:
-----------------------
Error occurred during initialization of VM
Could not reserve enough space for 2097152KB object heap

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

    at makeError (C:\Users\Taha\Desktop\React\test\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:174:9)
    at C:\Users\Taha\Desktop\React\test\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:278:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async runOnAllDevices (C:\Users\Taha\Desktop\React\test\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (C:\Users\Taha\Desktop\React\test\node_modules\@react-native-community\cli\build\index.js:142:9)
info Run CLI with --verbose flag for more details.
</code>```

Body:
I deleted node js react native and reinstalled it. I watched solution videos on the internet but I couldn't find a solution. I reviewed all the documentation properly and did everything as described, but when I try to run the emulator, the project gives this error.

> test@0.0.1 android
> react-native run-android

info JS server already running.
info Installing the app...
Starting a Gradle Daemon, 1 incompatible Daemon could not be reused, use --status for details

FAILURE: Build failed with an exception.

* What went wrong:
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/7.5.1/userguide/gradle_daemon.html
Process command line: C:\Program Files (x86)\Java\jre1.8.0_351\bin\java.exe -XX:MaxMetaspaceSize=512m -Xmx2048m -Dfile.encoding=windows-1254 -Duser.country=TR -Duser.language=tr -Duser.variant -cp C:\Users\Taha\.gradle\wrapper\dists\gradle-7.5.1-all\1ehga6e77gqps5uk2kc5kf1vc\gradle-7.5.1\lib\gradle-launcher-7.5.1.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 7.5.1
Please read the following process output to find out more:
-----------------------
Error occurred during initialization of VM
Could not reserve enough space for 2097152KB object heap

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/7.5.1/userguide/gradle_daemon.html
Process command line: C:\Program Files (x86)\Java\jre1.8.0_351\bin\java.exe -XX:MaxMetaspaceSize=512m -Xmx2048m -Dfile.encoding=windows-1254 -Duser.country=TR -Duser.language=tr -Duser.variant -cp C:\Users\Taha\.gradle\wrapper\dists\gradle-7.5.1-all\1ehga6e77gqps5uk2kc5kf1vc\gradle-7.5.1\lib\gradle-launcher-7.5.1.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 7.5.1
Please read the following process output to find out more:
-----------------------
Error occurred during initialization of VM
Could not reserve enough space for 2097152KB object heap

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

    at makeError (C:\Users\Taha\Desktop\React\test\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:174:9)
    at C:\Users\Taha\Desktop\React\test\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:278:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async runOnAllDevices (C:\Users\Taha\Desktop\React\test\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (C:\Users\Taha\Desktop\React\test\node_modules\@react-native-community\cli\build\index.js:142:9)
info Run CLI with --verbose flag for more details.


问:
Python unit test
Hi i want to passed my unit test, but i do not know how
Can you help me please
I do not how to write code and unit test

I have advice from forum but my skills for programing my skills is minimalist

Instead writing a bunch of code that I will probably get wrong (good reason to test), I would build dictionary2 (terrible name) from dictionary (equally terrible name). Can do it in 1 line of Python code.

Your example is not written correctly for testing (or for being useful). coding() and decoding() should not print, they should return the translated string. Once modified, you test can call them with a string and compare the returned string against the expected result.

selection() will be difficult to test because it calls input(). You need to replace the existing function with one that returns strings provided by the test. I don't see this as being worth the effort.

You should modify the example.py module so it doesn't run any code when imported. Write a main() function, and only call this function if name == "main

```<code>dictionary={'A':'.-', 'B':'-...',
            'C':'-.-.', 'D':'-..', 'E':'.','F':'..-.', 'G':'--.', 'H':'....',
            'I':'..', 'J':'.---', 'K':'-.-','L':'.-..', 'M':'--', 'N':'-.',
            'O':'---', 'P':'.--.', 'Q':'--.-','R':'.-.', 'S':'...', 'T':'-',
            'U':'..-', 'V':'...-', 'W':'.--','X':'-..-', 'Y':'-.--', 'Z':'--..',}

dictionary2={'.-':'A','-...':'B','-.-.':'C','-..':'D', '.':'E','..-.':'F','--.':'G','....':'H',
             '..':'I','.---':'J', '-.-':'K','.-..':'L', '--':'M', '-.':'N',
             '---':'O', '.--.':'P', '--.-':'Q','.-.':'R', '...':'S', '-':'T',
             '..-':'U', '...-':'V', '.--':'W','-..-':'X', '-.--':'Y', '--..':'Z',}

def coding(s):
    void=" "
    for i in s: #indexování
        if i != ' ':
            void+=dictionary[i]+" "
        else:
            void += ' '

    print(void)

def decoding(s):
    void = ""
    splitstring = a.split(" ") #rozdělení podle mezer
    for i in splitstring: #indexování
            void += dictionary2[i]
    print(void)

def selection(f):
     f=int(input("1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY ")) # menu
     return f

c = 1
d = 0
while(c!="0"):
    d =selection(d)
    a=input("ZADEJ TEXT NA ŠIFROVÁNÍ: ")
    a=a.upper()

    startUp="" # nevyužívá se ale bez ní program nelze spustit

    if d==1: # šifrování
        coding(a)

    else: # dešifrování
        decoding(a)

    c = input(("POKUD CHCTE PROGRAM UKONČIT, ZADEJTE 0 || PRO POKRAČOVÁNÍ ZADEJTE LIBOVOLNÝ ZNAK : "))
</code>```
```<code>from example import coding
from example import decoding
from example import selection
from example import a

import pytest

def test_coding():
    #test coding for letters A-Z
    assert test_coding('A') == '.-'
    assert test_coding('B') == '-...'
    assert test_coding('C') == '-.-.'
    assert test_coding('D') == '-..'
    assert test_coding('E') == '.'
    assert test_coding('F') == '..-.'
    assert test_coding('G') == '--.'
    assert test_coding('H') == '....'
    assert test_coding('I') == '..'
    assert test_coding('J') == '.---'
    assert test_coding('K') == '-.-'
    assert test_coding('L') == '.-..'
    assert test_coding('M') == '--'
    assert test_coding('N') == '-.'
    assert test_coding('O') == '---'
    assert test_coding('P') == '.--.'
    assert test_coding('Q') == '--.-'
    assert test_coding('R') == '.-.'
    assert test_coding('S') == '...'
    assert test_coding('T') == '-'
    assert test_coding('U') == '..-'
    assert test_coding('V') == '...-'
    assert test_coding('W') == '.--'
    assert test_coding('X') == '-..-'
    assert test_coding('Y') == '-.--'
    assert test_coding('Z') == '--..'

    # test typeerror
    with pytest.raises(TypeError):
        test_coding(4)
        test_coding(True)
        test_coding("r")

def test_decoding() :
    #test decoding for letters A-Z
    assert test_decoding('.-') == 'A'
    assert test_decoding('-...') == 'B'
    assert test_decoding('-.-.') == 'C'
    assert test_decoding('-..') == 'D'
    assert test_decoding('.') == 'E'
    assert test_decoding('..-.') == 'F'
    assert test_decoding('--.') == 'G'
    assert test_decoding('....') == 'H'
    assert test_decoding('..') == 'I'
    assert test_decoding('---') == 'J'
    assert test_decoding('-.-') == 'K'
    assert test_decoding('.-..') == 'L'
    assert test_decoding('--') == 'M'
    assert test_decoding('-.') == 'N'
    assert test_decoding('---') == 'O'
    assert test_decoding('.--.') == 'P'
    assert test_decoding('--.-') == 'Q'
    assert test_decoding('.-.') == 'R'
    assert test_decoding('...') == 'S'
    assert test_decoding('-') == 'T'
    assert test_decoding('..-') == 'U'
    assert test_decoding('...-') == 'V'
    assert test_decoding('.--') == 'W'
    assert test_decoding('-..-') == 'X'
    assert test_decoding('-.--') == 'Y'
    assert test_decoding('--..') == 'Z'

def test_selection():
    assert test_selection(1) == test_coding(a)
</code>```

I do not know how to passed unit test

Title: Python unit test

Body:
Hi i want to passed my unit test, but i do not know how
Can you help me please
I do not how to write code and unit test

I have advice from forum but my skills for programing my skills is minimalist

Instead writing a bunch of code that I will probably get wrong (good reason to test), I would build dictionary2 (terrible name) from dictionary (equally terrible name). Can do it in 1 line of Python code.

Your example is not written correctly for testing (or for being useful). coding() and decoding() should not print, they should return the translated string. Once modified, you test can call them with a string and compare the returned string against the expected result.

selection() will be difficult to test because it calls input(). You need to replace the existing function with one that returns strings provided by the test. I don't see this as being worth the effort.

You should modify the example.py module so it doesn't run any code when imported. Write a main() function, and only call this function if name == "main

dictionary={'A':'.-', 'B':'-...',
            'C':'-.-.', 'D':'-..', 'E':'.','F':'..-.', 'G':'--.', 'H':'....',
            'I':'..', 'J':'.---', 'K':'-.-','L':'.-..', 'M':'--', 'N':'-.',
            'O':'---', 'P':'.--.', 'Q':'--.-','R':'.-.', 'S':'...', 'T':'-',
            'U':'..-', 'V':'...-', 'W':'.--','X':'-..-', 'Y':'-.--', 'Z':'--..',}

dictionary2={'.-':'A','-...':'B','-.-.':'C','-..':'D', '.':'E','..-.':'F','--.':'G','....':'H',
             '..':'I','.---':'J', '-.-':'K','.-..':'L', '--':'M', '-.':'N',
             '---':'O', '.--.':'P', '--.-':'Q','.-.':'R', '...':'S', '-':'T',
             '..-':'U', '...-':'V', '.--':'W','-..-':'X', '-.--':'Y', '--..':'Z',}

def coding(s):
    void=" "
    for i in s: #indexování
        if i != ' ':
            void+=dictionary[i]+" "
        else:
            void += ' '

    print(void)

def decoding(s):
    void = ""
    splitstring = a.split(" ") #rozdělení podle mezer
    for i in splitstring: #indexování
            void += dictionary2[i]
    print(void)

def selection(f):
     f=int(input("1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY ")) # menu
     return f

c = 1
d = 0
while(c!="0"):
    d =selection(d)
    a=input("ZADEJ TEXT NA ŠIFROVÁNÍ: ")
    a=a.upper()

    startUp="" # nevyužívá se ale bez ní program nelze spustit

    if d==1: # šifrování
        coding(a)

    else: # dešifrování
        decoding(a)

    c = input(("POKUD CHCTE PROGRAM UKONČIT, ZADEJTE 0 || PRO POKRAČOVÁNÍ ZADEJTE LIBOVOLNÝ ZNAK : "))

from example import coding
from example import decoding
from example import selection
from example import a

import pytest

def test_coding():
    #test coding for letters A-Z
    assert test_coding('A') == '.-'
    assert test_coding('B') == '-...'
    assert test_coding('C') == '-.-.'
    assert test_coding('D') == '-..'
    assert test_coding('E') == '.'
    assert test_coding('F') == '..-.'
    assert test_coding('G') == '--.'
    assert test_coding('H') == '....'
    assert test_coding('I') == '..'
    assert test_coding('J') == '.---'
    assert test_coding('K') == '-.-'
    assert test_coding('L') == '.-..'
    assert test_coding('M') == '--'
    assert test_coding('N') == '-.'
    assert test_coding('O') == '---'
    assert test_coding('P') == '.--.'
    assert test_coding('Q') == '--.-'
    assert test_coding('R') == '.-.'
    assert test_coding('S') == '...'
    assert test_coding('T') == '-'
    assert test_coding('U') == '..-'
    assert test_coding('V') == '...-'
    assert test_coding('W') == '.--'
    assert test_coding('X') == '-..-'
    assert test_coding('Y') == '-.--'
    assert test_coding('Z') == '--..'

    # test typeerror
    with pytest.raises(TypeError):
        test_coding(4)
        test_coding(True)
        test_coding("r")

def test_decoding() :
    #test decoding for letters A-Z
    assert test_decoding('.-') == 'A'
    assert test_decoding('-...') == 'B'
    assert test_decoding('-.-.') == 'C'
    assert test_decoding('-..') == 'D'
    assert test_decoding('.') == 'E'
    assert test_decoding('..-.') == 'F'
    assert test_decoding('--.') == 'G'
    assert test_decoding('....') == 'H'
    assert test_decoding('..') == 'I'
    assert test_decoding('---') == 'J'
    assert test_decoding('-.-') == 'K'
    assert test_decoding('.-..') == 'L'
    assert test_decoding('--') == 'M'
    assert test_decoding('-.') == 'N'
    assert test_decoding('---') == 'O'
    assert test_decoding('.--.') == 'P'
    assert test_decoding('--.-') == 'Q'
    assert test_decoding('.-.') == 'R'
    assert test_decoding('...') == 'S'
    assert test_decoding('-') == 'T'
    assert test_decoding('..-') == 'U'
    assert test_decoding('...-') == 'V'
    assert test_decoding('.--') == 'W'
    assert test_decoding('-..-') == 'X'
    assert test_decoding('-.--') == 'Y'
    assert test_decoding('--..') == 'Z'

def test_selection():
    assert test_selection(1) == test_coding(a)

I do not know how to passed unit test


问:
JFrog Container Registry logo display duration
I have recently set up JFrog Container Registry (v7.46.11) using its helm installer.

Some stats:

```<code>Docker images uploaded: ~ 30
Binaries Size: 42 GB
Binaries Count: 600
Artifacts Size: 105 GB
Artifacts count: 1200
File system: Used: 147 GB / 500 GB (29.4%)
No of concurrent users: 1 (that's right) and most of time it's idle. Essentially, no one is using it right now.
</code>```

Issue is when I try logging in, the JFrog logo keeps showing up for almost 30-40 secs.

In all sincerity, I love the logo but not the duration for which it displays itself before actually showing the login screen. After logging in, everything works fine. No slowness is observed after that. To reduce the logo show time, I tried increasing the xms and xmx parameter along with the request and limits parameters as well but I don't see any change in the logo display duration. Is there any other JVM option that needs tweaking?

```<code>resources:
  requests:
    memory: "4Gi"
    cpu: "2"
  limits:
    memory: "5Gi"
    cpu: "4"
 ## The following Java options are passed to the java process running Artifactory.
 ## You should set them according to the resources set above.
 ## IMPORTANT: Make sure resources.limits.memory is at least 1G more than Xmx.
javaOpts:
  xms: "4g"
  xmx: "4g"
</code>```

Body:
I have recently set up JFrog Container Registry (v7.46.11) using its helm installer.

Some stats:

Docker images uploaded: ~ 30
Binaries Size: 42 GB
Binaries Count: 600
Artifacts Size: 105 GB
Artifacts count: 1200
File system: Used: 147 GB / 500 GB (29.4%)
No of concurrent users: 1 (that's right) and most of time it's idle. Essentially, no one is using it right now.

Issue is when I try logging in, the JFrog logo keeps showing up for almost 30-40 secs.

In all sincerity, I love the logo but not the duration for which it displays itself before actually showing the login screen. After logging in, everything works fine. No slowness is observed after that. To reduce the logo show time, I tried increasing the xms and xmx parameter along with the request and limits parameters as well but I don't see any change in the logo display duration. Is there any other JVM option that needs tweaking?

resources:
  requests:
    memory: "4Gi"
    cpu: "2"
  limits:
    memory: "5Gi"
    cpu: "4"
 ## The following Java options are passed to the java process running Artifactory.
 ## You should set them according to the resources set above.
 ## IMPORTANT: Make sure resources.limits.memory is at least 1G more than Xmx.
javaOpts:
  xms: "4g"
  xmx: "4g"


问:
How to decorate Stepper widget in Flutter
I want decorate my stepper widget. I can't find any widget to customise the defalut design.

I want to make this design but stapper widget constructor doesn't have any decoration attribute. So how to achieve this design.


问:
report builder scheduling sending by email
i am using microsoft report builder and my goal is Data transmission automatione to sending some tables to my team, i connect to DB and build a report contain only 1 table, how can i delivere this report to my manager through email? (scheduling)


问:
How to get ONLY magic methods for given class/object in Python?
I wonder what check I should make to check whether method is magic? Not dunder (two underscore before and after), ONLY and ONLY magic methods. If be more specific methods that not goes through __getattr__

This is my current solution, but I want to simplify set of __ignore_attributes__  and make this solution more robust.

```<code>class ParameterizedMeta(ABCMeta):

    @_tp_cache
    def __getitem__(cls, *values):
        # methods have default implementation not places here
        values = cls.__subclass_parseargs__(*values)
        parameters = cls.__subclass_parameters__(*values)
        name = cls.__subclass_name__(parameters)
        bases = cls.__subclass_bases__(parameters)
        subclass = type(name, bases, parameters)
        subclass.__subclass_post_init__()
        return subclass

__ignore_attributes__ = {
    "__class__",
    "__mro__",
    "__new__",
    "__init__",

    "__setattr__",
    "__getattr__",
    "__delattr__",
    "__getattribute__",
    "__eq__",
    "__ne__",

    "__init_subclass__",
    "__class_getitem__",
    "__subclasshook__",

    "__module__",
    "__name__",
    "__qualname__",

    "__dict__",

    "__slots__",
    "__size__",
    "__sizeof__",
    "__weakref__",
    "__abstractmethods__",

    "__orig_class__",
    "__post_init__",

    "__type__",
    ...
}

__force_attributes__ = [
    "__hash__",
    "__str__",
    "__repr__",
]

__proxy_meta_bypass__ = {"__type__", ...}

class ProxyMeta(ParameterizedMeta):
    __type__: type[Serializable]

    def __getattr__(self, item) -> Any:
        # If requested attribute is one of predefined prevent infinite recursion
        if item in __proxy_meta_bypass__ :
            raise AttributeError
        return getattr(self.__type__, item)

    def __subclass_post_init__(self):
        if not isinstance(self.__type__, type):
            return

        attributes = set(dir(self.__type__) + __force_attributes__)

        def delegate(attribute: str):
            def proxy(s, *args, **kwargs):
                func = getattr(s.__value__, attribute)
                return func(*args, **kwargs)

            proxy.__name__ = str(attributes)

            return proxy

        def check_is_magic(attribute: str):
            if not attribute.startswith("__") or not attribute.endswith("__"):
                return False
            if attribute in __ignore_attributes__:
                return False
            value = getattr(self.__type__, attribute)
            if not callable(value):
                return False
            return True

        for name in filter(check_is_magic, attributes):
            setattr(self, name, delegate(name))
</code>```

Body:
I wonder what check I should make to check whether method is magic? Not dunder (two underscore before and after), ONLY and ONLY magic methods. If be more specific methods that not goes through __getattr__

This is my current solution, but I want to simplify set of __ignore_attributes__  and make this solution more robust.

class ParameterizedMeta(ABCMeta):

    @_tp_cache
    def __getitem__(cls, *values):
        # methods have default implementation not places here
        values = cls.__subclass_parseargs__(*values)
        parameters = cls.__subclass_parameters__(*values)
        name = cls.__subclass_name__(parameters)
        bases = cls.__subclass_bases__(parameters)
        subclass = type(name, bases, parameters)
        subclass.__subclass_post_init__()
        return subclass

__ignore_attributes__ = {
    "__class__",
    "__mro__",
    "__new__",
    "__init__",

    "__setattr__",
    "__getattr__",
    "__delattr__",
    "__getattribute__",
    "__eq__",
    "__ne__",

    "__init_subclass__",
    "__class_getitem__",
    "__subclasshook__",

    "__module__",
    "__name__",
    "__qualname__",

    "__dict__",

    "__slots__",
    "__size__",
    "__sizeof__",
    "__weakref__",
    "__abstractmethods__",

    "__orig_class__",
    "__post_init__",

    "__type__",
    ...
}

__force_attributes__ = [
    "__hash__",
    "__str__",
    "__repr__",
]

__proxy_meta_bypass__ = {"__type__", ...}

class ProxyMeta(ParameterizedMeta):
    __type__: type[Serializable]

    def __getattr__(self, item) -> Any:
        # If requested attribute is one of predefined prevent infinite recursion
        if item in __proxy_meta_bypass__ :
            raise AttributeError
        return getattr(self.__type__, item)

    def __subclass_post_init__(self):
        if not isinstance(self.__type__, type):
            return

        attributes = set(dir(self.__type__) + __force_attributes__)

        def delegate(attribute: str):
            def proxy(s, *args, **kwargs):
                func = getattr(s.__value__, attribute)
                return func(*args, **kwargs)

            proxy.__name__ = str(attributes)

            return proxy

        def check_is_magic(attribute: str):
            if not attribute.startswith("__") or not attribute.endswith("__"):
                return False
            if attribute in __ignore_attributes__:
                return False
            value = getattr(self.__type__, attribute)
            if not callable(value):
                return False
            return True

        for name in filter(check_is_magic, attributes):
            setattr(self, name, delegate(name))


问:
About "Unhandled event loop exception" in Eclipse run on Ubuntu
I installed Eclipse 4.26.0 (from this link) to my Ubuntu virtual machine on VirtualBox. But when I click "Open File" or any other operations that would open a file explorer, error "Unhandled event loop exception: No more handles" is shown, and then another window with "An SWT error has occurred".

The full Exception Stack Trace is as below:

```<code>org.eclipse.swt.SWTError: No more handles
    at org.eclipse.swt.SWT.error(SWT.java:4944)
    at org.eclipse.swt.SWT.error(SWT.java:4833)
    at org.eclipse.swt.SWT.error(SWT.java:4804)
    at org.eclipse.swt.widgets.Dialog.error(Dialog.java:202)
    at org.eclipse.swt.widgets.FileDialog.openNativeChooserDialog(FileDialog.java:351)
    at org.eclipse.swt.widgets.FileDialog.open(FileDialog.java:335)
    at org.eclipse.jdt.ui.wizards.BuildPathDialogAccess.chooseExternalJAREntries(BuildPathDialogAccess.java:493)
    at org.eclipse.jdt.internal.ui.wizards.buildpaths.LibrariesWorkbookPage.openExtJarFileDialog(LibrariesWorkbookPage.java:1219)
    at org.eclipse.jdt.internal.ui.wizards.buildpaths.LibrariesWorkbookPage.libaryPageCustomButtonPressed(LibrariesWorkbookPage.java:453)
    at org.eclipse.jdt.internal.ui.wizards.buildpaths.LibrariesWorkbookPage$LibrariesAdapter.customButtonPressed(LibrariesWorkbookPage.java:403)
    at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.buttonPressed(TreeListDialogField.java:177)
    at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.doButtonSelected(TreeListDialogField.java:412)
    at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField$2.widgetSelected(TreeListDialogField.java:373)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:252)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:5855)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1529)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:5065)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4517)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:823)
    at org.eclipse.jface.window.Window.open(Window.java:799)
    at org.eclipse.ui.internal.actions.NewWizardShortcutAction.run(NewWizardShortcutAction.java:130)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:474)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:580)
    at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:414)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:5855)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1529)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:5065)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4517)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1155)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1046)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:155)
    at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:643)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:550)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:171)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:152)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:203)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:136)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:402)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:255)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:659)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:596)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1467)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1440)
</code>```

and Session Data:

```<code>eclipse.buildId=4.26.0.20221201-1200
java.version=17.0.5
java.vendor=Eclipse Adoptium
BootLoader constants: OS=linux, ARCH=x86_64, WS=gtk, NL=zh_CN
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os linux -ws gtk -arch x86_64 -product org.eclipse.epp.package.java.product
</code>```

I am not familiar with Linux system and I have tried several methods I found but none of them worked.

I have installed SWT Designer and changed the default file association of .java file to WindowBuilder Editor.

I have re-installed Eclipse and recreated the workspace.

I want to get a solution for it.

Body:
I installed Eclipse 4.26.0 (from this link) to my Ubuntu virtual machine on VirtualBox. But when I click "Open File" or any other operations that would open a file explorer, error "Unhandled event loop exception: No more handles" is shown, and then another window with "An SWT error has occurred".

The full Exception Stack Trace is as below:

org.eclipse.swt.SWTError: No more handles
    at org.eclipse.swt.SWT.error(SWT.java:4944)
    at org.eclipse.swt.SWT.error(SWT.java:4833)
    at org.eclipse.swt.SWT.error(SWT.java:4804)
    at org.eclipse.swt.widgets.Dialog.error(Dialog.java:202)
    at org.eclipse.swt.widgets.FileDialog.openNativeChooserDialog(FileDialog.java:351)
    at org.eclipse.swt.widgets.FileDialog.open(FileDialog.java:335)
    at org.eclipse.jdt.ui.wizards.BuildPathDialogAccess.chooseExternalJAREntries(BuildPathDialogAccess.java:493)
    at org.eclipse.jdt.internal.ui.wizards.buildpaths.LibrariesWorkbookPage.openExtJarFileDialog(LibrariesWorkbookPage.java:1219)
    at org.eclipse.jdt.internal.ui.wizards.buildpaths.LibrariesWorkbookPage.libaryPageCustomButtonPressed(LibrariesWorkbookPage.java:453)
    at org.eclipse.jdt.internal.ui.wizards.buildpaths.LibrariesWorkbookPage$LibrariesAdapter.customButtonPressed(LibrariesWorkbookPage.java:403)
    at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.buttonPressed(TreeListDialogField.java:177)
    at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField.doButtonSelected(TreeListDialogField.java:412)
    at org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField$2.widgetSelected(TreeListDialogField.java:373)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:252)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:5855)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1529)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:5065)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4517)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:823)
    at org.eclipse.jface.window.Window.open(Window.java:799)
    at org.eclipse.ui.internal.actions.NewWizardShortcutAction.run(NewWizardShortcutAction.java:130)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:474)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:580)
    at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:414)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:5855)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1529)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:5065)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4517)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1155)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1046)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:155)
    at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:643)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:550)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:171)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:152)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:203)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:136)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:402)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:255)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:659)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:596)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1467)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1440)

and Session Data:

eclipse.buildId=4.26.0.20221201-1200
java.version=17.0.5
java.vendor=Eclipse Adoptium
BootLoader constants: OS=linux, ARCH=x86_64, WS=gtk, NL=zh_CN
Framework arguments:  -product org.eclipse.epp.package.java.product
Command-line arguments:  -os linux -ws gtk -arch x86_64 -product org.eclipse.epp.package.java.product

I am not familiar with Linux system and I have tried several methods I found but none of them worked.

I have installed SWT Designer and changed the default file association of .java file to WindowBuilder Editor.

I have re-installed Eclipse and recreated the workspace.

I want to get a solution for it.


问:
Unrepeatable read or something else?
I'm going over transaction management in DBMS, specifically conflict serializability.  I know that

T1_R(a), T2_R(b), T1_R(a)

would be considered an unrepeatable read.  But would

T1_R(a), T2_W(a)

be considered an unrepeatable read? And if not, what kind of interference would something like

T1_R(a), T2_R(a), T2_W(a), T2_W(b), T1_R(b), T2_W(b)

be?  Because it seems not to be conflict serializable, but I can't figure out what kind of interference it is, if any.

Title: Unrepeatable read or something else?


问:
npm install is giving an error after installing node js and visual studio community
C:\Users\HP\Desktop\ZTM\simplefolio>

npm ERR! gyp ERR! stack     at ChildProcess._handle.onexit (node:internal/child_process:291:12)
npm ERR! gyp ERR! stack     at onErrorNT (node:internal/child_process:483:16)
npm ERR! gyp ERR! stack     at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
npm ERR! gyp ERR! System Windows_NT 10.0.19044
npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\HP\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd C:\Users\HP\Desktop\ZTM\simplefolio\node_modules\lmdb-store
npm ERR! gyp ERR! node -v v19.2.0
npm ERR! gyp ERR! node-gyp -v v9.3.0
npm ERR! gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\HP\AppData\Local\npm-cache_logs\2022-12-11T10_40_35_068Z-debug-0.log

I have uninstalled and reinstalled node.js then installed Visual studio community 2022 and I am still facing this error , what can be done?


问:
How to draw a large number of rectangles in wpf?
I needed to make a 1024 x 1024 field in the game of life, but so far I can't figure out how to do it in order to maintain functionality. When I draw 100х100 rectangle, the program is already starting to load for a long time.

```<code>void CreateBoard()
        {
            cBoard.Children.Clear();
            BoardRef = new Rectangle[BoardSize, BoardSize];
            for (int i = 0; i < BoardSize; i++)
            {
                for (int j = 0; j < BoardSize; j++)
                {
                    if (i == 0 || i == BoardSize - 1 || j == 0 || j == BoardSize - 1) // Makes boundaries[enter image description here](https://i.stack.imgur.com/D4scK.png)
                    {
                        Rectangle r = new Rectangle
                        {
                            Width = RectSize,
                            Height = RectSize,
                            Stroke = Brushes.DarkRed,
                            StrokeThickness = 0.5,
                            Fill = Brushes.DarkRed,
                        };
                        BoardRef[i, j] = r;
                        Canvas.SetLeft(r, j * RectSize);
                        Canvas.SetTop(r, i * RectSize);
                        cBoard.Children.Add(r);
                    }
                    else
                    {
                        CellModel cell = new CellModel { State = false, Col = i, Ren = j };
                        Rectangle r = new Rectangle
                        {
                            Width = RectSize,
                            Height = RectSize,
                            Stroke = Brushes.Gray,
                            StrokeThickness = 0.5,
                            Fill = Brushes.Black,
                            Tag = cell
                        };
                        r.MouseDown += R_MouseDown;
                        BoardRef[i, j] = r;
                        Canvas.SetLeft(r, j * RectSize);
                        Canvas.SetTop(r, i * RectSize);
                        cBoard.Children.Add(r);
                    }
                }
            }
        }
</code>```

view

Body:
I needed to make a 1024 x 1024 field in the game of life, but so far I can't figure out how to do it in order to maintain functionality. When I draw 100х100 rectangle, the program is already starting to load for a long time.

void CreateBoard()
        {
            cBoard.Children.Clear();
            BoardRef = new Rectangle[BoardSize, BoardSize];
            for (int i = 0; i < BoardSize; i++)
            {
                for (int j = 0; j < BoardSize; j++)
                {
                    if (i == 0 || i == BoardSize - 1 || j == 0 || j == BoardSize - 1) // Makes boundaries[enter image description here](https://i.stack.imgur.com/D4scK.png)
                    {
                        Rectangle r = new Rectangle
                        {
                            Width = RectSize,
                            Height = RectSize,
                            Stroke = Brushes.DarkRed,
                            StrokeThickness = 0.5,
                            Fill = Brushes.DarkRed,
                        };
                        BoardRef[i, j] = r;
                        Canvas.SetLeft(r, j * RectSize);
                        Canvas.SetTop(r, i * RectSize);
                        cBoard.Children.Add(r);
                    }
                    else
                    {
                        CellModel cell = new CellModel { State = false, Col = i, Ren = j };
                        Rectangle r = new Rectangle
                        {
                            Width = RectSize,
                            Height = RectSize,
                            Stroke = Brushes.Gray,
                            StrokeThickness = 0.5,
                            Fill = Brushes.Black,
                            Tag = cell
                        };
                        r.MouseDown += R_MouseDown;
                        BoardRef[i, j] = r;
                        Canvas.SetLeft(r, j * RectSize);
                        Canvas.SetTop(r, i * RectSize);
                        cBoard.Children.Add(r);
                    }
                }
            }
        }

view


问:
How to create a persistent service in AOSP Framework that can communicate to native layer in HAL?
How to create a persistent service in AOSP to communicate with the native layer in HAL?

For example, I am interested in having a 3rd party application communicate through a persistent service in AOSP Framework and have that communication reach the native layer in AOSP HAL.

Android App -> Service in AOSP Framework (Java) -> Service (C++) -> HAL (native)

Android App <- Service in AOSP Framework (Java) <- Service (C++) <- HAL (native)

Additional questions:

Would the above be the minimal number of steps (processes) for communication to reach from the App to HAL? For example for each path, would it require both a Java Service and a C++ Service?

Would each of the steps above be independent processes? For example in (1) and (2) paths, would there be a total of 4 processes for each path?

Is there an example of how to create a persistent service in AOSP for both Java and C++? Which directory would these live in if building AOSP locally? How can these be registered to start automatically on device boot?

How can communication be established between App and Java Service? How can communication be established between the Java Service and the C++ Service? How can communication be established between the C++ Service and HAL?


问:
React how to export html and javascript as a file after React finish rendering on client
Background

I have a React client application.

Demand

I have a demand that I need to export the static HTML file after clicking a button.
Similar question  is here

Exporting a React Application as static HTML

Two conditions must be satisfied.

The static HTML must include the data state at the time when I click the export button.

The static HTML must include the javascript event. For example, the submit button should also works at static HTML file.

Current Develop Status

I tried to do this with the following React code.

App.js

```<code>import React, { useState } from 'react';
import ListComponent from './List'

const App = () => {
    const [name, setName] = useState('')
    const [names, setNames] = useState([])

    const handleSubmit = () => {
        setNames(n => ([...n, name]))
        setName('')
    }

    console.log(names)

    const handleExport = () => {

        const link = document.createElement("a");

        // Create a blog object with the file content which you want to add to the file
        const file = new Blob([document.getElementsByTagName('html')[0].innerHTML], { type: 'text/plain' });

        // Add file content in the object URL
        link.href = URL.createObjectURL(file);

        // Add file name
        link.download = "sample.html";

        // Add click event to <a> tag to save file.
        link.click();
        URL.revokeObjectURL(link.href);
    }

    return (<div>
        <div>App</div>
        <div>
            <button onClick={handleExport}>export</button>
        </div>
        <div>
            <input name='name' value={name} onChange={e=>setName(e.target.value)}></input>
        </div>
        <div>
            <button onClick={handleSubmit}>submit</button>
        </div>
        <ListComponent names={names}/>
    </div>)
};

export default App
</code>```

List.jsx

```<code>import styles from './List.module.css'

const ListComponent = (props) => {
    const { names } = props
    return <div>

        {names.map(n => {
            return <div className={styles.list}>
                <p className={styles.name}>name:</p>
                <p className={styles.value}>{n}</p>
            </div>
        })}

    </div>
}

export default ListComponent
</code>```

List.module.css

```<code>.list {
    display: flex;
}

.name {
color: blue;
}

.value {
color: yellow;
}
</code>```

The implementation above can satisfy the first condition, but I don't know how to satisfy the second condition.

Exported static HTML opened by browser

The exported static HTML file's source code

    <meta charset="utf-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#000000">
    <meta name="description" content="Web site created using create-react-app">
    <link rel="apple-touch-icon" href="/logo192.png">

    <link rel="manifest" href="/manifest.json">

    <title>React App</title>

    You need to enable JavaScript to run this app.

App

<button>export</button>

<input name="name" value="">

<button>submit</button>

name:

asdas

name:

asd

name:

asd

name:

asd

<grammarly-desktop-integration data-grammarly-shadow-root="true"></grammarly-desktop-integration>```

The Problem

The name list is remained as what I expected but the submit button could not be clicked anymore.
That is because the javascript code controlling event logic is not exported during HTML export.

When I import the bundle.js which is generated during npm run start. The submit button can be clicked but the name list is lost. That is because bundle.js contains React code which will force rendering page from mount stage.

Submit button can be clicked but page is rendering again

My Question

Is there a way to export a static HTML including both dom and styles and javascript event?

Body:
Background

I have a React client application.

Demand

I have a demand that I need to export the static HTML file after clicking a button.
Similar question  is here

Exporting a React Application as static HTML

Two conditions must be satisfied.

The static HTML must include the data state at the time when I click the export button.

The static HTML must include the javascript event. For example, the submit button should also works at static HTML file.

Current Develop Status

I tried to do this with the following React code.

App.js

import React, { useState } from 'react';
import ListComponent from './List'

const App = () => {
    const [name, setName] = useState('')
    const [names, setNames] = useState([])

    const handleSubmit = () => {
        setNames(n => ([...n, name]))
        setName('')
    }

    console.log(names)

    const handleExport = () => {

        const link = document.createElement("a");

        // Create a blog object with the file content which you want to add to the file
        const file = new Blob([document.getElementsByTagName('html')[0].innerHTML], { type: 'text/plain' });

        // Add file content in the object URL
        link.href = URL.createObjectURL(file);

        // Add file name
        link.download = "sample.html";

        // Add click event to  tag to save file.
        link.click();
        URL.revokeObjectURL(link.href);
    }

    return (

App

            <button onClick={handleExport}>export</button>

            <input name='name' value={name} onChange={e=>setName(e.target.value)}></input>

            <button onClick={handleSubmit}>submit</button>

        <ListComponent names={names}/>

)
};

export default App

List.jsx

import styles from './List.module.css'

const ListComponent = (props) => {
    const { names } = props
    return

        {names.map(n => {
            return

name:

{n}

        })}

}

export default ListComponent

List.module.css

.list {
    display: flex;
}

.name {
color: blue;
}

.value {
color: yellow;
}

The implementation above can satisfy the first condition, but I don't know how to satisfy the second condition.

Exported static HTML opened by browser

The exported static HTML file's source code

    <meta charset="utf-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#000000">
    <meta name="description" content="Web site created using create-react-app">
    <link rel="apple-touch-icon" href="/logo192.png">

    <link rel="manifest" href="/manifest.json">

    <title>React App</title>

    You need to enable JavaScript to run this app.

App

<button>export</button>

<input name="name" value="">

<button>submit</button>

name:

asdas

name:

asd

name:

asd

name:

asd

<grammarly-desktop-integration data-grammarly-shadow-root="true"></grammarly-desktop-integration>

The Problem

The name list is remained as what I expected but the submit button could not be clicked anymore.
That is because the javascript code controlling event logic is not exported during HTML export.

When I import the bundle.js which is generated during npm run start. The submit button can be clicked but the name list is lost. That is because bundle.js contains React code which will force rendering page from mount stage.

Submit button can be clicked but page is rendering again

My Question

Is there a way to export a static HTML including both dom and styles and javascript event?


问:
How Do I Create a Map Image Only Using Paint/MS Office
I work security for a business campus, where we are expected to respond to different areas for alarms.

I want to make an interactive map so specific buildings can be highlighted during alarms, with maps of each floor of each building nested within them so the alarmed areas can also be highlighted.

The main problem is that the map images I have access to are proprietary information, so I can't take them home to create something on my computer, and I can't use online sources either.

Is there a way to make such a file only using Microsoft Office and/or paint?

And if it is possible, how do I go about making it?

I've made png file maps that outline our patrol routes, but those are just printed out and act as a learning tool. They also are not interactive and they don't cover all areas with active alarm panels.