问:
Migrating existing containers from Hyper-V to WSL2 technology
After DockerCon 2020, I enthusiastically downloaded Windows 10 2004 and tried to upgrade Docker Desktop to WSL 2 containers and experiment.

I had a few containers, in particular a couple of databases along with their data stored within volumes. Postgres and MS SQL Server in the case.

I wouldn't like to lose the data, though it's not critical. I used Docker volumes rather than OS mounts because I have repeatedly seen that using Windows mounts for database data storage is not recommended.

When I enabled WSL-2 for the first time, all my containers and volumes disappeared.

I'd like to ask if there is any (recommended) procedure or tool to mgirate Hyper-V based containers to WSL-2 along with their data.

Images can be easily redownloaded. How about container setup and data migration to WSL-2?

Of course I can do it manually. I can dump the volumes to my local drive (as a tar) using busybox and restore using another busybox instance

答:
Of course, here is my sharing of experience.

Reconstruct the docker run syntax

First, you need to remember or reconstruct the syntax to start the container to re-run them later. The idea is to collect as much information as possible from existing containers to re-run them

Here is a good starting point

Migrating volumes

That's between ease of execution and long-running task. Easy because it took me simply one container, long and tedious because it requires multiple commands

```<code>docker run `
           --rm ` #Dispose after use
           -v G:\Docker:/volumes ` # Mount my Windows drive so that the file will appear in Explorer
           - v src_mount:/src ` # e.g. mssql2017:/mssql2017 mounts mssql2017 named volume to Busybox
           busybox `
           tar -zcvf /volumes/backup_name.tar.gz /src
</code>```

Rinse and repeat for all named volumes of your interest. I had a bunch only

Dump images you won't be able/willing to reconstruct

In my case, Oracle 12c/19c were built but never pushed. Building Oracle is painful becuase you have to build the container after downloading their licensed ZIP file

Use docker save -o wisely. Example

```<code>docker save oracledb:12.0.0.0c -o oracledb.img
</code>```

Restore images

After switching to WSL-2, use docker load wisely

Restore volumes

Manually recreate all volumes with docker volume create and unzip with busybox. This is kind of a reverse

```<code>docker run `
       --rm ` #Dispose after use
       -v G:\Docker:/volumes ` # Mount my Windows drive so that the file will appear in Explorer
       - v dest_mount:/dest ` # e.g. mssql2017:/mssql2017 mounts mssql2017 named volume to Busybox
       busybox `
       tar -zxvf /volumes/backup_name.tar.gz /dest
</code>```

Restore containers

Now that you have your source Docker commandline-s, launch them to recreate containers.

Conclusion: I am thinking about making a reusable Powershell script

Body:
Of course, here is my sharing of experience.

Reconstruct the docker run syntax

First, you need to remember or reconstruct the syntax to start the container to re-run them later. The idea is to collect as much information as possible from existing containers to re-run them

Here is a good starting point

Migrating volumes

That's between ease of execution and long-running task. Easy because it took me simply one container, long and tedious because it requires multiple commands

docker run `
           --rm ` #Dispose after use
           -v G:\Docker:/volumes ` # Mount my Windows drive so that the file will appear in Explorer
           - v src_mount:/src ` # e.g. mssql2017:/mssql2017 mounts mssql2017 named volume to Busybox
           busybox `
           tar -zcvf /volumes/backup_name.tar.gz /src

Rinse and repeat for all named volumes of your interest. I had a bunch only

Dump images you won't be able/willing to reconstruct

In my case, Oracle 12c/19c were built but never pushed. Building Oracle is painful becuase you have to build the container after downloading their licensed ZIP file

Use docker save -o wisely. Example

docker save oracledb:12.0.0.0c -o oracledb.img

Restore images

After switching to WSL-2, use docker load wisely

Restore volumes

Manually recreate all volumes with docker volume create and unzip with busybox. This is kind of a reverse

docker run `
       --rm ` #Dispose after use
       -v G:\Docker:/volumes ` # Mount my Windows drive so that the file will appear in Explorer
       - v dest_mount:/dest ` # e.g. mssql2017:/mssql2017 mounts mssql2017 named volume to Busybox
       busybox `
       tar -zxvf /volumes/backup_name.tar.gz /dest

Restore containers

Now that you have your source Docker commandline-s, launch them to recreate containers.

Conclusion: I am thinking about making a reusable Powershell script


来源: stackexchange

问:
How to alert input value from JSON (javascript)
I have a problem trying to alert input values from json object. I get 'undefined' when i execute this code. Can someone please give me some ideas, I think I tried everything.
btw. I have to use JSON because it is my school project.
Thank you! xx</p>

```<code><script>
let arr = [];

function adduser(){
    let user = {
        name: document.getElementById("first_name").value,
        lname: document.getElementById("last_name").value,
        text: document.getElementById("txtara").value,
        email: document.getElementById("emails").value
    }

    arr.push(user);
    let json_str = JSON.stringify(arr);
    alert(json_str.name);
}
</script>
</code>```

答:
You're trying to "print" a value from string, that's not possible. If you want to convert your array to JSON and next "print" it on an alert, please try this:</p>

```<code>let user={
name:document.getElementById("first_name").value,
 lname:document.getElementById("last_name").value,
 text:document.getElementById("txtara").value,
 email:document.getElementById("emails").value
}
let json = JSON.parse(user);
alert(json.name);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You're trying to "print" a value from string, that's not possible. If you want to convert your array to JSON and next "print" it on an alert, please try this:

let user={
name:document.getElementById("first_name").value,
 lname:document.getElementById("last_name").value,
 text:document.getElementById("txtara").value,
 email:document.getElementById("emails").value
}
let json = JSON.parse(user);
alert(json.name);


问:
What Can I do to improve the 96% (f-score) in my CNN Keras?
I'm running a project with roughly 22000 images (11000 each class) with ResNet50 fine tuning. This is my code:

base_model = ResNet50(weights='imagenet', include_top=True, input_shape=(224,224,3))

head_model = base_model.get_layer("conv5_block1_1_conv").output

head_model = Dropout(0.75)(head_model)
head_model = Flatten()(head_model)
head_model = Dense(1, activation="sigmoid")(head_model)
model = Model(inputs=base_model.input, outputs=head_model)
model.summary()
for layer in base_model.layers:
    layer.trainable = False

adam = Adam(lr=0.001)
model.compile(optimizer= adam, loss='binary_crossentropy', metrics=['accuracy'])

train_datagen = ImageDataGenerator()
train_generator = train_datagen.flow_from_directory(TRAIN_DIR,
    target_size=(224, 224),
    batch_size=50,
    class_mode='binary')
model.fit_generator(train_generator, steps_per_epoch=100)

model.save("asd.h5")
```

With this model I reached 96 % of f-score. What method I can apply to improve its accuracy? I already tried include colormap as preprocessing and Include Dense layers.

答:
There're a lot of techniques:

You can change the structure of model. Add or remove some layers (and not only Dense layers). Or use other pretrained model.

Change the optimizer. For example, despite the Adam another popular optimizer is RMSprop. You can also try to tune optimizer's hyperparameters.

Preprocess data. You can do zoom, shear and etc.

Body:
I'm running a project with roughly 22000 images (11000 each class) with ResNet50 fine tuning. This is my code:

base_model = ResNet50(weights='imagenet', include_top=True, input_shape=(224,224,3))

head_model = base_model.get_layer("conv5_block1_1_conv").output

head_model = Dropout(0.75)(head_model)
head_model = Flatten()(head_model)
head_model = Dense(1, activation="sigmoid")(head_model)
model = Model(inputs=base_model.input, outputs=head_model)
model.summary()
for layer in base_model.layers:
    layer.trainable = False

adam = Adam(lr=0.001)
model.compile(optimizer= adam, loss='binary_crossentropy', metrics=['accuracy'])

train_datagen = ImageDataGenerator()
train_generator = train_datagen.flow_from_directory(TRAIN_DIR,
    target_size=(224, 224),
    batch_size=50,
    class_mode='binary')
model.fit_generator(train_generator, steps_per_epoch=100)

model.save("asd.h5")

With this model I reached 96 % of f-score. What method I can apply to improve its accuracy? I already tried include colormap as preprocessing and Include Dense layers.


问:
Compare two strings of ints in java
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10? </p>

```<code>String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";
</code>```

答: You can use Scanner.nextInt() to read numbers from the string, add them to a Set, and see if set1.equals(set2) is true.

ContentLicense: CC BY-SA 3.0

Title: Compare two strings of ints in java

Body:
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10?

String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";


问:
Credential handles keeps going in process monitor
Here I use the Microsoft Performance monitor to check the credentials handle for my c# application. I find the credentials handle keeps growing up. You can open performance monitor and add a "credentials handle" counter under "Security Per-Process Statistics". Will it cause handle leak? Will the handle be collected by GC? How can I use windbg or other tools to analyze this issue?

Here is my sample program:

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DBTest
{
    class DBTest2
    {
        class Program
        {
            [SuppressMessage("ReSharper", "InconsistentlySynchronizedField")]
            static void Work(object data)
            {
                var dbConn = new SqlConnection("*********");
                SqlConnection.ClearPool(dbConn);
                dbConn.Open();

                string sqlQuery = "SELECT DBName = name FROM master..sysdatabases WHERE name = @DBName";

                using (var command = new SqlCommand(sqlQuery, dbConn) { CommandTimeout = 300 })
                {
                    command.Parameters.Add(new SqlParameter("@DBName", SqlDbType.NVarChar) { Direction = ParameterDirection.Input, Value = "***" });

                    command.ExecuteScalar();
                }

                dbConn.Close();
            }

            static void Main(string[] args)
            {
                Timer tmr = new Timer(Work, "tick...", 1000 * 60 * 1, 30 * 1000);
                Console.ReadLine();
                tmr.Dispose();
                return;
            }
        }
    }
}
</code>```

答:
Put your SqlConnection in a using block as well:</p>

```<code>using (var dbConn = new SqlConnection("*********"))
{
}
</code>```

Body:
Here I use the Microsoft Performance monitor to check the credentials handle for my c# application. I find the credentials handle keeps growing up. You can open performance monitor and add a "credentials handle" counter under "Security Per-Process Statistics". Will it cause handle leak? Will the handle be collected by GC? How can I use windbg or other tools to analyze this issue?

Here is my sample program:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DBTest
{
    class DBTest2
    {
        class Program
        {
            [SuppressMessage("ReSharper", "InconsistentlySynchronizedField")]
            static void Work(object data)
            {
                var dbConn = new SqlConnection("*********");
                SqlConnection.ClearPool(dbConn);
                dbConn.Open();

                string sqlQuery = "SELECT DBName = name FROM master..sysdatabases WHERE name = @DBName";

                using (var command = new SqlCommand(sqlQuery, dbConn) { CommandTimeout = 300 })
                {
                    command.Parameters.Add(new SqlParameter("@DBName", SqlDbType.NVarChar) { Direction = ParameterDirection.Input, Value = "***" });

                    command.ExecuteScalar();
                }

                dbConn.Close();
            }

            static void Main(string[] args)
            {
                Timer tmr = new Timer(Work, "tick...", 1000 * 60 * 1, 30 * 1000);
                Console.ReadLine();
                tmr.Dispose();
                return;
            }
        }
    }
}

Body:
Put your SqlConnection in a using block as well:

using (var dbConn = new SqlConnection("*********"))
{
}


问:
Multiple IF condition based on previous and the current row - Pandas
I want to create a new column G which should display 1 if the previous row of D column contains a chrg or float and the current rows contains Dischrg. The first row should contain 0.

I want the pandas equivalent of the following excel code:

```<code>=IF(AND(D2="Chrg",D3="Dischrg"),G2+1,IF(AND(D2="Float",D3="Dischrg"),G2+1,0))
</code>```

```<code>D         G
Chrg      0
Dischrg   1
Float     0
Dischrg   0
Float     0
Dischrg   1
</code>```

答:
You can shift the column so you have the previous value in the same row:

In [1]: import pandas as pd
In [2]: df = pd.DataFrame([{"a": 1, "b": 1}, {"a": 2, "b": 2}, {"a": 3, "b": 3}])
In [3]: df
Out[3]:
   a  b
0  1  1
1  2  2
2  3  3

In [4]: df["prev"] = df.a.shift(1)

In [5]: df
Out[5]:
   a  b  prev
0  1  1   NaN
1  2  2   1.0
2  3  3   2.0
```

Body:
I want to create a new column G which should display 1 if the previous row of D column contains a chrg or float and the current rows contains Dischrg. The first row should contain 0.

I want the pandas equivalent of the following excel code:

=IF(AND(D2="Chrg",D3="Dischrg"),G2+1,IF(AND(D2="Float",D3="Dischrg"),G2+1,0))

D         G
Chrg      0
Dischrg   1
Float     0
Dischrg   0
Float     0
Dischrg   1


问:
Show transparent dialog in flutter
I want to disply a image in flutter in an transparent dialog. I've set opaque to false and used MaterialType.transparency. When I open the dialog the background is black.

```<code>class ShowProfileImage extends ModalRoute<void> {
  final String url;

  @override
  Duration get transitionDuration => Duration(milliseconds: 500);

  @override
  bool get opaque => false;

  @override
  bool get barrierDismissible => false;

  @override
  Color get barrierColor => Colors.black;

  @override
  String get barrierLabel => null;

  @override
  bool get maintainState => true;

  VoidCallback onDeleteImage;

  ShowProfileImage(String this.url);

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    // This makes sure that text and other content follows the material style
    return Material(
      type: MaterialType.transparency,
      // make sure that the overlay content is not cut off
      child: SafeArea(
        child: InkWell(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
                height: double.infinity,
                width: double.infinity,
                color: Colors.transparent,
                child: Center(
                    child: Container(
                        width: 300,
                        child: Image(image: NetworkImageWithRetry(url)))))),
      ),
    );
  }
}
</code>```

答:
Just call </p>

```<code>_showTransparentDialog(context);
</code>```

<p>Implementation: </p>

```<code>Future<T> _showTransparentDialog<T>(BuildContext context) async {
  return await showDialog<T>(
    context: context,
    builder: (_) {
      return AlertDialog(
        backgroundColor: Colors.transparent,
        content: Image.asset('your_image_asset'),
      );
    },
  );
}
</code>```

Title: Show transparent dialog in flutter

Body:
I want to disply a image in flutter in an transparent dialog. I've set opaque to false and used MaterialType.transparency. When I open the dialog the background is black.

class ShowProfileImage extends ModalRoute<void> {
  final String url;

  @override
  Duration get transitionDuration => Duration(milliseconds: 500);

  @override
  bool get opaque => false;

  @override
  bool get barrierDismissible => false;

  @override
  Color get barrierColor => Colors.black;

  @override
  String get barrierLabel => null;

  @override
  bool get maintainState => true;

  VoidCallback onDeleteImage;

  ShowProfileImage(String this.url);

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    // This makes sure that text and other content follows the material style
    return Material(
      type: MaterialType.transparency,
      // make sure that the overlay content is not cut off
      child: SafeArea(
        child: InkWell(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
                height: double.infinity,
                width: double.infinity,
                color: Colors.transparent,
                child: Center(
                    child: Container(
                        width: 300,
                        child: Image(image: NetworkImageWithRetry(url)))))),
      ),
    );
  }
}

Body:
Just call

_showTransparentDialog(context);

Implementation:

Future<T> _showTransparentDialog<T>(BuildContext context) async {
  return await showDialog<T>(
    context: context,
    builder: (_) {
      return AlertDialog(
        backgroundColor: Colors.transparent,
        content: Image.asset('your_image_asset'),
      );
    },
  );
}


问:
No-downtime Laravel deployment
I want to deploy a Laravel app from Gitlab to a server with no downtime. On the server, I serve the app with php artisan serve. Currently, I'm thinking that I would first copy all the files, then stop the old php artisan serve process on the server and start a new one on the server in the directory with the new files. However, this introduces a small downtime. Is there a way to avoid this?

答:
If you are serving with a single server, you can not achieve 0 downtime. If downtime is a crucial part of your system, then use two server and load balance between them smartly. Remember, no hosting or VPS provider ensure you to deliver 100% availability. So if you want to get 100% availability in the deployment process, in an irony situation, your site may have been down in another time. What I'm saying is that, if tiny moment of restarting php artisan serve is matter, then scale up to more than one server.
A workaround solution would be use some 3rd party service (like CloudFlare) which can smartly detect server down situation and notify user when it is back, I personally use that.
If you really want full uptime, docker with kubernetes is your technology.

Title: No-downtime Laravel deployment


问:
Streamlit Panda Query Function Syntax Error When Finding Column in CSV Dataframe
When Using Streamlit to build a data interface getting a syntax error.  My downloaded csv dataframe has a column 'NUMBER OF PERSONS INJURED', after converting it into a dataframe with panda and trying to use the query function to reference it I'm getting errors like below.  I converted the text to lower case in the dataframe.  I've attached the error message and sample csv file screenshot.  Github has code and sample csv file.  My questions are:

1. how to fix this error?  2. What's the underlying cause of it?

Code in Question:

```<code>injured_people = st.slider("", 0, 19)
st.map(data.query("number of persons injured > @injured_people")[["latitude", "longitude"]].dropna(how="any"))
</code>```

Error Message

csv sample shot of number of persons injured

Things I've tried:

adding '' to number of persons injured to convert to string.  But
then get error about st.slider being int and unable to operate with
> between str & int.

hacking the csv by converting number of persons injured with
underscore number_of_persons_injured but that throws undefined
error.

Converting @injured_people to a string. Yes stupid I know.  String() undefined error.

injured_people = st.slider("", 0, 19)

injured_people = string(injured_people)

Git File: https://github.com/petersun825/Bike_Crash_Dashboard_NYC/blob/master/app.py

答:
pandas does not know what you mean for the column name with spaces, which leads it to try and find a column number. You can escape the spaces with backticks:

st.map(data.query("`number of persons injured` > @injured_people")[["latitude", "longitude"]].dropna(how="any"))
```

Body:
When Using Streamlit to build a data interface getting a syntax error.  My downloaded csv dataframe has a column 'NUMBER OF PERSONS INJURED', after converting it into a dataframe with panda and trying to use the query function to reference it I'm getting errors like below.  I converted the text to lower case in the dataframe.  I've attached the error message and sample csv file screenshot.  Github has code and sample csv file.  My questions are:

1. how to fix this error?  2. What's the underlying cause of it?

Code in Question:

injured_people = st.slider("", 0, 19)
st.map(data.query("number of persons injured > @injured_people")[["latitude", "longitude"]].dropna(how="any"))

Error Message

csv sample shot of number of persons injured

Things I've tried:

adding '' to number of persons injured to convert to string.  But
then get error about st.slider being int and unable to operate with
> between str & int.

hacking the csv by converting number of persons injured with
underscore number_of_persons_injured but that throws undefined
error.

Converting @injured_people to a string. Yes stupid I know.  String() undefined error.

injured_people = st.slider("", 0, 19)

injured_people = string(injured_people)

Git File: https://github.com/petersun825/Bike_Crash_Dashboard_NYC/blob/master/app.py


问:
Google VM RAM for Minecraft Server
I've been tasking with creating a Minecraft server for about 500 players. I've never create a Minecraft server this large before and I think the best way to go about it is (how I've done all my other servers) with Google Cloud. Google Cloud has the following VM options:

I'm thinking about ~100MB per player to be on the safe side, so that's about 50 GB, so I'd say the n2-highmem-8 is probably a good VM to use. Is this overkill? Underkill?

Also, I know that a MC server can't use Multiple CPUs at the same time, so is it a waste paying for 8 Virtual CPUs?

Thanks!

答:
Minecraft has  FREE servers in the launcher
Step1
Step2

Title: Google VM RAM for Minecraft Server


问:
Is there a way to dynamically change the widgets displayed using Tkinter?
I am building a GUI with Tkinter in which I would like to give users the option of changing an entry widget to a label widget (and vice-versa) by clicking a button.

I have tried a few different approaches but can't get it to work. Here is one of the ways I've tried to approach this problem:

```<code>import tkinter as tk

show_label = False

class App(tk.Tk):

    def __init__(self):
        super().__init__()
        label = tk.Label(self, text="This is a label")
        entry = tk.Entry(self)
        button = tk.Button(self, text="Label/Entry",
                           command=self.change)
        if show_label:
            label.pack()
        else:
            entry.pack()

        button.pack()

    def change(self):
        global show_label
        show_label = not show_label
        self.update()

if __name__ == '__main__':
    app = App()
    app.mainloop()
</code>```

Aside from the above, I have also tried:

Updating the instance of app inside the mainloop, i.e. after instantiating app = App()

Making show_label a class variable and the change() a class method

Any help on the matter is greatly appreciated!

Thanks

答:
It appears that the mistake you're making is thinking that the code in __init__ runs more than once. It only runs once when you create an instance of App.

To fix your code, move the logic for displaying the entry or label into the code that runs when you click the button. Also,  you need to use instance variables to hold references to the widgets so that you can refer to them in other functions.

```<code>import tkinter as tk

class App(tk.Tk):

    def __init__(self):
        super().__init__()
        self.label = tk.Label(self, text="This is a label")
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Label/Entry",
                                command=self.change)
        self.button.pack()
        self.show_label = False

    def change(self):
        self.show_label = not self.show_label

        if self.show_label:
            self.entry.pack_forget()
            self.label.pack()
        else:
            self.label.pack_forget()
            self.entry.pack()

if __name__ == '__main__':
    app = App()
    app.mainloop()
</code>```

Body:
I am building a GUI with Tkinter in which I would like to give users the option of changing an entry widget to a label widget (and vice-versa) by clicking a button.

I have tried a few different approaches but can't get it to work. Here is one of the ways I've tried to approach this problem:

import tkinter as tk

show_label = False

class App(tk.Tk):

    def __init__(self):
        super().__init__()
        label = tk.Label(self, text="This is a label")
        entry = tk.Entry(self)
        button = tk.Button(self, text="Label/Entry",
                           command=self.change)
        if show_label:
            label.pack()
        else:
            entry.pack()

        button.pack()

    def change(self):
        global show_label
        show_label = not show_label
        self.update()

if __name__ == '__main__':
    app = App()
    app.mainloop()

Aside from the above, I have also tried:

Updating the instance of app inside the mainloop, i.e. after instantiating app = App()

Making show_label a class variable and the change() a class method

Any help on the matter is greatly appreciated!

Thanks

Body:
It appears that the mistake you're making is thinking that the code in __init__ runs more than once. It only runs once when you create an instance of App.

To fix your code, move the logic for displaying the entry or label into the code that runs when you click the button. Also,  you need to use instance variables to hold references to the widgets so that you can refer to them in other functions.

import tkinter as tk

class App(tk.Tk):

    def __init__(self):
        super().__init__()
        self.label = tk.Label(self, text="This is a label")
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Label/Entry",
                                command=self.change)
        self.button.pack()
        self.show_label = False

    def change(self):
        self.show_label = not self.show_label

        if self.show_label:
            self.entry.pack_forget()
            self.label.pack()
        else:
            self.label.pack_forget()
            self.entry.pack()

if __name__ == '__main__':
    app = App()
    app.mainloop()


问:
Add values from a list to each unique ID code [SQL]
I have a list of product names (Book, Car, Table). My table currently looks like this:

What i would like my table to show is all 3 products for each JobID e.g.:

So essentially for each distinct JobID, there should be 3 products.

How can I do this in SQL? This is a sample dataset, i'm actually working with a much larger and complex dataset but I would like to understand how to do this with a simple dataset and adapt it to my larger dataset.

答:
Use a cross join:

```<code>select j.jobid, p.productname
from (select distinct jobid from t) j cross join
     (select distinct productname from t) p
order by j.jobid, p.productname;
</code>```

Body:
Use a cross join:

select j.jobid, p.productname
from (select distinct jobid from t) j cross join
     (select distinct productname from t) p
order by j.jobid, p.productname;


问:
Navigate a URL with Query string values on click of hyperlink
I have a control with 'email' and 'password' textboxes and a 'autoLogin' checkbox. All are web form controls (not html controls). And there is a 'Login' hyperlink. When I click on heperlink, I want to move to other page using NavigateUrl property like below:

```<code>NavigateUrl="~/DoLogin.aspx?email={0}&pwd={1}&autoLogin={3}"
</code>```

how to pass and how to get the query string?

Thanks in Advance...

答:
I'm assuming your doing this because your DoLogin page has some login code in the Page_Load?

I really wouldn't recommend passing username/password credentials in a URL.

Like @Magnus has stated, it would be better to change the Hyperlink to a LinkButton and put your code in there.

Body:
I have a control with 'email' and 'password' textboxes and a 'autoLogin' checkbox. All are web form controls (not html controls). And there is a 'Login' hyperlink. When I click on heperlink, I want to move to other page using NavigateUrl property like below:

NavigateUrl="~/DoLogin.aspx?email={0}&pwd={1}&autoLogin={3}"

how to pass and how to get the query string?

Thanks in Advance...


问:
How to load test 10k requests per second using jmeter?
I need to load test my website with 10k req/sec for 1 hour using JMeter. I am confused with the values of loop count, number of thread, ramp-up period and duration.

Also will my laptop (i5 8GB) be able to do that? If not what is the alternative.

PS: I checked every question/answer on stackoverflow for this but I couldn't find any help. Please dont mark it repeated question.

答:
You can use "Constant Throughput Timer" and define target throughput and select throughput based on "all active threads".

Define maximum number of users count in your script so that it will be enough for 10K req/sec.

Also if you are using windows machine then I think you will face this issue "https://www.baselogic.com/2011/11/23/solved-java-net-bindexception-address-use-connect-issue-windows/"

I will recommend to use distributed testing or use more than 1 machine.


问:
Error: Could not parse the Android application Module's Gradle Config
I've been trying to setup Firebase in my Android project.
Problem is, I've been getting this error:

Could not parse the Android application Module's Gradle Config

And I really can't solve it.

I've seen quite a lot of people getting this error, but it seems that they could solve it by upgrading their build tool version, or by updating google-services. I've done all that and haven't been able to make it work so far.

Here are my Gradle scripts:

```<code>apply plugin: 'com.android.application'

android {
signingConfigs {
    AndroidAppPro {
    }
}
compileSdkVersion 25
buildToolsVersion '26.0.0'
useLibrary 'org.apache.http.legacy'
defaultConfig {
    applicationId "com.critizr.pro"
    minSdkVersion 14
    targetSdkVersion 25
    versionCode 9
    versionName "1.5.1"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
productFlavors {
    preprod {
        applicationId "com.cr.pro"
        buildConfigField 'boolean', 'IS_PROD', 'false'
        buildConfigField 'String', 'HOST', '"https://myurl.com/"'
    }
    prod {
        applicationId "com.cr.pro"
        buildConfigField 'boolean', 'IS_PROD', 'true'
        buildConfigField 'String', 'HOST', '"https://myurl/"'
    }
}
packagingOptions {
     exclude 'META-INF/DEPENDENCIES.txt'
     exclude 'META-INF/LICENSE.txt'
     exclude 'META-INF/NOTICE.txt'
     exclude 'META-INF/NOTICE'
     exclude 'META-INF/LICENSE'
     exclude 'META-INF/DEPENDENCIES'
     exclude 'META-INF/notice.txt'
     exclude 'META-INF/license.txt'
     exclude 'META-INF/dependencies.txt'
     exclude 'META-INF/LGPL2.1'
   }
}

dependencies {
compile project(':lib-viewflow')

// new libs
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:cardview-v7:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'

compile 'com.google.android.gms:play-services-gcm:11.0.2'
compile 'com.google.android.gms:play-services-maps:11.0.2'
//compile 'com.google.android.gms:play-services-analytics:11.0.1'

compile 'org.apache.httpcomponents:httpclient:4.1'
compile 'org.apache.httpcomponents:httpmime:4.1'

compile 'com.joshdholtz.sentry:sentry-android:1.5.0'
compile 'com.borax12.materialdaterangepicker:library:1.6'
compile 'com.github.PhilJay:MPAndroidChart:v2.2.5'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.cloudinary:cloudinary-core:1.2.2'
compile 'com.cloudinary:cloudinary-android:1.2.2'
compile 'com.loopj.android:android-async-http:1.4.5'
}
 apply plugin: 'com.google.gms.google-services'
</code>```

And the second one:

```<code> buildscript {
repositories {
    jcenter()
    maven { url "https://jitpack.io" }
}
 dependencies {
    classpath 'com.android.tools.build:gradle:2.3.1'
    classpath 'com.google.gms:google-services:3.1.0'
}
}

allprojects {
repositories {
    jcenter()
    maven { url "https://jitpack.io" }
}
}
</code>```

答:
Verify the build tab, and make sure you've got no warnings in there.

Firebase Assistant seems to be very sensitive to any Gradle info, warning, or error.

For me it was a simple "info" from gradle, that databinding.enabled is not required anymore:

```<code> DSL element 'android.dataBinding.enabled' is obsolete and has been replaced with 'android.buildFeatures.dataBinding'.
</code>```

Once removed, Firebase Assistant worked fine.

Body:
I've been trying to setup Firebase in my Android project.
Problem is, I've been getting this error:

Could not parse the Android application Module's Gradle Config

And I really can't solve it.

I've seen quite a lot of people getting this error, but it seems that they could solve it by upgrading their build tool version, or by updating google-services. I've done all that and haven't been able to make it work so far.

Here are my Gradle scripts:

apply plugin: 'com.android.application'

android {
signingConfigs {
    AndroidAppPro {
    }
}
compileSdkVersion 25
buildToolsVersion '26.0.0'
useLibrary 'org.apache.http.legacy'
defaultConfig {
    applicationId "com.critizr.pro"
    minSdkVersion 14
    targetSdkVersion 25
    versionCode 9
    versionName "1.5.1"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
productFlavors {
    preprod {
        applicationId "com.cr.pro"
        buildConfigField 'boolean', 'IS_PROD', 'false'
        buildConfigField 'String', 'HOST', '"https://myurl.com/"'
    }
    prod {
        applicationId "com.cr.pro"
        buildConfigField 'boolean', 'IS_PROD', 'true'
        buildConfigField 'String', 'HOST', '"https://myurl/"'
    }
}
packagingOptions {
     exclude 'META-INF/DEPENDENCIES.txt'
     exclude 'META-INF/LICENSE.txt'
     exclude 'META-INF/NOTICE.txt'
     exclude 'META-INF/NOTICE'
     exclude 'META-INF/LICENSE'
     exclude 'META-INF/DEPENDENCIES'
     exclude 'META-INF/notice.txt'
     exclude 'META-INF/license.txt'
     exclude 'META-INF/dependencies.txt'
     exclude 'META-INF/LGPL2.1'
   }
}

dependencies {
compile project(':lib-viewflow')

// new libs
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:cardview-v7:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'

compile 'com.google.android.gms:play-services-gcm:11.0.2'
compile 'com.google.android.gms:play-services-maps:11.0.2'
//compile 'com.google.android.gms:play-services-analytics:11.0.1'

compile 'org.apache.httpcomponents:httpclient:4.1'
compile 'org.apache.httpcomponents:httpmime:4.1'

compile 'com.joshdholtz.sentry:sentry-android:1.5.0'
compile 'com.borax12.materialdaterangepicker:library:1.6'
compile 'com.github.PhilJay:MPAndroidChart:v2.2.5'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.cloudinary:cloudinary-core:1.2.2'
compile 'com.cloudinary:cloudinary-android:1.2.2'
compile 'com.loopj.android:android-async-http:1.4.5'
}
 apply plugin: 'com.google.gms.google-services'

And the second one:

 buildscript {
repositories {
    jcenter()
    maven { url "https://jitpack.io" }
}
 dependencies {
    classpath 'com.android.tools.build:gradle:2.3.1'
    classpath 'com.google.gms:google-services:3.1.0'
}
}

allprojects {
repositories {
    jcenter()
    maven { url "https://jitpack.io" }
}
}

Body:
Verify the build tab, and make sure you've got no warnings in there.

Firebase Assistant seems to be very sensitive to any Gradle info, warning, or error.

For me it was a simple "info" from gradle, that databinding.enabled is not required anymore:

 DSL element 'android.dataBinding.enabled' is obsolete and has been replaced with 'android.buildFeatures.dataBinding'.

Once removed, Firebase Assistant worked fine.


问:
How to properly connect MySQL database with C# application?
I am trying to connect my MySQL database with C# but it's not getting connected.

I am using

```<code>static string connstring = @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";
</code>```

but still I am getting

Authentication to host 'my.live.ip' for user 'user' using method 'mysql_native_password' failed with message: Access denied for user 'user'@'202.xxx.xxx.xxx' (using password: NO)`

I have searched on it but didn't find any suitable solution(s).

P.S: The live IP that I am using is of azure. i.e. MySQL database is hosted on azure server via xampp

Any help would be highly appreciated

答:
You can just look it up but here’s come code anyway that I found:

Replace all port # usernames and password database name and server ip with what you need.

Code:

```<code>using System;
using System.Windows;
using MySql.Data.MySqlClient;

namespace Deportes_WPF
{

public partial class Login : Window
{
private MySqlConnection connection;
private string server;
private string database;
private string user;
private string password;
private string port;
private string connectionString;
private string sslM;

public Login()
{
    InitializeComponent();

    server = "server_name";
    database = "database_name";
    user = "user_id";
    password = "password";
    port = "3306";
    sslM = "none";

    connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);

    connection = new MySqlConnection(connectionString);
}

private void conexion()
{
    try
    {
        connection.Open();

        MessageBox.Show("successful connection");

        connection.Close();
    }
    catch (MySqlException ex)
    {
        MessageBox.Show(ex.Message + connectionString);
    }
}

private void btn1_Click(object sender, RoutedEventArgs e)
{
    conexion();
}
}

}
</code>```

I hope this code works for you.

It also looks like for the error you gave me that the username or password is invalid.

Body:
I am trying to connect my MySQL database with C# but it's not getting connected.

I am using

static string connstring = @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";

but still I am getting

Authentication to host 'my.live.ip' for user 'user' using method 'mysql_native_password' failed with message: Access denied for user 'user'@'202.xxx.xxx.xxx' (using password: NO)`

I have searched on it but didn't find any suitable solution(s).

P.S: The live IP that I am using is of azure. i.e. MySQL database is hosted on azure server via xampp

Any help would be highly appreciated

Body:
You can just look it up but here’s come code anyway that I found:

Replace all port # usernames and password database name and server ip with what you need.

Code:

using System;
using System.Windows;
using MySql.Data.MySqlClient;

namespace Deportes_WPF
{

public partial class Login : Window
{
private MySqlConnection connection;
private string server;
private string database;
private string user;
private string password;
private string port;
private string connectionString;
private string sslM;

public Login()
{
    InitializeComponent();

    server = "server_name";
    database = "database_name";
    user = "user_id";
    password = "password";
    port = "3306";
    sslM = "none";

    connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);

    connection = new MySqlConnection(connectionString);
}

private void conexion()
{
    try
    {
        connection.Open();

        MessageBox.Show("successful connection");

        connection.Close();
    }
    catch (MySqlException ex)
    {
        MessageBox.Show(ex.Message + connectionString);
    }
}

private void btn1_Click(object sender, RoutedEventArgs e)
{
    conexion();
}
}

}

I hope this code works for you.

It also looks like for the error you gave me that the username or password is invalid.


答:
Looks like homework. So these steps you can follow:

Trim both strings

Convert both strings into ArrayList using space separator

Sort both arrays numerically

Compare both arrays

Title: Compare two strings of ints in java


问:
Flutter DropdownButtonFormField.onChanged doesn't update UI
I have a screen with a DropdownButtonFormField:

```<code>var _list = ['foo', 'bar'];
String _value;

build() {
  ...
  DropdownButtonFormField(
    items: _items(ctx),
    onChanged: (item) => _onChanged(ctx, item),
    value: _value,
  )
  ...
}

List<DropdownMenuItem<String>> _items(ctx) {
  final specialNone = DropdownMenuItem(
    child: Text('NONE'),
    value: '#none',
  );
  final specialNew = DropdownMenuItem(
    child: Text('CREATE NEW'),
    value: '#new',
  );

  return [
    specialNone,
    specialNew,
    ..._list.map((o) => DropdownMenuItem(child: Text(o), value: o)).toList()
  ];
}

void _onChanged(ctx, String value) async {
  if (value == '#new') {
    final result = await Navigator.pushNamed(ctx, '/vendor');

    if (result != null)
      setState(() {
        _list.add(result);
        _value = result;
      });
  } else if (value == '#none')
    setState(() {
      _value = null;
    });
  else
    setState(() {
      _value = value;
    });
}
</code>```

There's a special item "CREATE NEW" in the items list. When clicked, a new item will be added to the list, and I want it to be selected instead of selecting "CREATE NEW".

NOTE: If you change DropdownButtonFormField to DropdownButton, it will work.

答: You can set the value of the onChanged to be null so the value cannot be changed.</p>

Body:
I have a screen with a DropdownButtonFormField:

var _list = ['foo', 'bar'];
String _value;

build() {
  ...
  DropdownButtonFormField(
    items: _items(ctx),
    onChanged: (item) => _onChanged(ctx, item),
    value: _value,
  )
  ...
}

List<DropdownMenuItem<String>> _items(ctx) {
  final specialNone = DropdownMenuItem(
    child: Text('NONE'),
    value: '#none',
  );
  final specialNew = DropdownMenuItem(
    child: Text('CREATE NEW'),
    value: '#new',
  );

  return [
    specialNone,
    specialNew,
    ..._list.map((o) => DropdownMenuItem(child: Text(o), value: o)).toList()
  ];
}

void _onChanged(ctx, String value) async {
  if (value == '#new') {
    final result = await Navigator.pushNamed(ctx, '/vendor');

    if (result != null)
      setState(() {
        _list.add(result);
        _value = result;
      });
  } else if (value == '#none')
    setState(() {
      _value = null;
    });
  else
    setState(() {
      _value = value;
    });
}

There's a special item "CREATE NEW" in the items list. When clicked, a new item will be added to the list, and I want it to be selected instead of selecting "CREATE NEW".

NOTE: If you change DropdownButtonFormField to DropdownButton, it will work.


答:
As Josef said in the comment, i had to look at : sklearn PolynomialFeature .

Then I found this answer :

    PolynomialFeatures(degree=3).get_feature_names()
```

<p>In the context :</p>

<pre class="lang-py prettyprint-override"><code>
    #%%  creating the model
    X = df[['x','y']].astype(float) #
    Y = df['z'].astype(float)

    polynomial_features_final= PolynomialFeatures(degree=3)
    #X3 = polynomial_features_final.fit_transform(X)

    X3 = polynomial_features_final.fit_transform(df[['x', 'y']].to_numpy())

    model = sm.OLS(Y, X3).fit()
    predictions = model.predict(X3)

    print_model = model.summary()
    print(print_model)

    print("\n-- ONE SOLUTION --\n Coef and Term name :")
    results = list(zip(model.params, polynomial_features_final.get_feature_names()))
    print(results)

</code>```

Title: extract formula from OLS Regression Results

Body:
My Goal is: Extracting the formula (not only the coefs) after a linear regression done with statsmodel.

Context :
I have a pandas dataframe ,

df
      x    y     z

0   0.0  2.0    54.200
1   0.0  2.2    70.160
2   0.0  2.4    89.000
3   0.0  2.6    110.960

i 'am doing a linear regression using statsmodels.api (2 variables, polynomial degree=3) , i'am happy with this regression.

OLS Regression Results
==============================================================================
Dep. Variable:                      z   R-squared:                       1.000
Model:                            OLS   Adj. R-squared:                  1.000
Method:                 Least Squares   F-statistic:                 2.193e+29
Date:                Sun, 31 May 2020   Prob (F-statistic):               0.00
Time:                        22:04:49   Log-Likelihood:                 9444.6
No. Observations:                 400   AIC:                        -1.887e+04
Df Residuals:                     390   BIC:                        -1.883e+04
Df Model:                           9
Covariance Type:            nonrobust
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const          0.2000   3.33e-11   6.01e+09      0.000       0.200       0.200
x1             2.0000   1.16e-11   1.72e+11      0.000       2.000       2.000
x2             1.0000   2.63e-11    3.8e+10      0.000       1.000       1.000
x3             4.0000   3.85e-12   1.04e+12      0.000       4.000       4.000
x4            12.0000   4.36e-12   2.75e+12      0.000      12.000      12.000
x5             3.0000   6.81e-12   4.41e+11      0.000       3.000       3.000
x6             6.0000   5.74e-13   1.05e+13      0.000       6.000       6.000
x7            13.0000   4.99e-13    2.6e+13      0.000      13.000      13.000
x8            14.0000   4.99e-13   2.81e+13      0.000      14.000      14.000
x9             5.0000   5.74e-13   8.71e+12      0.000       5.000       5.000
==============================================================================
Omnibus:                       25.163   Durbin-Watson:                   0.038
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               28.834
Skew:                          -0.655   Prob(JB):                     5.48e-07
Kurtosis:                       2.872   Cond. No.                     6.66e+03
==============================================================================

I need to implement that outside of python , (ms excel) , I would like to know the formula.

I know it is polynomial deg3 , but I wondering how to know which coeff apply to which term of
the equation. Something like that :

For exemple : x7 coeef is the coeff for x³ ,y², x²y , ... ?

Note: this is a simplify version of my problem , in reallity I have 3 variables ,  deg:3 so 20 coefs.

This is a simpler exemple of code to get started with my case:

# %% Question extract formula from linear regresion coeff
#Import
import numpy as np   # version : '1.18.1'
import pandas as pd  # version'1.0.0'

import statsmodels.api as sm   # version : '0.10.1'
from sklearn.preprocessing import PolynomialFeatures

from itertools import product

#%% Creating the dummies datas
def function_for_df(row):
    x= row['x']
    y= row['y']
    return  unknow_function(x,y)

def unknow_function(x,y):
    """
     This is to generate the datas , of  course in reality I do not know the formula
    """
    r =0.2+ \
       6*x**3+4*x**2+2*x+ \
       5*y**3+3*y**2+1*y+ \
       12*x*y + 13*x**2*y+ 14*x*y**2
    return r

# input data
x_input = np.arange(0, 4 , 0.2)
y_input = np.arange(2, 6 , 0.2)

# create a simple dataframe with dummies datas
df = pd.DataFrame(list(product(x_input, y_input)), columns=['x', 'y'])
df['z'] = df.apply(function_for_df, axis=1)

# In the reality I start from there !

#%%  creating the model
X = df[['x','y']].astype(float) #
Y = df['z'].astype(float)

polynomial_features_final= PolynomialFeatures(degree=3)
X3 = polynomial_features_final.fit_transform(X)

model = sm.OLS(Y, X3).fit()
predictions = model.predict(X3)

print_model = model.summary()
print(print_model)

#%% using the model to make predictions, no problem
def model_predict(x_sample, y_samples):
    df_input = pd.DataFrame({  "x":x_sample, "y":y_samples }, index=[0])
    X_input = polynomial_features_final.fit_transform(df_input)
    prediction = model.predict(X_input)
    return prediction

print("prediction for x=2, y=3.2 :" ,model_predict(2 ,3.2))

# How to extract the formula for the "model" ?
#Thanks

Side notes:

A desciption like the one given by pasty ModelDesc will be fine:

from patsy import ModelDesc
ModelDesc.from_formula("y ~ x")

# or even better :

desc = ModelDesc.from_formula("y ~ (a + b + c + d) ** 2")
desc.describe()

But i 'am not able to make the bridge between my model and patsy.ModelDesc.
Thanks for your help.

Body:
As Josef said in the comment, i had to look at : sklearn PolynomialFeature .

Then I found this answer :

    PolynomialFeatures(degree=3).get_feature_names()

In the context :

    #%%  creating the model
    X = df[['x','y']].astype(float) #
    Y = df['z'].astype(float)

    polynomial_features_final= PolynomialFeatures(degree=3)
    #X3 = polynomial_features_final.fit_transform(X)

    X3 = polynomial_features_final.fit_transform(df[['x', 'y']].to_numpy())

    model = sm.OLS(Y, X3).fit()
    predictions = model.predict(X3)

    print_model = model.summary()
    print(print_model)

    print("\n-- ONE SOLUTION --\n Coef and Term name :")
    results = list(zip(model.params, polynomial_features_final.get_feature_names()))
    print(results)


问:
I am having some issue while creating VM from ansible
I am using Ansible  version2. 2.9.9 and Python version 3.6.9; and I have installed requests modules too but every time I run my code I ger error of Mo Module name requests, I have changed the ansible_pythin_interpreter to python 3 as well but it didn't heled me. Please go through my code and help me here.

```<code>Traceback (most recent call last):
  File "/tmp/ansible_vmware_guest_payload_evshxlga/ansible_vmware_guest_payload.zip/ansible/module_utils/vmware.py", line 24, in <module>
    import requests
ImportError: No module named 'requests'

    "msg": "Failed to import the required Python library (requests) on Python /user/bin/python. Please read the module documentation and install it in the appropriate location. If the required library is installed, but Ansible is using the wrong Python interpreter, please consult the documentation on ansible_python_interpreter"
</code>```

I have uploaded my code as well

```<code>- hosts: vm
 # tasks:
#connection: local
  #gather_facts: no
  vars_prompt:
   - name: myuser
     prompt: Enter the UserName
     private: no
   - name: mypass
     prompt: Enter the Password
   - name: vc_name
     prompt: Enter the vCenter/ESXi HostName
     private: no
   - name: guest_name
     prompt: Enter the Guest VM Name
     private: no
   - name: hdd
     prompt: Enter the HardDrive Space you want to use
     private: no
   - name: ram
     prompt: Enter the RAM in MB
     private: no
   - name: cpu
     prompt: Enter the number of processor you want to use
     private: no
   - name: ip_addr
     prompt: Enter the Ip address you want to specify
     private: no
   - name: os_system
     private: no
     prompt: |
      Which os do you want to use?
      1- Windows Server
      2- CentOS_7
      3- CentOs_8
      4- Ubuntu
      5- Others
     tasks:
      set_fact: os_system == "Win server 2012.iso"
      when: (os_system == "1")
      set_fact: os_system == "CentOS-7-x86_64-Minimal-1804.iso"
      when: (os_systen == "2")
      set_fact: os_system == "CentOS-8-x86_64-1905-dvd1.iso"
      when: (os_system == "3")
      set_fact : os_system == "ubuntu-16.04.6-server-amd64.iso"
      when: (os_system == "4")

  remote_user: root

  tasks:
#  - name: Create a VM
     delegate_to: localhost

  - vmware_guest:
     hostname: "{{ vc_name }}"
     username: "{{ myuser }}"
     password: "{{ mypass }}"
     validate_certs: no
     folder: /DC1/vm/
     name: "{{guest_name}}"
     state: poweredon
     guest_id: "{{guest_name}}"
    # This is hostname of particular ESXi server on which user wants VM to be deployed
     esxi_hostname: "{{ vc_name }}"
     disk:
     - size_gb: "{{hdd}}"
       type: thin
       datastore: datastore1
     hardware:
       memory_mb: "{{ram}}"
       num_cpus: "{{cpu}}"
       scsi: paravirtual
     networks:
     - name: VM Network
      # mac: aa:bb:dd:aa:00:14
       ip: "{{ip_addr}}"
       netmask: 255.255.255.0
       device_type: vmnic0
     wait_for_ip_address: yes
     cdrom:
      type: iso
      iso_path: "vmfs/volumes/datastore1/Iso/{{os_system}}"
</code>```

答: this issue has been solved, I added delegate_to: localhost to my playbook and it solved the issue of Import Error : Request Module failed</p>

Body:
I am using Ansible  version2. 2.9.9 and Python version 3.6.9; and I have installed requests modules too but every time I run my code I ger error of Mo Module name requests, I have changed the ansible_pythin_interpreter to python 3 as well but it didn't heled me. Please go through my code and help me here.

Traceback (most recent call last):
  File "/tmp/ansible_vmware_guest_payload_evshxlga/ansible_vmware_guest_payload.zip/ansible/module_utils/vmware.py", line 24, in <module>
    import requests
ImportError: No module named 'requests'

    "msg": "Failed to import the required Python library (requests) on Python /user/bin/python. Please read the module documentation and install it in the appropriate location. If the required library is installed, but Ansible is using the wrong Python interpreter, please consult the documentation on ansible_python_interpreter"

I have uploaded my code as well

- hosts: vm
 # tasks:
#connection: local
  #gather_facts: no
  vars_prompt:
   - name: myuser
     prompt: Enter the UserName
     private: no
   - name: mypass
     prompt: Enter the Password
   - name: vc_name
     prompt: Enter the vCenter/ESXi HostName
     private: no
   - name: guest_name
     prompt: Enter the Guest VM Name
     private: no
   - name: hdd
     prompt: Enter the HardDrive Space you want to use
     private: no
   - name: ram
     prompt: Enter the RAM in MB
     private: no
   - name: cpu
     prompt: Enter the number of processor you want to use
     private: no
   - name: ip_addr
     prompt: Enter the Ip address you want to specify
     private: no
   - name: os_system
     private: no
     prompt: |
      Which os do you want to use?
      1- Windows Server
      2- CentOS_7
      3- CentOs_8
      4- Ubuntu
      5- Others
     tasks:
      set_fact: os_system == "Win server 2012.iso"
      when: (os_system == "1")
      set_fact: os_system == "CentOS-7-x86_64-Minimal-1804.iso"
      when: (os_systen == "2")
      set_fact: os_system == "CentOS-8-x86_64-1905-dvd1.iso"
      when: (os_system == "3")
      set_fact : os_system == "ubuntu-16.04.6-server-amd64.iso"
      when: (os_system == "4")

  remote_user: root

  tasks:
#  - name: Create a VM
     delegate_to: localhost

  - vmware_guest:
     hostname: "{{ vc_name }}"
     username: "{{ myuser }}"
     password: "{{ mypass }}"
     validate_certs: no
     folder: /DC1/vm/
     name: "{{guest_name}}"
     state: poweredon
     guest_id: "{{guest_name}}"
    # This is hostname of particular ESXi server on which user wants VM to be deployed
     esxi_hostname: "{{ vc_name }}"
     disk:
     - size_gb: "{{hdd}}"
       type: thin
       datastore: datastore1
     hardware:
       memory_mb: "{{ram}}"
       num_cpus: "{{cpu}}"
       scsi: paravirtual
     networks:
     - name: VM Network
      # mac: aa:bb:dd:aa:00:14
       ip: "{{ip_addr}}"
       netmask: 255.255.255.0
       device_type: vmnic0
     wait_for_ip_address: yes
     cdrom:
      type: iso
      iso_path: "vmfs/volumes/datastore1/Iso/{{os_system}}"


问:
WeldContainer and SeContainer
What is the difference between using:

WeldContainer se = new Weld().initialize();

or

SeContainer se = SeContainerInitializer.newInstance().initialize();

I just want to use @Injection and @Produce annotations, but I have not found the difference between these two ways of initializing an object instance.

答:
Context and Dependency Injection (CDI) is a specification. That means it defines an API only and does not provide an implementation. That's why you have to include an implementation such as Weld in order to actually use the API. The WeldContainer class is vendor-specific whereas the SeContainer interface is part of the specification. The former implements the latter.

The SeContainerInitializer class, which is part of the API, will delegate to the implementation included with the application. So if you use Weld as the implementation then ultimately using SeContainerInitializer and SeContainer is the same as using Weld and WeldContainer "under the hood".

From a purist's perspective it's best to rely only on the specification's interface and never directly depend on the implementation. That way you can swap vendors if and when you need to since you're using functionality common to all implementations. However, often times an implementation provides more functionality than what's required by the specification. In order to use that functionality you have to directly depend on the implementation.

In other words, whether you use Weld / WeldContainer or SeContainerInitialializer / SeContainer depends on the (current and future) requirements of your application. When in doubt, program to the interface.

Note this separation between the API and implementation is not unique to CDI. Pretty much the entire Java EE—or as it's now known, Jakarta EE—API works this way. An example would be the Java Persistence API (JPA) and Hibernate or EclipseLink (two implementations). For an example within Java SE there's the Java Database Connectivity (JDBC) API and the various implementations (i.e. drivers).

Title: WeldContainer and SeContainer


问:
Any UnhandledException are not caught from ComboBox on INotifyPropertyChanged, while Button does
Given a WPF Core/Framework application. Unhandled Exceptions should be caught by some UnhandledException event.

```<code>TaskScheduler.UnobservedTaskException += (s, e) => Debugger.Break();
AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => Debugger.Break();
Dispatcher.UnhandledException += (sender, args) => Debugger.Break();
DispatcherUnhandledException += (sender, eventArgs) => Debugger.Break();
</code>```

Given is an ObservableCollection<TItem> collection presented by a combobox.
The collection also fires ItemPropertyChanged events.

```<code>Collection.CollectionChanged += ItemsCollectionChanged;

public event PropertyChangedEventHandler PropertyItemChanged = delegate { };

private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.OldItems != null)
    {
        foreach (INotifyPropertyChanged item in e.OldItems)
            item.PropertyChanged -= ItemPropertyChanged;
    }

    if (e.NewItems != null)
    {
        foreach (INotifyPropertyChanged item in e.NewItems)
            item.PropertyChanged += ItemPropertyChanged;
    }
}
</code>```

The issue was I didn't implement

```<code>private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    throw new NotImplementedException("ToDo");
    // done later PropertyItemChanged(sender, e);
}
</code>```

When I change the collection item property from code behind/view model like this

```<code>ComboBoxCatalog.Collection.First().IsChecked = true;
</code>```

everything is fine. The debugger stops on some UnhandledException.

Now when I change an property by combobox:

```<code><ComboBox ItemsSource="{Binding ComboBoxCatalog.Collection, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="{x:Type local:CheckboxItem}">
            <CheckBox Content="{Binding IsChecked}" IsChecked="{Binding IsChecked}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
</code>```

None of these UnhandledException are fired. Only FirstChanceException are fired.

I have implemented a full working demo on Github: https://github.com/LwServices/WpfAppExceptionDemo

What need to be done that the exception will fire UnhandledException ?

Update: I get the same behavior on .NET Core 3.1 and .NET Framework 4.7.2

答:
The exception is catched and handled for you by the framework.

If you look in the output window while you are debugging in Visual Studio, you'll see that the debugger outputs a System.Windows.Data Error message:

```<code>System.Windows.Data Error: 8 : Cannot save value from target back to source. ...
</code>```

If you want to turn this kind of errors into runtime exceptions that you can catch yourself in your global error handler, you could implement your own TraceListener as suggested here.

Body:
Given a WPF Core/Framework application. Unhandled Exceptions should be caught by some UnhandledException event.

TaskScheduler.UnobservedTaskException += (s, e) => Debugger.Break();
AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => Debugger.Break();
Dispatcher.UnhandledException += (sender, args) => Debugger.Break();
DispatcherUnhandledException += (sender, eventArgs) => Debugger.Break();

Given is an ObservableCollection<TItem> collection presented by a combobox.
The collection also fires ItemPropertyChanged events.

Collection.CollectionChanged += ItemsCollectionChanged;

public event PropertyChangedEventHandler PropertyItemChanged = delegate { };

private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.OldItems != null)
    {
        foreach (INotifyPropertyChanged item in e.OldItems)
            item.PropertyChanged -= ItemPropertyChanged;
    }

    if (e.NewItems != null)
    {
        foreach (INotifyPropertyChanged item in e.NewItems)
            item.PropertyChanged += ItemPropertyChanged;
    }
}

The issue was I didn't implement

private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    throw new NotImplementedException("ToDo");
    // done later PropertyItemChanged(sender, e);
}

When I change the collection item property from code behind/view model like this

ComboBoxCatalog.Collection.First().IsChecked = true;

everything is fine. The debugger stops on some UnhandledException.

Now when I change an property by combobox:

<ComboBox ItemsSource="{Binding ComboBoxCatalog.Collection, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="{x:Type local:CheckboxItem}">
            <CheckBox Content="{Binding IsChecked}" IsChecked="{Binding IsChecked}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

None of these UnhandledException are fired. Only FirstChanceException are fired.

I have implemented a full working demo on Github: https://github.com/LwServices/WpfAppExceptionDemo

What need to be done that the exception will fire UnhandledException ?

Update: I get the same behavior on .NET Core 3.1 and .NET Framework 4.7.2

Body:
The exception is catched and handled for you by the framework.

If you look in the output window while you are debugging in Visual Studio, you'll see that the debugger outputs a System.Windows.Data Error message:

System.Windows.Data Error: 8 : Cannot save value from target back to source. ...

If you want to turn this kind of errors into runtime exceptions that you can catch yourself in your global error handler, you could implement your own TraceListener as suggested here.


问:
GUI Framework Plugin Design
As a plugin framework developer, I want to specify an interface, myNameSpace.IPlugin, that the plugins must implement. The return value of one of the interface members, IPlugin.GetWidget(),  must be of a type derived from System.Windows.Forms.Control and it also must implement myNameSpace.IFoo interface. I also want to allow the plugin developers to return third party controls (which are already System.Windows.Forms.Control descendents) from IPlugin.GetWidget(). What is the best way to unambiguously specify this requirement , other than documenting it, ofcourse :) , and enforce it ? How would a plugin developer go about desigining a plugin (using a 3rd party control) to meet these requirements ?</p>

答:
Your design smells a little fishy. Why must widgets both inherit from a concrete class and implement another unrelated interface? Sounds like you're a little inheritance-happy. Instead of that, try this:

```<code>interface IPlugin
{
    IWidget Widget { get; }
}

interface IWidget
{
    System.Windows.Forms.Control Control { get; }
    IFoo Foo { get; }
}
</code>```

Whether IFoo is implemented by the control itself or by another class should really be up to the implementer. Your code shouldn't care.

OwnerDisplayName: Ash Tewari

ContentLicense: CC BY-SA 2.5

Title: GUI Framework Plugin Design

Body:
Your design smells a little fishy. Why must widgets both inherit from a concrete class and implement another unrelated interface? Sounds like you're a little inheritance-happy. Instead of that, try this:

interface IPlugin
{
    IWidget Widget { get; }
}

interface IWidget
{
    System.Windows.Forms.Control Control { get; }
    IFoo Foo { get; }
}

Whether IFoo is implemented by the control itself or by another class should really be up to the implementer. Your code shouldn't care.

OwnerDisplayName: munificent


问:
Iterate through an array of characters in C
Recently I saw this while loop condition in C in the example below but I have no idea what the while condition really means and how the compiler knows when it is done. Could someone explain it to me?

This is what I believe it means: while loop iterates through the char array until the ending of the array since there is nothing else then the while loop ends, or am I wrong? I tried to use the same while loop but in another language such as Go, however, the compiler threw an error saying that I cannot use a non-bool.

```<code>// C program to demonstrate
// example of tolower() function.

#include <ctype.h>
#include <stdio.h>

int main()
{
    int j = 0;
    char str[] = "GEEKSFORGEEKS\n";

    // Character to be converted to lowercase
    char ch = 'G';

    // convert ch to lowercase using toLower()
    char ch;

    while (str[j]) { // <- this part, how is this a condition?
        ch = str[j];

        // convert ch to lowercase using toLower()
        putchar(tolower(ch));

        j++;
    }

    return 0;
}
</code>```

答:
You can think of an array of chars as following:

So as you see in the picture an array of chars is already a pointer, and each of the characters has an address, as well that the address of a pointer is the address of the first element, so when you declared

```<code>char str[] = "GEEKSFORGEEKS\n";
</code>```

it was allocated in the memory like below:

```<code>[G][E][E][K][S][F][O][R][G][E][E][K][S][\n][\0]
</code>```

The program will crash because you have a redeclaration of ch variable, as well there is no need to initialize the char ch = 'G'; since you're overriding it in the while loop and it will take str[j], and so you started iterating at j = 0 which the 1st index in the array [G], as you're incrementing the loop will go until the null character [\0] and stop because there's no iteration after the NULL, in other examples you might see the following condition in the loop: while(str[j] != '\0') which is similar to your condition but just more specific.

You can gain more performance by iterating through the pointer just like the following:

```<code>#include <ctype.h>
#include <stdio.h>

int main()
{
    char *str = "GEEKSFORGEEKS\n";

    while (*str)
        putchar(tolower(*str++));

    return 0;
}
</code>```

Body:
Recently I saw this while loop condition in C in the example below but I have no idea what the while condition really means and how the compiler knows when it is done. Could someone explain it to me?

This is what I believe it means: while loop iterates through the char array until the ending of the array since there is nothing else then the while loop ends, or am I wrong? I tried to use the same while loop but in another language such as Go, however, the compiler threw an error saying that I cannot use a non-bool.

// C program to demonstrate
// example of tolower() function.

#include <ctype.h>
#include <stdio.h>

int main()
{
    int j = 0;
    char str[] = "GEEKSFORGEEKS\n";

    // Character to be converted to lowercase
    char ch = 'G';

    // convert ch to lowercase using toLower()
    char ch;

    while (str[j]) { // <- this part, how is this a condition?
        ch = str[j];

        // convert ch to lowercase using toLower()
        putchar(tolower(ch));

        j++;
    }

    return 0;
}

Body:
You can think of an array of chars as following:

So as you see in the picture an array of chars is already a pointer, and each of the characters has an address, as well that the address of a pointer is the address of the first element, so when you declared

char str[] = "GEEKSFORGEEKS\n";

it was allocated in the memory like below:

[G][E][E][K][S][F][O][R][G][E][E][K][S][\n][\0]

The program will crash because you have a redeclaration of ch variable, as well there is no need to initialize the char ch = 'G'; since you're overriding it in the while loop and it will take str[j], and so you started iterating at j = 0 which the 1st index in the array [G], as you're incrementing the loop will go until the null character [\0] and stop because there's no iteration after the NULL, in other examples you might see the following condition in the loop: while(str[j] != '\0') which is similar to your condition but just more specific.

You can gain more performance by iterating through the pointer just like the following:

#include <ctype.h>
#include <stdio.h>

int main()
{
    char *str = "GEEKSFORGEEKS\n";

    while (*str)
        putchar(tolower(*str++));

    return 0;
}


问:
Compare images Python PIL
How can I compare two images? I found Python's PIL library, but I do not really understand how it works.</p>

答:
based on Victor Ilyenko's answer, I needed to convert the images to RGB as PIL fails silently when the .png you're trying to compare contains a alpha channel.</p>

```<code>image_one = Image.open(path_one).convert('RGB')
image_two = Image.open(path_two).convert('RGB')
</code>```

Title: Compare images Python PIL

Body:
based on Victor Ilyenko's answer, I needed to convert the images to RGB as PIL fails silently when the .png you're trying to compare contains a alpha channel.

image_one = Image.open(path_one).convert('RGB')
image_two = Image.open(path_two).convert('RGB')


问:
Math.log10 javascript polyfill
As described in MDN the following polyfill can be used for Math.log10:

```<code>Math.log10 = Math.log10 || function(x) {
  return Math.log(x) / Math.LN10;
};
</code>```

Unfortunately, due to floating point arithmetic (in the non native implementation), this:

```<code>Math.log10(1000000)
</code>```

will result to:

```<code>=> 5.999999999999999
</code>```

One way to get around this issue is to do some rounding:

```<code>rounding_const = 1000000;

function log10(n) {
  return Math.round(rounding_const * Math.log(n) / Math.LN10) / rounding_const;
}
</code>```

Is there a better approach (algorithmic?) which will not involve hacky rounding?

答:
```<code>Math.log10 = function (x) {
  if (!(x > 0 && x < 1 / 0)) {
    return Math.log(x) * Math.LOG10E;
  }
  var n = Math.round(Math.log(Math.min(Math.max(x, 10 / Number.MAX_VALUE), Number.MAX_VALUE / 10)) * Math.LOG10E);
  return n + Math.log(x / Math.pow(10, n)) * Math.LOG10E;
};
</code>```

Title: Math.log10 javascript polyfill

Body:
As described in MDN the following polyfill can be used for Math.log10:

Math.log10 = Math.log10 || function(x) {
  return Math.log(x) / Math.LN10;
};

Unfortunately, due to floating point arithmetic (in the non native implementation), this:

Math.log10(1000000)

will result to:

=> 5.999999999999999

One way to get around this issue is to do some rounding:

rounding_const = 1000000;

function log10(n) {
  return Math.round(rounding_const * Math.log(n) / Math.LN10) / rounding_const;
}

Is there a better approach (algorithmic?) which will not involve hacky rounding?


问:
How to set view in matplolib FigureCanvas programmatically?
```<code>from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from PyQt5 import QtCore
from PyQt5 import QtWidgets

class MyFigure(QtCore.QObject):
    def __init__(self):
        self.widget = QtWidgets.QWidget()
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.widget)
        self.axis = self.fig.add_subplot(111)
        self.toolbar = NavigationToolbar(self.canvas, self.widget)

    def plot(self, x, y):
        self.axis.plot(x, y)
        self.canvas.draw()

    def set_view(self, xmin, xmax, ymin, ymax):
        # how can I do that?

</code>```

With the NavigationToolbar I can use pan and zoom to interactively set the view to a particular region of the plot in FigureCanvas.

How can I set the FigureCanvas view programmatically to a region (xmin, xmax, ymin, ymax)?

答:
This seems to do the trick:</p>

```<code>def set_view(self, xmin, xmax, ymin, ymax):
    if self.toolbar._nav_stack() is None:
        # otherwise the zoomed view will be the first in the stack
        self.toolbar.push_current()
    # Call the _set_view method of the "Axes" instance
    self.axis._set_view((xlo, xhi, ylo, yhi))
    self.toolbar.draw()
    # add the new view to the navigation stack:
    self.toolbar.push_current()
</code>```

Body:
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from PyQt5 import QtCore
from PyQt5 import QtWidgets

class MyFigure(QtCore.QObject):
    def __init__(self):
        self.widget = QtWidgets.QWidget()
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.widget)
        self.axis = self.fig.add_subplot(111)
        self.toolbar = NavigationToolbar(self.canvas, self.widget)

    def plot(self, x, y):
        self.axis.plot(x, y)
        self.canvas.draw()

    def set_view(self, xmin, xmax, ymin, ymax):
        # how can I do that?

With the NavigationToolbar I can use pan and zoom to interactively set the view to a particular region of the plot in FigureCanvas.

How can I set the FigureCanvas view programmatically to a region (xmin, xmax, ymin, ymax)?

Body:
This seems to do the trick:

def set_view(self, xmin, xmax, ymin, ymax):
    if self.toolbar._nav_stack() is None:
        # otherwise the zoomed view will be the first in the stack
        self.toolbar.push_current()
    # Call the _set_view method of the "Axes" instance
    self.axis._set_view((xlo, xhi, ylo, yhi))
    self.toolbar.draw()
    # add the new view to the navigation stack:
    self.toolbar.push_current()


问:
Delegates and protocols with VC not connected
I have a parent view controller i.e. HomeViewController which has a navigation bar button via which a user can trigger an alert and enter a string. This string needs to be passed to the child view controller.

Here is the relevant code in the parent view controller:

```<code>protocol NewSectionDelegate {
    func sendSectionName(name : String)
}

class HomeViewController: UIViewController {
var sectionNameDelegate : NewSectionDelegate?

func addCardAsChild() { // add the child VC to the parent VC
if cardViewController == nil {
                cardViewController = CardViewController()
                addViewController(newViewController: cardViewController!)
            } else {
                addViewController(newViewController: cardViewController!)
            }
}

func triggerAlert() {
let alertController = UIAlertController(title: "New section", message: "Name the section with a words or a sentence", preferredStyle: .alert)
                alertController.addTextField(configurationHandler:
                    {(_ textField: UITextField) -> Void in //txtview customization
                    })

                let addAction = UIAlertAction(title: "Add", style: .default) { _ in
                    guard let sectionName = alertController.textFields?.first?.text else { return }
                    self.sectionNameDelegate?.sendSectionName(name: sectionName) // Sending string; verified that the string is not nil
                }

                alertController.addAction(addAction)
                self.present(alertController, animated: true, completion: nil)
}
</code>```

And here is the child view controller:

```<code>class CardViewController: UIViewController,  NewSectionDelegate {

override func viewDidLoad() {
        super.viewDidLoad()
        let homeViewController = HomeViewController()
        homeViewController.sectionNameDelegate = self
     }

    func sendSectionName(name: String) {
print("received name:\(name)") // This line of code is never called
}
</code>```

The data is not getting passed and I have no idea why.

答: I think the delegate method is getting called but for the internal HomeViewController you're making in the ChildViewController viewDidLoad method.  It looks like you're expecting the method to get called on a different object.  I would remove that code from viewDidLoad and set the sectionNameDelegate in HomeViewController

Body:
I have a parent view controller i.e. HomeViewController which has a navigation bar button via which a user can trigger an alert and enter a string. This string needs to be passed to the child view controller.

Here is the relevant code in the parent view controller:

protocol NewSectionDelegate {
    func sendSectionName(name : String)
}

class HomeViewController: UIViewController {
var sectionNameDelegate : NewSectionDelegate?

func addCardAsChild() { // add the child VC to the parent VC
if cardViewController == nil {
                cardViewController = CardViewController()
                addViewController(newViewController: cardViewController!)
            } else {
                addViewController(newViewController: cardViewController!)
            }
}

func triggerAlert() {
let alertController = UIAlertController(title: "New section", message: "Name the section with a words or a sentence", preferredStyle: .alert)
                alertController.addTextField(configurationHandler:
                    {(_ textField: UITextField) -> Void in //txtview customization
                    })

                let addAction = UIAlertAction(title: "Add", style: .default) { _ in
                    guard let sectionName = alertController.textFields?.first?.text else { return }
                    self.sectionNameDelegate?.sendSectionName(name: sectionName) // Sending string; verified that the string is not nil
                }

                alertController.addAction(addAction)
                self.present(alertController, animated: true, completion: nil)
}

And here is the child view controller:

class CardViewController: UIViewController,  NewSectionDelegate {

override func viewDidLoad() {
        super.viewDidLoad()
        let homeViewController = HomeViewController()
        homeViewController.sectionNameDelegate = self
     }

    func sendSectionName(name: String) {
print("received name:\(name)") // This line of code is never called
}

The data is not getting passed and I have no idea why.


问:
Python: Cannot install python module "pyautogui"
I can't install python module called "pyautogui" on windows 10 with python version 3.8

CMD:

```<code>C:\Users\Миша>pip install pyautogui
Collecting pyautogui
  Using cached PyAutoGUI-0.9.50.tar.gz (57 kB)
Collecting pymsgbox
  Using cached PyMsgBox-1.0.8.tar.gz (18 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    ERROR: Command errored out with exit status 1:
     command: 'c:\python38\python.exe' 'c:\python38\lib\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\CA81~1\AppData\Local\Temp\tmphpcf9lnw'
         cwd: C:\Users\Миша\AppData\Local\Temp\pip-install-rzx8xe3p\pymsgbox
    Complete output (14 lines):
    running dist_info
    creating C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info
    writing C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\PKG-INFO
    writing dependency_links to C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\dependency_links.txt
    writing top-level names to C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\top_level.txt
    writing manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    reading manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    Error in sitecustomize; set PYTHONVERBOSE for traceback:
    SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xcc in position 0: invalid continuation byte (sitecustomize.py, line 21)
    warning: no files found matching '*.py' under directory 'pymsgbox'
    writing manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    creating 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.dist-info'
    error: invalid command 'bdist_wheel'
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\python38\python.exe' 'c:\python38\lib\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\CA81~1\AppData\Local\Temp\tmphpcf9lnw' Check the logs for full command output.
</code>```

I haven't tried to do something yet because I don't understand the error. Any ideas?

答: From the official documentation, it is mentioned to use "pip install PyAutoGUI" (follow the proper casing).  I used the same and is working for me.  </p>

Body:
I can't install python module called "pyautogui" on windows 10 with python version 3.8

CMD:

C:\Users\Миша>pip install pyautogui
Collecting pyautogui
  Using cached PyAutoGUI-0.9.50.tar.gz (57 kB)
Collecting pymsgbox
  Using cached PyMsgBox-1.0.8.tar.gz (18 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    ERROR: Command errored out with exit status 1:
     command: 'c:\python38\python.exe' 'c:\python38\lib\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\CA81~1\AppData\Local\Temp\tmphpcf9lnw'
         cwd: C:\Users\Миша\AppData\Local\Temp\pip-install-rzx8xe3p\pymsgbox
    Complete output (14 lines):
    running dist_info
    creating C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info
    writing C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\PKG-INFO
    writing dependency_links to C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\dependency_links.txt
    writing top-level names to C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\top_level.txt
    writing manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    reading manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    Error in sitecustomize; set PYTHONVERBOSE for traceback:
    SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xcc in position 0: invalid continuation byte (sitecustomize.py, line 21)
    warning: no files found matching '*.py' under directory 'pymsgbox'
    writing manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    creating 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.dist-info'
    error: invalid command 'bdist_wheel'
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\python38\python.exe' 'c:\python38\lib\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\CA81~1\AppData\Local\Temp\tmphpcf9lnw' Check the logs for full command output.

I haven't tried to do something yet because I don't understand the error. Any ideas?


问:
Regex Capture one word OR two words in quotes
I'm trying to implement gmail style filters in my search and I'm stuck at this regex problem. I need to capture ONE word OR two words in quotes (but without the quotation marks themselves) This is PCRE (PHP)

ie.

```<code>name:mark
</code>```

desired result: 1st capture group should be mark

```<code>name:"mark"
</code>```

desired result: 1st capture group should be mark

```<code>name:"mark wilson"
</code>```

desired result: 1st capture group should be mark, second capture group should be wilson

```<code>name:mark wilson
</code>```

desired result: 1st capture group should be mark, wilson is ignored

The closest I've gotten is name:(\w+|\"\w+(?>\"|\s([a-z.'-]+\"))) it captures example 1 perfectly, but example 2 still includes the quotes, and example 3 ends up as:

group 1: "mark wilson"  (quotes included)

group 2: wilson"        (quote included)

I've tried lookahead and lookbehinds but I'm not getting anywhere with those either

any help would be very appreciated. tia

答:
The main point is that you cannot do that for arbitrary amount of groups, you must specify them all in the pattern at design time.

You may use a pattern like this with a branch reset group:

```<code>\w+:(?|(\w+)|"(\w+)(?:\h+(\w+))?(?:\h+(\w+))?")
</code>```

See the regex demo. Add more (?:\h+(\w+))? patterns at the end to support up to N amount of optional words.

Details

\w+: - 1+ word chars and then a :

(?|(\w+)|"(\w+)(?:\h+(\w+))?(?:\h+(\w+))?")  - a branch reset group where groups share the same IDs:

(\w+) - Group 1: one or more word chars

| - or

"(\w+)(?:\h+(\w+))?(?:\h+(\w+))?" -

" - a " char

(\w+) - Group 1: one or more word chars

(?:\h+(\w+))? - an optional occurrence of a sequences:

\h+ - 1 or more horizontal whitespaces

(\w+) - Group 2: one or more word chars

(?:\h+(\w+))?" - ibid, but with Group 3, etc.

Body:
I'm trying to implement gmail style filters in my search and I'm stuck at this regex problem. I need to capture ONE word OR two words in quotes (but without the quotation marks themselves) This is PCRE (PHP)

ie.

name:mark

desired result: 1st capture group should be mark

name:"mark"

desired result: 1st capture group should be mark

name:"mark wilson"

desired result: 1st capture group should be mark, second capture group should be wilson

name:mark wilson

desired result: 1st capture group should be mark, wilson is ignored

The closest I've gotten is name:(\w+|\"\w+(?>\"|\s([a-z.'-]+\"))) it captures example 1 perfectly, but example 2 still includes the quotes, and example 3 ends up as:

group 1: "mark wilson"  (quotes included)

group 2: wilson"        (quote included)

I've tried lookahead and lookbehinds but I'm not getting anywhere with those either

any help would be very appreciated. tia

Body:
The main point is that you cannot do that for arbitrary amount of groups, you must specify them all in the pattern at design time.

You may use a pattern like this with a branch reset group:

\w+:(?|(\w+)|"(\w+)(?:\h+(\w+))?(?:\h+(\w+))?")

See the regex demo. Add more (?:\h+(\w+))? patterns at the end to support up to N amount of optional words.

Details

\w+: - 1+ word chars and then a :

(?|(\w+)|"(\w+)(?:\h+(\w+))?(?:\h+(\w+))?")  - a branch reset group where groups share the same IDs:

(\w+) - Group 1: one or more word chars

| - or

"(\w+)(?:\h+(\w+))?(?:\h+(\w+))?" -

" - a " char

(\w+) - Group 1: one or more word chars

(?:\h+(\w+))? - an optional occurrence of a sequences:

\h+ - 1 or more horizontal whitespaces

(\w+) - Group 2: one or more word chars

(?:\h+(\w+))?" - ibid, but with Group 3, etc.


问:
org.xml.sax.SAXParseException: Premature end of file
I have this piece of code which gives to SAXParseError i.e., it is not getting the content, but the same thing when i use in my test pg it works correctly. Here i am providing my original code piece, can any1 figure out what is the problem

This is the part where I fetch a xml and append a node to it but it seems that i am not able to get the file itself

```<code>String atemp=readFileAsString("../webapps/abc/include/xml/data.xml")

        log.info("ok thats good")

        String[] splitString=res.split(",")

        log.info(atemp)

        try
        {
            def root = new XmlSlurper().parseText(atemp)
        }
        catch(Exception e)
        {
            log.debug("parse errror: "+e)
        }
        root.appendNode {
          row {
            name(splitString[1])
            host(splitString[2])
            desc(splitString[3])
            product(splitString[4])
            type(splitString[5])
            time(splitString[6])
            by(splitString[7])
          }
        }

        def outputBuilder = new StreamingMarkupBuilder()
        String temp = outputBuilder.bind{ mkp.yield root }

        File file = new File("../webapps/abc/include/xml/data.xml");
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        output.write(temp);
        output.close();
        log.info(temp)
</code>```

my readFileAsString function

```<code>private String readFileAsString(String filePath) {
    try
    {
        StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        log.info(reader==null);
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            log.info(readData)
        }
        reader.close();
        log.info("File Content\n"+fileData.toString());
        return fileData.toString();
    }
    catch (Exception e)
    {
        log.info(e);
    }
}
</code>```

Output

```<code>INFO http-5050-Processor24 com.abc.helper.WriteXml - false
INFO http-5050-Processor24 com.abc.helper.WriteXml - File Content
INFO http-5050-Processor24 com.abc.helper.WriteXml - ok thats good
</code>```

Note: I am able to open the file in my test program with the same path

答:
The readFileAsString method looks OK, but if the log output is to believed then your application is reading an empty file, and that's what is causing the XML parse exception.

The first thing to check is that the pathname of the file you are attempting to read is actually correct, and that the file at that location is not actually empty.  Try adding this line at the beginning of readFileAsString

```<code>log.info("file size is " + new File(filePath).length());
</code>```

Note that zero means either the file does not exist, or it is empty.

Looking at the rest of the code, your application seems to be reading the file, doing something to it and then writing it back to the same place.  Consider the possibility that it is the code that is generating the output that is broken ... and your application is attempting to read and parse a file that it has previously clobbered.

Body:
I have this piece of code which gives to SAXParseError i.e., it is not getting the content, but the same thing when i use in my test pg it works correctly. Here i am providing my original code piece, can any1 figure out what is the problem

This is the part where I fetch a xml and append a node to it but it seems that i am not able to get the file itself

String atemp=readFileAsString("../webapps/abc/include/xml/data.xml")

        log.info("ok thats good")

        String[] splitString=res.split(",")

        log.info(atemp)

        try
        {
            def root = new XmlSlurper().parseText(atemp)
        }
        catch(Exception e)
        {
            log.debug("parse errror: "+e)
        }
        root.appendNode {
          row {
            name(splitString[1])
            host(splitString[2])
            desc(splitString[3])
            product(splitString[4])
            type(splitString[5])
            time(splitString[6])
            by(splitString[7])
          }
        }

        def outputBuilder = new StreamingMarkupBuilder()
        String temp = outputBuilder.bind{ mkp.yield root }

        File file = new File("../webapps/abc/include/xml/data.xml");
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        output.write(temp);
        output.close();
        log.info(temp)

my readFileAsString function

private String readFileAsString(String filePath) {
    try
    {
        StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        log.info(reader==null);
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            log.info(readData)
        }
        reader.close();
        log.info("File Content\n"+fileData.toString());
        return fileData.toString();
    }
    catch (Exception e)
    {
        log.info(e);
    }
}

Output

INFO http-5050-Processor24 com.abc.helper.WriteXml - false
INFO http-5050-Processor24 com.abc.helper.WriteXml - File Content
INFO http-5050-Processor24 com.abc.helper.WriteXml - ok thats good

Note: I am able to open the file in my test program with the same path

Body:
The readFileAsString method looks OK, but if the log output is to believed then your application is reading an empty file, and that's what is causing the XML parse exception.

The first thing to check is that the pathname of the file you are attempting to read is actually correct, and that the file at that location is not actually empty.  Try adding this line at the beginning of readFileAsString

log.info("file size is " + new File(filePath).length());

Note that zero means either the file does not exist, or it is empty.

Looking at the rest of the code, your application seems to be reading the file, doing something to it and then writing it back to the same place.  Consider the possibility that it is the code that is generating the output that is broken ... and your application is attempting to read and parse a file that it has previously clobbered.