问:
Run Spark example on Kubernetes failed

My Mac OS/X Version : 10.15.3

Minikube Version: 1.9.2

I start the minikube use the following command without any extra configuration.

```<code>minikube start --driver=virtualbox
--image-repository='registry.cn-hangzhou.aliyuncs.com/google_containers' --cpus 4 --memory 4096 --alsologtostderr
</code>```

And I download spark-2.4.5-bin-hadoop2.7 from the Spark official website and build spark images by the following command

```<code>eval $(minikube docker-env)
./bin/docker-image-tool.sh -m -t 2.4.5 build
</code>```

then I run Spark-pi using the follwing command within my local machine where store the Spark 2.4.5.

```<code>
kubectl create serviceaccount spark
kubectl create clusterrolebinding spark-role --clusterrole=admin --serviceaccount=default:spark --namespace=default
./bin/spark-submit \
--master k8s://https://192.168.99.104:8443 \
--deploy-mode cluster \
--name spark-pi \
--class org.apache.spark.examples.SparkPi \
--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \
--conf spark.executor.instances=1 \
--conf spark.kubernetes.container.image=spark:2.4.5 \
local:///opt/spark/examples/jars/spark-examples_2.11-2.4.5.jar

</code>```

I get the following error

the full log can be found at full log

Can anyone explain this error and how to solve it?

答:
Another spark image (from gcr.io/spark-operator/spark) worked for me, without downgrading the version of Kubernetes.

```<code>bin/spark-submit \
--master k8s://https://192.168.99.100:8443 \
--deploy-mode cluster \
--name spark-pi \
--class org.apache.spark.examples.SparkPi \
--conf spark.driver.cores=1 \
--conf spark.driver.memory=512m \
--conf spark.executor.instances=2 \
--conf spark.executor.memory=512m \
--conf spark.executor.cores=1 \
--conf spark.kubernetes.container.image=gcr.io/spark-operator/spark:v2.4.5 \
--conf spark.kubernetes.container.image.pullPolicy=IfNotPresent \
--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \
local:///opt/spark/examples/jars/spark-examples_2.11-2.4.5.jar
</code>```

Title: Run Spark example on Kubernetes failed

Body:
My Mac OS/X Version : 10.15.3

Minikube Version: 1.9.2

I start the minikube use the following command without any extra configuration.

minikube start --driver=virtualbox
--image-repository='registry.cn-hangzhou.aliyuncs.com/google_containers' --cpus 4 --memory 4096 --alsologtostderr

And I download spark-2.4.5-bin-hadoop2.7 from the Spark official website and build spark images by the following command

eval $(minikube docker-env)
./bin/docker-image-tool.sh -m -t 2.4.5 build

then I run Spark-pi using the follwing command within my local machine where store the Spark 2.4.5.

kubectl create serviceaccount spark
kubectl create clusterrolebinding spark-role --clusterrole=admin --serviceaccount=default:spark --namespace=default
./bin/spark-submit \
--master k8s://https://192.168.99.104:8443 \
--deploy-mode cluster \
--name spark-pi \
--class org.apache.spark.examples.SparkPi \
--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \
--conf spark.executor.instances=1 \
--conf spark.kubernetes.container.image=spark:2.4.5 \
local:///opt/spark/examples/jars/spark-examples_2.11-2.4.5.jar

I get the following error

the full log can be found at full log

Can anyone explain this error and how to solve it?

Body:
Another spark image (from gcr.io/spark-operator/spark) worked for me, without downgrading the version of Kubernetes.

bin/spark-submit \
--master k8s://https://192.168.99.100:8443 \
--deploy-mode cluster \
--name spark-pi \
--class org.apache.spark.examples.SparkPi \
--conf spark.driver.cores=1 \
--conf spark.driver.memory=512m \
--conf spark.executor.instances=2 \
--conf spark.executor.memory=512m \
--conf spark.executor.cores=1 \
--conf spark.kubernetes.container.image=gcr.io/spark-operator/spark:v2.4.5 \
--conf spark.kubernetes.container.image.pullPolicy=IfNotPresent \
--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \
local:///opt/spark/examples/jars/spark-examples_2.11-2.4.5.jar


来源: stackexchange

问:
Vue Vuetify.Wrong index is passed to v-dialog when using v-for
So using v-for and v-dialog, my template looking like this:

```<code>  <v-list >
   <v-list-item v-for="(pool,indexp) in items[0].pools" :key="pool.name">
     <v-dialog :retain-focus="false" v-model="dialog" scrollable max-width="300px">
      <template v-slot:activator="{ on }">
       <v-btn color="primary" dark v-on="on">{{pool.name}}</v-btn>
        </template>
                <v-card><v-card-title>{{pool.name}}</v-card-title></v-card>
     </v-dialog>
    </v-list-item>
  </v-list>
</code>```

So say the object I'm looping through has 2 elements, this generates 2 buttons that will activate the v-dialog. My problem is that when I click the first "pool" button, the name of the second pool is shown in the dialog. WHy?

I have this in codepen:

https://codepen.io/averied/pen/QWjXxop?editable=true&editors=101%3Dhttps%3A%2F%2Fvuetifyjs.com%2Fen%2Fcomponents%2Fdialogs%2F

答:
If you’re using the same boolean variable, dialog, for everything in the v-for as it appears to me, then activating one will activate them all. Later ones will be rendered over top of earlier ones. So in a two item list you’ll always see the second item.

You probably don’t need the v-model on the v-dialog at all; I’m fairly certain the v-dialogs can maintain their internal state just fine. Unless you’re programmatically triggering the dialogs through something other than your button in the activator slot, or if you need to display or save the state for some reason. If so, you’ll need to maintain a list of booleans, one for each pool. Could potentially be an attribute on the pool object.

ContentLicense: CC BY-SA 4.0

Body:
So using v-for and v-dialog, my template looking like this:

  <v-list >
   <v-list-item v-for="(pool,indexp) in items[0].pools" :key="pool.name">
     <v-dialog :retain-focus="false" v-model="dialog" scrollable max-width="300px">
      <template v-slot:activator="{ on }">
       <v-btn color="primary" dark v-on="on">{{pool.name}}</v-btn>
        </template>
                <v-card><v-card-title>{{pool.name}}</v-card-title></v-card>
     </v-dialog>
    </v-list-item>
  </v-list>

So say the object I'm looping through has 2 elements, this generates 2 buttons that will activate the v-dialog. My problem is that when I click the first "pool" button, the name of the second pool is shown in the dialog. WHy?

I have this in codepen:

https://codepen.io/averied/pen/QWjXxop?editable=true&editors=101%3Dhttps%3A%2F%2Fvuetifyjs.com%2Fen%2Fcomponents%2Fdialogs%2F


问:
Displaying nested divs on the same line
I am working with a react component that produces nested divs. I'd like to style force the divs to be on the same line but can only declare styles on the outer container div. Is there a way to achieve this without styling the inner divs? If only I can pass style to the "hello" div.

Currently:

hello

secondLine thirdLine

Desired:

hello secondLine thirdLine

```<code><div style={{ textAlign: "left", whiteSpace: "nowrap" }}>
        <div style={{ display: "inline" }}>
            <div>hello</div>
        </div>
        {` `}
        <div style={{ display: "inline" }}> secondDiv </div>
        <div style={{ display: "inline" }}> thirdDiv </div>
    </div>
</code>```

答:
make the outer div display: 'flex'

```<code><div style={{ textAlign: "left", whiteSpace: "nowrap",display:"flex" }}>
    <div style={{ display: "inline" }}>
        <div>hello</div>
    </div>
    { }
    <div style={{ display: "inline" }}> secondDiv </div>
    <div style={{ display: "inline" }}> thirdDiv </div>
</div>
</code>```

For more reference :details

Title: Displaying nested divs on the same line

Body:
I am working with a react component that produces nested divs. I'd like to style force the divs to be on the same line but can only declare styles on the outer container div. Is there a way to achieve this without styling the inner divs? If only I can pass style to the "hello" div.

Currently:

hello

secondLine thirdLine

Desired:

hello secondLine thirdLine

hello

        {` `}

 secondDiv

 thirdDiv

Body:
make the outer div display: 'flex'

<div style={{ textAlign: "left", whiteSpace: "nowrap",display:"flex" }}>
    <div style={{ display: "inline" }}>
        <div>hello</div>
    </div>
    { }
    <div style={{ display: "inline" }}> secondDiv </div>
    <div style={{ display: "inline" }}> thirdDiv </div>
</div>

For more reference :details


问:
Javascript fetch getting undefined URL on window.popstate
I'm trying to fetch content from a php page. I have a fetch call + a history.pushState firing on click, which are both working fine, but window.popstate is returning an error when going back by pressing the browser's back button. The error is, that window.popstate doesn't know what url to fetch when going back.

Unfortunately I can't figure out how to pass the right url variable to window.popstate.

```<code>        // the code stripped fetch function
        var load = function(url){
            fetch(url, {
                method: "GET"
            }).then(function(response) {
                    response.text().then(function(text) {

                        // parsing and temporary placing fetched content into a fragment
                        var content = new DOMParser().parseFromString(text, "text/html"),
                        bodyPart = content.querySelector('main'),
                        fragmentElement = document.createDocumentFragment(),
                        tempElement = fragmentElement.appendChild(bodyPart);

                        // replacing the current content with the fragment
                        document.body.replaceChild(tempElement, document.querySelector('main'));

                        // need to assign the fetch on click function again, otherwise it won't work on the dynamically added (the fetched) links
                        clickOnPJAXLink();

                    });
                });
            }

            // the click function if clicking on any link function to start fetching content
            var clickOnPJAXLink = function(url) {
                document.querySelectorAll('A').forEach(a => {
                    a.addEventListener('click', (e) => {
                        e.preventDefault();
                        var url = e.currentTarget.getAttribute("href");
                        load(url);
                        history.pushState(url, "sometitle", url);
                    });
                });
            }

            // load the function initially on the home page
            clickOnPJAXLink();

            // popstate for back button
            window.addEventListener('popstate', function (e) {
                var state = e.state;
                if (state !== null) {
                    load(url);
                    console.log(url)
                }
            });
</code>```

The window.popstate returns the error, that var url is undefined and thus of course cannot fetch the before (the history back) content.

Many thanks for any tips!

答: history.pushState takes a data object as the first parameter, not a string- try history.pushState({url:e.currentTarget.getAttribute("href")}  then e.state.url will equal the url you want to load.</p>

Body:
I'm trying to fetch content from a php page. I have a fetch call + a history.pushState firing on click, which are both working fine, but window.popstate is returning an error when going back by pressing the browser's back button. The error is, that window.popstate doesn't know what url to fetch when going back.

Unfortunately I can't figure out how to pass the right url variable to window.popstate.

        // the code stripped fetch function
        var load = function(url){
            fetch(url, {
                method: "GET"
            }).then(function(response) {
                    response.text().then(function(text) {

                        // parsing and temporary placing fetched content into a fragment
                        var content = new DOMParser().parseFromString(text, "text/html"),
                        bodyPart = content.querySelector('main'),
                        fragmentElement = document.createDocumentFragment(),
                        tempElement = fragmentElement.appendChild(bodyPart);

                        // replacing the current content with the fragment
                        document.body.replaceChild(tempElement, document.querySelector('main'));

                        // need to assign the fetch on click function again, otherwise it won't work on the dynamically added (the fetched) links
                        clickOnPJAXLink();

                    });
                });
            }

            // the click function if clicking on any link function to start fetching content
            var clickOnPJAXLink = function(url) {
                document.querySelectorAll('A').forEach(a => {
                    a.addEventListener('click', (e) => {
                        e.preventDefault();
                        var url = e.currentTarget.getAttribute("href");
                        load(url);
                        history.pushState(url, "sometitle", url);
                    });
                });
            }

            // load the function initially on the home page
            clickOnPJAXLink();

            // popstate for back button
            window.addEventListener('popstate', function (e) {
                var state = e.state;
                if (state !== null) {
                    load(url);
                    console.log(url)
                }
            });

The window.popstate returns the error, that var url is undefined and thus of course cannot fetch the before (the history back) content.

Many thanks for any tips!


问:
Map within Map? Working with columns within two lists of dataframes
I'm working in R and have two lists of dataframes. I need to add a column to the dataframes within list1, filled with values taken from corresponding dataframes within list2. I think I need Map within Map, or lapply within Map, but I have only ever used Map and lapply on their own, or a lapply within a lapply so I am having trouble getting the correct code sorted. The below lists are similar to what I am working with.

```<code>dfa<-data.frame(tom=sample(seq(as.Date("2020-01-01"),as.Date("2020-03-01"), 1), 20), id=seq(1:20))
dfb<-data.frame(tom=sample(seq(as.Date("2020-01-01"),as.Date("2020-02-01"), 1), 32), id=seq(1:32))
list1<-list(dfa, dfb)

df1<-data.frame(date=seq(as.Date("2020-01-01"), as.Date("2020-03-01"), 1),num=sample(1:200, 61))
df2<-data.frame(date=seq(as.Date("2020-01-01"), as.Date("2020-03-01"), 1),num=sample(4:200, 61))
list2<-list(df1, df2)
</code>```

The code that I have tried might be close or totally off mark. I am trying to add the new column "d1" to all dataframes in list1. The values in d1 should be pulled from variable "num" in the dataframes of list2, where the dates match to the dates from dataframes in list1.

```<code>list3<-Map(function(x, y){
           Map(function(v, w){
               v<-cbind(v, d1=w[w$date==v, w$num])}, x$tom, y)},list1, list2)
</code>```

This just returns an error regarding use of atomic vectors: "Error in w$date : $ operator is invalid for atomic vectors"

But if I change it to indexing...

```<code>list3<-Map(function(x, y){
       Map(function(v, w){
           v<-cbind(v, d1=w[w[,1]==v, w[,2]])}, x$tom, y)}, list1, list2)
</code>```

It is not happy either: "Error in [.default(w, , 1) : incorrect number of dimensions"

By this point I've sort of lost track of what I'm trying to refer to in the innermost function and how to refer to it properly. Is this even getting close to what I want?

答:
We could use merge

```<code>Map(function(dat1,  dat2)  merge(dat1, dat2, by.x = 'tom',
        by.y = 'date', all.x = TRUE), list1, list2)
</code>```

If we need to rename the column

```<code>Map(function(dat1,  dat2)  {
    out <- merge(dat1, dat2, by.x = 'tom', by.y = 'date', all.x = TRUE)
    names(out)[3] <- 'd1'
    out},
       list1, list2)
</code>```

Body:
I'm working in R and have two lists of dataframes. I need to add a column to the dataframes within list1, filled with values taken from corresponding dataframes within list2. I think I need Map within Map, or lapply within Map, but I have only ever used Map and lapply on their own, or a lapply within a lapply so I am having trouble getting the correct code sorted. The below lists are similar to what I am working with.

dfa<-data.frame(tom=sample(seq(as.Date("2020-01-01"),as.Date("2020-03-01"), 1), 20), id=seq(1:20))
dfb<-data.frame(tom=sample(seq(as.Date("2020-01-01"),as.Date("2020-02-01"), 1), 32), id=seq(1:32))
list1<-list(dfa, dfb)

df1<-data.frame(date=seq(as.Date("2020-01-01"), as.Date("2020-03-01"), 1),num=sample(1:200, 61))
df2<-data.frame(date=seq(as.Date("2020-01-01"), as.Date("2020-03-01"), 1),num=sample(4:200, 61))
list2<-list(df1, df2)

The code that I have tried might be close or totally off mark. I am trying to add the new column "d1" to all dataframes in list1. The values in d1 should be pulled from variable "num" in the dataframes of list2, where the dates match to the dates from dataframes in list1.

list3<-Map(function(x, y){
           Map(function(v, w){
               v<-cbind(v, d1=w[w$date==v, w$num])}, x$tom, y)},list1, list2)

This just returns an error regarding use of atomic vectors: "Error in w$date : $ operator is invalid for atomic vectors"

But if I change it to indexing...

list3<-Map(function(x, y){
       Map(function(v, w){
           v<-cbind(v, d1=w[w[,1]==v, w[,2]])}, x$tom, y)}, list1, list2)

It is not happy either: "Error in [.default(w, , 1) : incorrect number of dimensions"

By this point I've sort of lost track of what I'm trying to refer to in the innermost function and how to refer to it properly. Is this even getting close to what I want?

Body:
We could use merge

Map(function(dat1,  dat2)  merge(dat1, dat2, by.x = 'tom',
        by.y = 'date', all.x = TRUE), list1, list2)

If we need to rename the column

Map(function(dat1,  dat2)  {
    out <- merge(dat1, dat2, by.x = 'tom', by.y = 'date', all.x = TRUE)
    names(out)[3] <- 'd1'
    out},
       list1, list2)


问:
How to print a string representation of myFirstCar using the _str_method?
I'm doing this question in a python book and I just stumbled across this question. As shown in the title I wrote above, it's asking me to use that variable with the _str_method and also, I should get the output:
Make = Honda, Model = Civic, Color = White, Price = 1500
How should I write the code? (Please help)

答:
To add some context to what has been said by others: the __str__ method on a class is used auto-magically when asking for the string representation of an object (either implicitly, or explicitly via str(myObject)). This method determines what gets produced as the string representation. So you'll want a class (myFirstCar), and you'll want to give it a __str__ method that outputs what you want (Make = Honda, Model = Civic, Color = White, Price = 1500). Here's some code that achieves that:

```<code>class myFirstCar:
    def __init__(self, make, model, color, price):
        self.make = make
        self.model = model
        self.color = color
        self.price = price

    def __str__(self):
        return f'Make = {self.make}, Model = {self.model}, Color = {self.color}, Price = {self.price}'

>> print(str(myFirstCar('Honda', 'Civic', 'White', '1500')))
Make = Honda, Model = Civic, Color = White, Price = 1500
</code>```

Happy Coding!

Body:
To add some context to what has been said by others: the __str__ method on a class is used auto-magically when asking for the string representation of an object (either implicitly, or explicitly via str(myObject)). This method determines what gets produced as the string representation. So you'll want a class (myFirstCar), and you'll want to give it a __str__ method that outputs what you want (Make = Honda, Model = Civic, Color = White, Price = 1500). Here's some code that achieves that:

class myFirstCar:
    def __init__(self, make, model, color, price):
        self.make = make
        self.model = model
        self.color = color
        self.price = price

    def __str__(self):
        return f'Make = {self.make}, Model = {self.model}, Color = {self.color}, Price = {self.price}'

>> print(str(myFirstCar('Honda', 'Civic', 'White', '1500')))
Make = Honda, Model = Civic, Color = White, Price = 1500

Happy Coding!


问:
How can I pass a 2 decimal place float from flask-python to html?
Could you help me, please?

How can I pass a 2 decimal place float from flask-python to html?

I typed the following code in the application.py:

```<code>average = db.execute("SELECT AVG(score) FROM comments WHERE book_id = :book_id", {"book_id": book_id}).fetchall()
return render_template("comments.html", book=book, statements=statements, average=average)
</code>```

And I typed in the html file:    .... jinjer

```<code>{{ average }}
</code>```

I was expecting a value = 3, but the outcome was:

```<code>[(Decimal('3.0000000000000000'),)]
</code>```

How can I fix it?

The value is ok, but the format is not.

答:
You can use the round function for precision in python. for example,

```<code>average = 2.34242433
average = round(average,2)
print(average)
</code>```

Output: 2.34

So in your application.py file, return as

average=round(average,2)

Body:
Could you help me, please?

How can I pass a 2 decimal place float from flask-python to html?

I typed the following code in the application.py:

average = db.execute("SELECT AVG(score) FROM comments WHERE book_id = :book_id", {"book_id": book_id}).fetchall()
return render_template("comments.html", book=book, statements=statements, average=average)

And I typed in the html file:    .... jinjer

{{ average }}

I was expecting a value = 3, but the outcome was:

[(Decimal('3.0000000000000000'),)]

How can I fix it?

The value is ok, but the format is not.

Body:
You can use the round function for precision in python. for example,

average = 2.34242433
average = round(average,2)
print(average)

Output: 2.34

So in your application.py file, return as

average=round(average,2)


问:
How to include 2 different Variables as Property and Value for a third Variable in Javascript or jQuery
```<code>var A = $(this).attr("id") //result is a string

var B = $(this).attr("id") //result is another string from a different id

var C = {
 A: B      //I want to use A as Property and B as Value
};
</code>```

when console.log(C) is made, JS console says that A is undefined. Why is this so?
//How can I use A as Property and B as Value as Object inside variable C then for Javascript and jQuery? //Thanks.

答:
If I understood you correctly you want to achieve something like this:

```<code>var a = 'something';
var b = 'else';

// example var c = { something: "else" };
</code>```

if so, then it's super easy without advanced es6 experimental feats ;)

just (I'm using es6 template literals - but you can do with normal string concat):

```<code> var c = JSON.parse(`{"${a}":"${b}"}`);
</code>```

Body:
var A = $(this).attr("id") //result is a string

var B = $(this).attr("id") //result is another string from a different id

var C = {
 A: B      //I want to use A as Property and B as Value
};

when console.log(C) is made, JS console says that A is undefined. Why is this so?
//How can I use A as Property and B as Value as Object inside variable C then for Javascript and jQuery? //Thanks.

Body:
If I understood you correctly you want to achieve something like this:

var a = 'something';
var b = 'else';

// example var c = { something: "else" };

if so, then it's super easy without advanced es6 experimental feats ;)

just (I'm using es6 template literals - but you can do with normal string concat):

 var c = JSON.parse(`{"${a}":"${b}"}`);


问:
Redis expiration replication to slaves
I am interested in using Redis to store a customer's session on the server side for authorization.  Basically, when a customer logs in a hash will be stored in a Redis cluster and the key returned to the client.  On each request, the client will pass the key as a header and the service will check that the hash still exists in Redis, if it doesn't then an error message will be returned.  This key will expire after X minutes resulting in any requests using that key to fail.  However, I have been reading online that some people experienced issues because of the way the expiration is replicated to slaves.  Slaves only expire a key when they receive a del command from the master so if a "get" is made on a slave before this command, the value at that key will be returned.

https://github.com/antirez/redis/issues/187

Does this issue still exist?  It seems like a big issue to me and would create a bit of a security hole.  Maybe not a big deal for stale data but when using for authorization it is a big deal

答:
A) no, not really — since 2014, a GET of an expired key will return "not found" on a slave even if the slave hasn't yet received a DEL from the replication stream. The outstanding issue has to do with EXISTS being inconsistent with GET, which only matters if you rely on the output of the EXISTS command.

B) Completely independent of this issue, the possibility of replication lag always exists. The security of your app shouldn't depend on the premise that replicas are always up-to-date.

Title: Redis expiration replication to slaves


问:
Error during SELECT sql query between Azure SQL DBs
I have .NET Core app with EF Core.

I use Azure SQL DBs.

I have one main DB "Catalog" and multiple others.

I'm trying to populate one table in multiple DBs but value I need to get from main DB "Catalog".

I did the following migration:

```<code>migrationBuilder.Sql("INSERT INTO [dbo].[Table2] "
                     + "(Name, Description)"
                     + " VALUES "
                     + "((SELECT param1 FROM [Catalog].[dbo].[Table1] WHERE DB_NAME() = CONCAT(param1, '-', param2)), 'some description')");
</code>```

But in result I see:

Reference to database and/or server name in 'Catalog.dbo.Table1'
  is not supported in this version of SQL Server.

So I can't execute SELECT queries between Azure DBs? Or my sql is wrong? How can I resolve this issue?

答:
If you want to query remote database, you can use the Azure SQL Database elastic query.

For example

create a certificate for the remote database

```<code> CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<master_key_password>';
 CREATE DATABASE SCOPED CREDENTIAL RemoteDBCred
 WITH IDENTITY = '<username>',
 SECRET = '<password>';
</code>```

Create an external data source fro the remote database

```<code>CREATE EXTERNAL DATA SOURCE MyRemoteDBSource WITH
    (TYPE = RDBMS,
    LOCATION = '<server_name>.database.windows.net',
    DATABASE_NAME = '<>',
    CREDENTIAL = RemoteDBCred,
) ;
</code>```

Create an external table with the data source

```<code>CREATE EXTERNAL TABLE [dbo].[<>]
(

)
WITH
( DATA_SOURCE = MyRemoteDBSource)
</code>```

Query the table

For more details, please refer to the document and the blog

Body:
I have .NET Core app with EF Core.

I use Azure SQL DBs.

I have one main DB "Catalog" and multiple others.

I'm trying to populate one table in multiple DBs but value I need to get from main DB "Catalog".

I did the following migration:

migrationBuilder.Sql("INSERT INTO [dbo].[Table2] "
                     + "(Name, Description)"
                     + " VALUES "
                     + "((SELECT param1 FROM [Catalog].[dbo].[Table1] WHERE DB_NAME() = CONCAT(param1, '-', param2)), 'some description')");

But in result I see:

Reference to database and/or server name in 'Catalog.dbo.Table1'
  is not supported in this version of SQL Server.

So I can't execute SELECT queries between Azure DBs? Or my sql is wrong? How can I resolve this issue?

Body:
If you want to query remote database, you can use the Azure SQL Database elastic query.

For example

create a certificate for the remote database

 CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<master_key_password>';
 CREATE DATABASE SCOPED CREDENTIAL RemoteDBCred
 WITH IDENTITY = '<username>',
 SECRET = '<password>';

Create an external data source fro the remote database

CREATE EXTERNAL DATA SOURCE MyRemoteDBSource WITH
    (TYPE = RDBMS,
    LOCATION = '<server_name>.database.windows.net',
    DATABASE_NAME = '<>',
    CREDENTIAL = RemoteDBCred,
) ;

Create an external table with the data source

CREATE EXTERNAL TABLE [dbo].[<>]
(

)
WITH
( DATA_SOURCE = MyRemoteDBSource)

Query the table

For more details, please refer to the document and the blog


问:
How do I update my prod database with dotnet ef database cli command?
How do I get EF to build all the tables for the prod db?

So far I've been building and pushing all my .Net Core database migrations to the dev db

ex.

>dotnet ef migrations add InitialModsN -c Auto2Context

>dotnet ef database update -c Auto2Context

In my Appsettings.Development.json file I have my con string pointing to dev db 'source=DEV'

```<code>"ConnectionStrings": {
"DefaultConnection": "Data Source=Auto2.db",
"Auto2": "data source=DEV; initial catalog=Auto2; user id=auto2; password=12345;" }
</code>```

And my Appsettings.json I have the prod db con string pointing to the prod db 'source=LIVE'

```<code>"ConnectionStrings": {
"DefaultConnection": "Data Source=Auto2.db",
"Auto2": "data source=LIVE; initial catalog=Auto2; user id=auto2; password=12345;" }
</code>```

So far everything is being built and migrated to dev, how do I change this to build all the changes up to date in the prod db?

Do I have to re create an initial migration file and then update?
If yes, how do I point it to the prod db?
I tried a couple of different commands with no luck.
Here is what I tried.

>dotnet ef database update -c Auto2Context --connection "data source=LIVE; initial catalog=Auto2; user id=auto2; password=12345"

-received 'Unrecognized option '--connection''

>dotnet ef database update -c Auto2Context --configuration Release

no tables created in the prod db

答:
Here is what I used and it seems to work.

dotnet publish --configuration Release /p:EnvironmentName=Production

but this only builds the application.
I had to run this command below to create a sql script to update the prod db.

dotnet ef migrations script -i -o "buildscript.sql" -c Auto2Context

Is this the best/correct way to push db changes to prod?

Body:
How do I get EF to build all the tables for the prod db?

So far I've been building and pushing all my .Net Core database migrations to the dev db

ex.

>dotnet ef migrations add InitialModsN -c Auto2Context

>dotnet ef database update -c Auto2Context

In my Appsettings.Development.json file I have my con string pointing to dev db 'source=DEV'

"ConnectionStrings": {
"DefaultConnection": "Data Source=Auto2.db",
"Auto2": "data source=DEV; initial catalog=Auto2; user id=auto2; password=12345;" }

And my Appsettings.json I have the prod db con string pointing to the prod db 'source=LIVE'

"ConnectionStrings": {
"DefaultConnection": "Data Source=Auto2.db",
"Auto2": "data source=LIVE; initial catalog=Auto2; user id=auto2; password=12345;" }

So far everything is being built and migrated to dev, how do I change this to build all the changes up to date in the prod db?

Do I have to re create an initial migration file and then update?
If yes, how do I point it to the prod db?
I tried a couple of different commands with no luck.
Here is what I tried.

>dotnet ef database update -c Auto2Context --connection "data source=LIVE; initial catalog=Auto2; user id=auto2; password=12345"

-received 'Unrecognized option '--connection''

>dotnet ef database update -c Auto2Context --configuration Release

no tables created in the prod db


问:
create java PrivateKey and PublicKey from a String of file
Good day,

There is another third party that need my web application to send them some data in encrypt format. Thus they send me some guide to do so, however, I am not familiar with it, I am trying to google around but looks like I am google wrong way.

The guide is something as follow:

Run openssl command to generate a privatekey:

openssl ecparam -name prime256v1 -genkey -out myprivate.pem

After run this command, I output a priv.pem file, and I saw inside got some key end with '==', which is as follow:

```<code>-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEILefWfeuZOgnbDlxpwo3uQ2xQXfhXHUPTS+vKzvVZdCToAoGCCqGSM49
AwEHoUQDQgAE4MeQspGRJ1qdpweBfiaT5P84alZdga1f7mSpa5HqXTH58u0ZWJUQ
J7ToU/bUOPITh4FX07AV6wrgFCmwtUenDQ==
-----END EC PRIVATE KEY-----
</code>```

Second one is run openssl command to generate the public key, and then send them:

openssl ec -in myprivate.pem -pubout -out mypublic.pem

Convert the private key to pkcs8 format:

openssl pkcs8 -topk8 -nocrypt -in myprivate.pem -out mypkcs8.pem

The third party will give me a public key in string format, then ask me to generate a secret key, and provide me some java code as follow:

first is to generate secret key and second one is encrypt:

```<code>public static SecretKey generateSharedSecret(PrivateKey privateKey,
            PublicKey publicKey) {
        try {
            KeyAgreement keyAgreement = KeyAgreement.getInstance( "ECDH" );
            keyAgreement.init( privateKey );
            keyAgreement.doPhase( publicKey, true );
            SecretKeySpec key = new SecretKeySpec(
                    keyAgreement.generateSecret( ), "AES" );
            return key;
        } catch ( Exception e ) {
            // TODO Auto-generated catch block
            e.printStackTrace( );
            return null;
        }
    }

public static String encryptString(SecretKey key, String plainText) {
        try {
            String myIv = "Testing @ IV!";
            byte[] iv = myIv.getBytes( "UTF-8" );
            IvParameterSpec ivSpec = new IvParameterSpec( iv );
            Cipher cipher = Cipher.getInstance( "AES / CBC / PKCS5Padding" );
            byte[] plainTextBytes = plainText.getBytes( "UTF-8" );
            byte[] cipherText;
            cipher.init( Cipher.ENCRYPT_MODE, key, ivSpec );
            cipherText = new byte[cipher.getOutputSize( plainTextBytes.length )];
            int encryptLength = cipher.update( plainTextBytes, 0,
                    plainTextBytes.length, cipherText, 0 );
            encryptLength += cipher.doFinal( cipherText, encryptLength );
            return bytesToHex( cipherText );
        } catch ( Exception e ) {
            e.printStackTrace( );
            return null;
        }
    }
</code>```

and also the bytes to hex string method:

```<code>public static String bytesToHex(byte[] byteArray) {
    StringBuffer hexStringBuffer = new StringBuffer( );
    for ( int i = 0; i < byteArray.length; i++ ) {
        hexStringBuffer.append( String.format( "%02X", byteArray[ i ] ) );
    }
    return hexStringBuffer.toString( );
}
</code>```

I have self gen a private key and also a public key by using openssl command, but the 4th step telling me that they will give me a public key as well, thus I am not understand, which public key should I use.

And also, how can I convert a String into java PrivateKey and PublicKey object?

* add on *
I try to convert the der file to java PublicKey object, it looks work. Before this, I convert the pem to der using openssl command:

```<code>openssl pkey -pubin -in ecpubkey.pem -outform der -out ecpubkey.der
</code>```

Here is the java code:

```<code>        File f = new File("/home/my/Desktop/key/ecpubkey.der");
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int) f.length()];
        dis.readFully(keyBytes);
        dis.close();

        KeyFactory fact = KeyFactory.getInstance("EC");
        PublicKey theirpub = fact.generatePublic(new X509EncodedKeySpec(keyBytes));
</code>```

However, I am hitting java.security.spec.InvalidKeySpecException: java.io.IOException: insufficient data when I try to convert der file to java PrivateKey object, the following is what I did:

```<code>openssl ecparam -name prime256v1 -genkey -out priv.pem
openssl pkcs8 -topk8 -nocrypt -in priv.pem -outform der -out priv.der
</code>```

And the following is my java code:

```<code>        File f2 = new File("/home/my/Desktop/key/priv.der");
        FileInputStream fis2 = new FileInputStream(f2);
        DataInputStream dis2 = new DataInputStream(fis2);
        byte[] keyBytes2 = new byte[(int) f.length()];
        dis2.readFully(keyBytes2);
        dis2.close();

        KeyFactory fact2 = KeyFactory.getInstance("EC");
        PrivateKey pKey = fact2.generatePrivate( new PKCS8EncodedKeySpec(keyBytes2) ); // this line hit insufficient data
</code>```

答:
Base on dave_thompson_085 explanation and code, I manage to create my java PublicKey and Privatekey with following:

```<code>public static PublicKey getPublicKey(String filename) throws IOException, GeneralSecurityException {
    String publicKeyPEM = getKey(filename);
    return getPublicKeyFromString(publicKeyPEM);
}

private static String getKey(String filename) throws IOException {
    // Read key from file
    String strKeyPEM = "";
    BufferedReader br = new BufferedReader(new FileReader(filename));
    String line;
    while ((line = br.readLine()) != null) {
        strKeyPEM += line + "\n";
    }
    br.close();
    return strKeyPEM;
}

public static PublicKey getPublicKeyFromString(String key) throws IOException, GeneralSecurityException {
    String publicKeyPEM = key;
    publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
    publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
    BASE64Decoder b = new BASE64Decoder();
    byte[] encoded = b.decodeBuffer(publicKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("EC");
    PublicKey pubKey = (PublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
    return pubKey;
}
</code>```

and this is for private key

```<code>public static PrivateKey getPrivateKey(String filename) throws IOException, GeneralSecurityException {
    String privateKeyPEM = getKey(filename);
    return getPrivateKeyFromString(privateKeyPEM);
}

public static PrivateKey getPrivateKeyFromString(String key) throws IOException, GeneralSecurityException {
    String privateKeyPEM = key;
    privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
    privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");

    BASE64Decoder b = new BASE64Decoder();
    byte[] encoded = b.decodeBuffer(privateKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("EC");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
    PrivateKey privKey = (PrivateKey) kf.generatePrivate(keySpec);
    return privKey;
}
</code>```

Many thanks to @dave_thompson_085 explanation.

Body:
Good day,

There is another third party that need my web application to send them some data in encrypt format. Thus they send me some guide to do so, however, I am not familiar with it, I am trying to google around but looks like I am google wrong way.

The guide is something as follow:

Run openssl command to generate a privatekey:

openssl ecparam -name prime256v1 -genkey -out myprivate.pem

After run this command, I output a priv.pem file, and I saw inside got some key end with '==', which is as follow:

-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEILefWfeuZOgnbDlxpwo3uQ2xQXfhXHUPTS+vKzvVZdCToAoGCCqGSM49
AwEHoUQDQgAE4MeQspGRJ1qdpweBfiaT5P84alZdga1f7mSpa5HqXTH58u0ZWJUQ
J7ToU/bUOPITh4FX07AV6wrgFCmwtUenDQ==
-----END EC PRIVATE KEY-----

Second one is run openssl command to generate the public key, and then send them:

openssl ec -in myprivate.pem -pubout -out mypublic.pem

Convert the private key to pkcs8 format:

openssl pkcs8 -topk8 -nocrypt -in myprivate.pem -out mypkcs8.pem

The third party will give me a public key in string format, then ask me to generate a secret key, and provide me some java code as follow:

first is to generate secret key and second one is encrypt:

public static SecretKey generateSharedSecret(PrivateKey privateKey,
            PublicKey publicKey) {
        try {
            KeyAgreement keyAgreement = KeyAgreement.getInstance( "ECDH" );
            keyAgreement.init( privateKey );
            keyAgreement.doPhase( publicKey, true );
            SecretKeySpec key = new SecretKeySpec(
                    keyAgreement.generateSecret( ), "AES" );
            return key;
        } catch ( Exception e ) {
            // TODO Auto-generated catch block
            e.printStackTrace( );
            return null;
        }
    }

public static String encryptString(SecretKey key, String plainText) {
        try {
            String myIv = "Testing @ IV!";
            byte[] iv = myIv.getBytes( "UTF-8" );
            IvParameterSpec ivSpec = new IvParameterSpec( iv );
            Cipher cipher = Cipher.getInstance( "AES / CBC / PKCS5Padding" );
            byte[] plainTextBytes = plainText.getBytes( "UTF-8" );
            byte[] cipherText;
            cipher.init( Cipher.ENCRYPT_MODE, key, ivSpec );
            cipherText = new byte[cipher.getOutputSize( plainTextBytes.length )];
            int encryptLength = cipher.update( plainTextBytes, 0,
                    plainTextBytes.length, cipherText, 0 );
            encryptLength += cipher.doFinal( cipherText, encryptLength );
            return bytesToHex( cipherText );
        } catch ( Exception e ) {
            e.printStackTrace( );
            return null;
        }
    }

and also the bytes to hex string method:

public static String bytesToHex(byte[] byteArray) {
    StringBuffer hexStringBuffer = new StringBuffer( );
    for ( int i = 0; i < byteArray.length; i++ ) {
        hexStringBuffer.append( String.format( "%02X", byteArray[ i ] ) );
    }
    return hexStringBuffer.toString( );
}

I have self gen a private key and also a public key by using openssl command, but the 4th step telling me that they will give me a public key as well, thus I am not understand, which public key should I use.

And also, how can I convert a String into java PrivateKey and PublicKey object?

* add on *
I try to convert the der file to java PublicKey object, it looks work. Before this, I convert the pem to der using openssl command:

openssl pkey -pubin -in ecpubkey.pem -outform der -out ecpubkey.der

Here is the java code:

        File f = new File("/home/my/Desktop/key/ecpubkey.der");
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int) f.length()];
        dis.readFully(keyBytes);
        dis.close();

        KeyFactory fact = KeyFactory.getInstance("EC");
        PublicKey theirpub = fact.generatePublic(new X509EncodedKeySpec(keyBytes));

However, I am hitting java.security.spec.InvalidKeySpecException: java.io.IOException: insufficient data when I try to convert der file to java PrivateKey object, the following is what I did:

openssl ecparam -name prime256v1 -genkey -out priv.pem
openssl pkcs8 -topk8 -nocrypt -in priv.pem -outform der -out priv.der

And the following is my java code:

        File f2 = new File("/home/my/Desktop/key/priv.der");
        FileInputStream fis2 = new FileInputStream(f2);
        DataInputStream dis2 = new DataInputStream(fis2);
        byte[] keyBytes2 = new byte[(int) f.length()];
        dis2.readFully(keyBytes2);
        dis2.close();

        KeyFactory fact2 = KeyFactory.getInstance("EC");
        PrivateKey pKey = fact2.generatePrivate( new PKCS8EncodedKeySpec(keyBytes2) ); // this line hit insufficient data

Body:
Base on dave_thompson_085 explanation and code, I manage to create my java PublicKey and Privatekey with following:

public static PublicKey getPublicKey(String filename) throws IOException, GeneralSecurityException {
    String publicKeyPEM = getKey(filename);
    return getPublicKeyFromString(publicKeyPEM);
}

private static String getKey(String filename) throws IOException {
    // Read key from file
    String strKeyPEM = "";
    BufferedReader br = new BufferedReader(new FileReader(filename));
    String line;
    while ((line = br.readLine()) != null) {
        strKeyPEM += line + "\n";
    }
    br.close();
    return strKeyPEM;
}

public static PublicKey getPublicKeyFromString(String key) throws IOException, GeneralSecurityException {
    String publicKeyPEM = key;
    publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
    publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
    BASE64Decoder b = new BASE64Decoder();
    byte[] encoded = b.decodeBuffer(publicKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("EC");
    PublicKey pubKey = (PublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
    return pubKey;
}

and this is for private key

public static PrivateKey getPrivateKey(String filename) throws IOException, GeneralSecurityException {
    String privateKeyPEM = getKey(filename);
    return getPrivateKeyFromString(privateKeyPEM);
}

public static PrivateKey getPrivateKeyFromString(String key) throws IOException, GeneralSecurityException {
    String privateKeyPEM = key;
    privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
    privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");

    BASE64Decoder b = new BASE64Decoder();
    byte[] encoded = b.decodeBuffer(privateKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("EC");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
    PrivateKey privKey = (PrivateKey) kf.generatePrivate(keySpec);
    return privKey;
}

Many thanks to @dave_thompson_085 explanation.


问:
Accessing elements in panda dataframe
How do I iterate through this dataframe?  I want to know what the nameis (AAL, AAME, or AACG) and be able to access the everything highlighted in red for name.

答:
You are trying to access the multi-index column. Accessing a multi-index column is pretty the same as the access a column in the general dataFrame. For example, if you want to access 2020-05-21 row in AAL then you have to...

```<code>df['AAL']['Date']['2020-05-21']
</code>```

Title: Accessing elements in panda dataframe

Body:
You are trying to access the multi-index column. Accessing a multi-index column is pretty the same as the access a column in the general dataFrame. For example, if you want to access 2020-05-21 row in AAL then you have to...

df['AAL']['Date']['2020-05-21']


问:
@Size Validator is not working in my Spring Project
Hi i am trying to put validation in my spring project but it is not working for me i also add all the required validator jar in my lib folder.

My Controller Class is looking like

```<code>package qm;

import java.sql.Date;
import java.text.SimpleDateFormat;

import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentAdmissionController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields(new String[] {"studentSkill","studentDOB"});
        SimpleDateFormat dateFormat=new SimpleDateFormat("dd-mm-yyyy");
        binder.registerCustomEditor(Date.class,"studentDOB", new CustomDateEditor(dateFormat, false));
    }

    @RequestMapping(value="/registration.html",method=RequestMethod.GET)
    public ModelAndView getStudentAdmissionForm() {
        ModelAndView model=new ModelAndView("AdmissionForm");

        return model;
    }

    @ModelAttribute
    public void addCommonObject(Model model) {
        model.addAttribute("headerMessage","Q-Manager.com");
    }

    @RequestMapping(value="/submit-detail.html",method=RequestMethod.POST)
    public ModelAndView studentDetail(@Valid @ModelAttribute("student1") Student student,BindingResult result) {
        if(result.hasErrors()) {
            ModelAndView model=new ModelAndView("AdmissionForm");
            return model;
        }
        ModelAndView model=new ModelAndView("AdmissionSuccess");
        return model;

    }

}
</code>```

my Student Class is

```<code>package qm;

import java.util.ArrayList;
import java.util.Date;

import javax.validation.constraints.Size;

public class Student {

    @Size(min=2,max=30)
    private String studentName;

    private String studentHobby;
    private Long studentMobile;
    private Date studentDOB;
    private ArrayList<String> studentSkill;
    private Address studentAddress;

    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public String getStudentHobby() {
        return studentHobby;
    }
    public void setStudentHobby(String studentHobby) {
        this.studentHobby = studentHobby;
    }
    public Long getStudentMobile() {
        return studentMobile;
    }
    public void setStudentMobile(Long studentMobile) {
        this.studentMobile = studentMobile;
    }
    public Date getStudentDOB() {
        return studentDOB;
    }
    public void setStudentDOB(Date studentDOB) {
        this.studentDOB = studentDOB;
    }
    public ArrayList<String> getStudentSkill() {
        return studentSkill;
    }
    public void setStudentSkill(ArrayList<String> studentSkill) {
        this.studentSkill = studentSkill;
    }
    public Address getStudentAddress() {
        return studentAddress;
    }
    public void setStudentAddress(Address studentAddress) {
        this.studentAddress = studentAddress;
    }

}
</code>```

my Address Class is

```<code>package qm;

public class Address {

    private String country,city,street,pincode;

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }

}
</code>```

and Here is my AdmissionForm.jsp

```<code><%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
    <head>
        <title>Student Form</title>
    </head>
    <body>
            <center><h4>${headerMessage}</h4></center>
            <center><h4>Student Admission Form</h4></center>
            <center>
                <form:errors path="student1.*"/>
            </center>
            <form action="submit-detail.html" method="post">
            <table>
                <tr>
                        <td>Student Name</td>
                        <td><input type="text" name="studentName"/></td>
                </tr>
                <tr>
                        <td>Hobby</td>
                        <td><input type="text" name="studentHobby"/></td>
                </tr>
                <tr>
                        <td>Student Mobile</td>
                        <td><input type="text" name="studentMobile"/></td>
                </tr>
                <tr>
                        <td>DOB</td>
                        <td><input type="text" name="studentDOB" value="May 04 09:51:52 CDT 2009"/></td>
                </tr>
                <tr>
                        <td>Skills</td>
                        <td>
                            <select name="studentSkill" multiple>
                                <option value="Core java">Core java</option>
                                <option value="Spring Core">Spring Core</option>
                                <option value="Spring MVC">Spring MVC</option>
                            </select>
                        </td>
                </tr>

            </table>

            <table>

                <tr><td>Student Address</td></tr>
                <tr><td>Country<input type="text" name="studentAddress.country"/></td></tr>
                <tr><td>City<input type="text" name="studentAddress.city"/></td></tr>
                <tr><td>Street<input type="text" name="studentAddress.street"/></td></tr>
                <tr><td>Pin Code<input type="text" name="studentAddress.pincode"/></td></tr>

                <tr>
                        <td><input type="submit" value="Submit"/></td>
                </tr>

            </table>

            </form>

    </body>
</html>
</code>```

anyone suggest me the where i am wrong so i will correct my code actually in my previous research i found that most of the people suggest regarding the jars ie need so i define all the required jars for validation in spring.

classmate-1.0.0 jars

hibernate-validator-annotation-processor-5.1.2.Final jar

jboss-logging-3.1.3.ga jar

validation-api-1.1.0.final

I used Spring 4.3.* jars for this project

答:
Try by adding below dependency in your pom.xml</p>

```<code><dependency>
    <groupId>org.hibernate</groupId>
     <artifactId>hibernate-validator</artifactId>
    <version>6.0.12.Final</version>
</dependency>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi i am trying to put validation in my spring project but it is not working for me i also add all the required validator jar in my lib folder.

My Controller Class is looking like

package qm;

import java.sql.Date;
import java.text.SimpleDateFormat;

import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentAdmissionController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields(new String[] {"studentSkill","studentDOB"});
        SimpleDateFormat dateFormat=new SimpleDateFormat("dd-mm-yyyy");
        binder.registerCustomEditor(Date.class,"studentDOB", new CustomDateEditor(dateFormat, false));
    }

    @RequestMapping(value="/registration.html",method=RequestMethod.GET)
    public ModelAndView getStudentAdmissionForm() {
        ModelAndView model=new ModelAndView("AdmissionForm");

        return model;
    }

    @ModelAttribute
    public void addCommonObject(Model model) {
        model.addAttribute("headerMessage","Q-Manager.com");
    }

    @RequestMapping(value="/submit-detail.html",method=RequestMethod.POST)
    public ModelAndView studentDetail(@Valid @ModelAttribute("student1") Student student,BindingResult result) {
        if(result.hasErrors()) {
            ModelAndView model=new ModelAndView("AdmissionForm");
            return model;
        }
        ModelAndView model=new ModelAndView("AdmissionSuccess");
        return model;

    }

}

my Student Class is

package qm;

import java.util.ArrayList;
import java.util.Date;

import javax.validation.constraints.Size;

public class Student {

    @Size(min=2,max=30)
    private String studentName;

    private String studentHobby;
    private Long studentMobile;
    private Date studentDOB;
    private ArrayList<String> studentSkill;
    private Address studentAddress;

    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public String getStudentHobby() {
        return studentHobby;
    }
    public void setStudentHobby(String studentHobby) {
        this.studentHobby = studentHobby;
    }
    public Long getStudentMobile() {
        return studentMobile;
    }
    public void setStudentMobile(Long studentMobile) {
        this.studentMobile = studentMobile;
    }
    public Date getStudentDOB() {
        return studentDOB;
    }
    public void setStudentDOB(Date studentDOB) {
        this.studentDOB = studentDOB;
    }
    public ArrayList<String> getStudentSkill() {
        return studentSkill;
    }
    public void setStudentSkill(ArrayList<String> studentSkill) {
        this.studentSkill = studentSkill;
    }
    public Address getStudentAddress() {
        return studentAddress;
    }
    public void setStudentAddress(Address studentAddress) {
        this.studentAddress = studentAddress;
    }

}

my Address Class is

package qm;

public class Address {

    private String country,city,street,pincode;

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }

}

and Here is my AdmissionForm.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

        <title>Student Form</title>

${headerMessage}

Student Admission Form

                <form:errors path="student1.*"/>

            <form action="submit-detail.html" method="post">

                        Student Name
                        <input type="text" name="studentName"/>

                        Hobby
                        <input type="text" name="studentHobby"/>

                        Student Mobile
                        <input type="text" name="studentMobile"/>

                        DOB
                        <input type="text" name="studentDOB" value="May 04 09:51:52 CDT 2009"/>

                        Skills

                            <select name="studentSkill" multiple>
                                <option value="Core java">Core java</option>
                                <option value="Spring Core">Spring Core</option>
                                <option value="Spring MVC">Spring MVC</option>
                            </select>

Student Address

Country<input type="text" name="studentAddress.country"/>

City<input type="text" name="studentAddress.city"/>

Street<input type="text" name="studentAddress.street"/>

Pin Code<input type="text" name="studentAddress.pincode"/>

                        <input type="submit" value="Submit"/>

            </form>

anyone suggest me the where i am wrong so i will correct my code actually in my previous research i found that most of the people suggest regarding the jars ie need so i define all the required jars for validation in spring.

classmate-1.0.0 jars

hibernate-validator-annotation-processor-5.1.2.Final jar

jboss-logging-3.1.3.ga jar

validation-api-1.1.0.final

I used Spring 4.3.* jars for this project

Body:
Try by adding below dependency in your pom.xml

<dependency>
    <groupId>org.hibernate</groupId>
     <artifactId>hibernate-validator</artifactId>
    <version>6.0.12.Final</version>
</dependency>


问:
i hide some imageViews inside recycler view, but when i do scroll down all imageViews hide

Hello Team!!

I'm new on android but i have knoweledge in html and javascript. So i have a JSON that have some options(img,or not img) and i create a recycler view to list this JSON and all ok, later i try that hide some imageView of card because the JSON show that this doesn't have picture. It works fine

But when i do scroll down to bottom limit all imageViews hide, i don't know how solve it and i search in web but i can't find some solution for this issue.

Code in adapter

```<code>@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onBindViewHolder(postViewHolder postViewHolder, int position) {
    addPostTimeline addPost = addPostTimelines.get(position);
    try {
        CircleImageView img=postViewHolder.imgFoto;
        JSONObject fileson=addPost.getDatosTimeine().getJSONObject("file");

        // postViewHolder.imgTimeLine = @+id/image_timeline

        if(!fileson.getBoolean("err")){ // si tiene archivos adjuntos
            switch (fileson.getString("type")){
                case "Pic":
                    imageTimeline imgTm=new imageTimeline(fileson.getString("src"), postViewHolder.imgTimeLine);
                    imgTm.execute();
                break;
                default:
                    postViewHolder.imgTimeLine.setVisibility(View.GONE);
                break;
            }
        }else{
            postViewHolder.contentFiles.setVisibility(View.GONE);
        }
        putImgProfile putImg=new putImgProfile(addPost.getDatosTimeine().getString("pDir"), img);
        putImg.execute();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

Structure of card with recycler

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    android:id="@+id/cvManana"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    card_view:cardCornerRadius="4dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">
    <LinearLayout android:background="@drawable/textlines"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:paddingTop="6dp"
        android:paddingBottom="6dp"
        android:orientation="vertical"
        android:id="@+id/post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/imgPerfil"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginRight="8dp"
                android:scaleType="centerCrop"
                android:src="@mipmap/ic_load_img" />
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <TextView
                        android:id="@+id/tv_fechaPost"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="hace 44 minutos sep. 22º 16"
                        android:textColor="#999" />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <TextView
                        android:id="@+id/tv_nickname"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingRight="12dp"
                        android:text="SonickSeven"
                        android:textColor="#24650e"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:id="@+id/contentTextStory">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/tv_postTimeLine"
                    android:textColor="#666"
                    android:textSize="15dp"
                    android:layout_gravity="left"
                    android:text="historias"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/contentFiles">
                <!-- image to hide -->
                <ImageView
                    android:id="@+id/image_timeline"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:adjustViewBounds="true"
                    android:cropToPadding="false"
                    android:scaleType="fitStart"
                    card_view:srcCompat="@drawable/campo_manana" />
                <!-- end imagen to hide -->
            </LinearLayout>
            <LinearLayout
                android:paddingTop="4dp"
                android:paddingBottom="7dp"
                android:layout_gravity="left"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <LinearLayout
                    android:gravity="right"
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_reply"
                        android:layout_gravity="center_vertical"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_reply_gray"/>
                    <TextView
                        android:id="@+id/countReply"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_share"
                        android:scaleType="centerCrop"
                        android:layout_gravity="center_vertical"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_share_gray"/>
                    <TextView
                        android:id="@+id/countShare"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:layout_gravity="center_vertical"
                        android:id="@+id/bt_like"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_like_gray"/>
                    <TextView
                        android:id="@+id/countLike"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_dislike"
                        android:layout_gravity="center_vertical"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_nolike_gray"/>
                    <TextView
                        android:id="@+id/countNoLike"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>
</code>```

i saw that when i go to bottom of scroll and up the switch trigger again, but it doesn't could because the recycler view run all array JSON. Sorry i can understand how work android-java

答:
You need to reset the visible where you don’t need to set the visible.</p>

```<code>postViewHolder.imgTimeLine.setVisibility(View.VISIBLE);// reset
if(!fileson.getBoolean("err")){ // si tiene archivos adjuntos
        switch (fileson.getString("type")){
            case "Pic":
                imageTimeline imgTm=new imageTimeline(fileson.getString("src"),
                    postViewHolder.imgTimeLine);
                imgTm.execute();
            break;
            default:
                postViewHolder.imgTimeLine.setVisibility(View.GONE);
            break;
        }
    }else{
        postViewHolder.contentFiles.setVisibility(View.GONE);
    }
</code>```

Body:
Hello Team!!

I'm new on android but i have knoweledge in html and javascript. So i have a JSON that have some options(img,or not img) and i create a recycler view to list this JSON and all ok, later i try that hide some imageView of card because the JSON show that this doesn't have picture. It works fine

But when i do scroll down to bottom limit all imageViews hide, i don't know how solve it and i search in web but i can't find some solution for this issue.

Code in adapter

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onBindViewHolder(postViewHolder postViewHolder, int position) {
    addPostTimeline addPost = addPostTimelines.get(position);
    try {
        CircleImageView img=postViewHolder.imgFoto;
        JSONObject fileson=addPost.getDatosTimeine().getJSONObject("file");

        // postViewHolder.imgTimeLine = @+id/image_timeline

        if(!fileson.getBoolean("err")){ // si tiene archivos adjuntos
            switch (fileson.getString("type")){
                case "Pic":
                    imageTimeline imgTm=new imageTimeline(fileson.getString("src"), postViewHolder.imgTimeLine);
                    imgTm.execute();
                break;
                default:
                    postViewHolder.imgTimeLine.setVisibility(View.GONE);
                break;
            }
        }else{
            postViewHolder.contentFiles.setVisibility(View.GONE);
        }
        putImgProfile putImg=new putImgProfile(addPost.getDatosTimeine().getString("pDir"), img);
        putImg.execute();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Structure of card with recycler

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    android:id="@+id/cvManana"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    card_view:cardCornerRadius="4dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">
    <LinearLayout android:background="@drawable/textlines"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:paddingTop="6dp"
        android:paddingBottom="6dp"
        android:orientation="vertical"
        android:id="@+id/post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/imgPerfil"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginRight="8dp"
                android:scaleType="centerCrop"
                android:src="@mipmap/ic_load_img" />
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <TextView
                        android:id="@+id/tv_fechaPost"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="hace 44 minutos sep. 22º 16"
                        android:textColor="#999" />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <TextView
                        android:id="@+id/tv_nickname"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingRight="12dp"
                        android:text="SonickSeven"
                        android:textColor="#24650e"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:id="@+id/contentTextStory">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/tv_postTimeLine"
                    android:textColor="#666"
                    android:textSize="15dp"
                    android:layout_gravity="left"
                    android:text="historias"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/contentFiles">

                <ImageView
                    android:id="@+id/image_timeline"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:adjustViewBounds="true"
                    android:cropToPadding="false"
                    android:scaleType="fitStart"
                    card_view:srcCompat="@drawable/campo_manana" />

            </LinearLayout>
            <LinearLayout
                android:paddingTop="4dp"
                android:paddingBottom="7dp"
                android:layout_gravity="left"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <LinearLayout
                    android:gravity="right"
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_reply"
                        android:layout_gravity="center_vertical"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_reply_gray"/>
                    <TextView
                        android:id="@+id/countReply"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_share"
                        android:scaleType="centerCrop"
                        android:layout_gravity="center_vertical"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_share_gray"/>
                    <TextView
                        android:id="@+id/countShare"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:layout_gravity="center_vertical"
                        android:id="@+id/bt_like"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_like_gray"/>
                    <TextView
                        android:id="@+id/countLike"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_dislike"
                        android:layout_gravity="center_vertical"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_nolike_gray"/>
                    <TextView
                        android:id="@+id/countNoLike"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

i saw that when i go to bottom of scroll and up the switch trigger again, but it doesn't could because the recycler view run all array JSON. Sorry i can understand how work android-java

Body:
You need to reset the visible where you don’t need to set the visible.

postViewHolder.imgTimeLine.setVisibility(View.VISIBLE);// reset
if(!fileson.getBoolean("err")){ // si tiene archivos adjuntos
        switch (fileson.getString("type")){
            case "Pic":
                imageTimeline imgTm=new imageTimeline(fileson.getString("src"),
                    postViewHolder.imgTimeLine);
                imgTm.execute();
            break;
            default:
                postViewHolder.imgTimeLine.setVisibility(View.GONE);
            break;
        }
    }else{
        postViewHolder.contentFiles.setVisibility(View.GONE);
    }


问:
Extract string between other strings using RegEx
I would like to extract the string between site: and .com using pure RegEx, e.g.,

```<code>string = "site:linkedin.com/in"
result = "linkedin"

string = "site:instagram.com"
result = "instagram"
</code>```

Thanks in advance.

答:
Like this, check https://regex101.com/r/g5bJZr/3

```<code>(?<=site:).*?(?=.com)
</code>```

It use look around advanced regex technique

Body:
I would like to extract the string between site: and .com using pure RegEx, e.g.,

string = "site:linkedin.com/in"
result = "linkedin"

string = "site:instagram.com"
result = "instagram"

Thanks in advance.

Body:
Like this, check https://regex101.com/r/g5bJZr/3

(?<=site:).*?(?=.com)

It use look around advanced regex technique


问:
Are there any sealed classes alternatives in Dart 2.0?
I have Android development background and I'm learning Flutter.

In Android it's a common practice to use Kotlin sealed classes to return a state from ViewModel e.g.

```<code>sealed class MyState {
    data class Success(val data: List<MyObject>) : MyState()
    data class Error(val error: String) : MyState()
}
</code>```

I want to use similar pattern in Flutter and return a State object from the BLOC class. What is the best way to achieve the same in Flutter?

答:
Rémi Rousselet's answer is somehow correct but as sindrenm mentioned:

Unfortunately, this isn't the same thing. Kotlin sealed classes guarantee that there are no other implementations of the given class outside of the file they're defined in. That means you can exhaust when statements (switch in Dart) by just providing all possible alternatives as cases, not having to think about potential sub-classes elsewhere

While there is an active discussion about this feature on dart language: Algebraic Data Types, but there is some libraries that can help you implement this behavior. You can use this libraries:

Sealed Unions

Super Enum

Sealed Class

And if you are using BLoC library you can use this lib:

Sealed Flutter Bloc

I hope that dart language add this feature ASAP

Body:
I have Android development background and I'm learning Flutter.

In Android it's a common practice to use Kotlin sealed classes to return a state from ViewModel e.g.

sealed class MyState {
    data class Success(val data: List<MyObject>) : MyState()
    data class Error(val error: String) : MyState()
}

I want to use similar pattern in Flutter and return a State object from the BLOC class. What is the best way to achieve the same in Flutter?


问:
Xamarin.Forms loading Xaml with LoadFromXaml is not creating contained objects for a StackLayout
I'm trying to add to an existing xamarin.forms page, chunks of xaml that will be generated dynamically.

I'm starting my research using the following example from the official docs.

Everything works fine there, but when I try to change the string with the button def for a string with the stacklayout with the button inside, only the stacklayout is inflated, with no children at all.

That's weird, because you can inflate a full page in the example, but it looks like I'm missing something here.

Any advice about how to use LoadFromXaml for partial composite objects?

```<code>// MainPage.xaml.cs
void OnLoadButtonClicked(object sender, EventArgs e)
        {
            string navigationButtonXAML = "<StackLayout><Button Text=\"Navigate\" /></StackLayout>";
            var sl = new StackLayout().LoadFromXaml(navigationButtonXAML);
            _stackLayout.Children.Add(sl);
        }
</code>```

答:
From the official doc, it's only using LoadFromXaml for single view or a complete contentPage, I also tried LoadFromXaml for layout, and it's loading the layout without its children. For loading layout with children, I'm try debugging with source code, will update later, and as a workaround, you can use layout with contentview like this:

```<code>string navigationStackLayoutXAML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ContentView xmlns=\"http://xamarin.com/schemas/2014/forms\" xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\" xmlns:d=\"http://xamarin.com/schemas/2014/forms/design\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" mc:Ignorable=\"d\" x:Class=\"LoadRuntimeXAML.CustomerViewDemo\"> <ContentView.Content> <StackLayout > <Label Text=\"Hello Xamarin.Forms!\" /> <Button Text=\"SECONDB\"/> </StackLayout> </ContentView.Content> </ContentView>";
ContentView contentView = new ContentView().LoadFromXaml(navigationStackLayoutXAML);
_stackLayout.Children.Add(contentView);
</code>```

Although it's xaml is a little bit more complex, but it can use predefined attributes just as in .xaml, also, elements inside the contentView will be accessible through:

```<code>Button secondB = contentView.FindByName<Button>("secondB");
</code>```

Body:
I'm trying to add to an existing xamarin.forms page, chunks of xaml that will be generated dynamically.

I'm starting my research using the following example from the official docs.

Everything works fine there, but when I try to change the string with the button def for a string with the stacklayout with the button inside, only the stacklayout is inflated, with no children at all.

That's weird, because you can inflate a full page in the example, but it looks like I'm missing something here.

Any advice about how to use LoadFromXaml for partial composite objects?

// MainPage.xaml.cs
void OnLoadButtonClicked(object sender, EventArgs e)
        {
            string navigationButtonXAML = "<StackLayout><Button Text=\"Navigate\" /></StackLayout>";
            var sl = new StackLayout().LoadFromXaml(navigationButtonXAML);
            _stackLayout.Children.Add(sl);
        }

Body:
From the official doc, it's only using LoadFromXaml for single view or a complete contentPage, I also tried LoadFromXaml for layout, and it's loading the layout without its children. For loading layout with children, I'm try debugging with source code, will update later, and as a workaround, you can use layout with contentview like this:

string navigationStackLayoutXAML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ContentView xmlns=\"http://xamarin.com/schemas/2014/forms\" xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\" xmlns:d=\"http://xamarin.com/schemas/2014/forms/design\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" mc:Ignorable=\"d\" x:Class=\"LoadRuntimeXAML.CustomerViewDemo\"> <ContentView.Content> <StackLayout > <Label Text=\"Hello Xamarin.Forms!\" /> <Button Text=\"SECONDB\"/> </StackLayout> </ContentView.Content> </ContentView>";
ContentView contentView = new ContentView().LoadFromXaml(navigationStackLayoutXAML);
_stackLayout.Children.Add(contentView);

Although it's xaml is a little bit more complex, but it can use predefined attributes just as in .xaml, also, elements inside the contentView will be accessible through:

Button secondB = contentView.FindByName<Button>("secondB");


答:
if you have access and can change the HTML change the inner
 to  or any inline element, the parent div have display:inline and inner div will take full width ignoring parent having inline display, because the inner div have default display block:

        hello

 secondDiv

 thirdDiv

```
</div>
</div>
</p>

<p>for your jsx code it should be like:</p>

```

    hello

  {` `}

 secondDiv

 thirdDiv

```

Title: Displaying nested divs on the same line

Body:
I am working with a react component that produces nested divs. I'd like to style force the divs to be on the same line but can only declare styles on the outer container div. Is there a way to achieve this without styling the inner divs? If only I can pass style to the "hello" div.

Currently:

hello

secondLine thirdLine

Desired:

hello secondLine thirdLine

hello

        {` `}

 secondDiv

 thirdDiv

Body:
if you have access and can change the HTML change the inner <div> to <span> or any inline element, the parent div have display:inline and inner div will take full width ignoring parent having inline display, because the inner div have default display block:

<div style="textAlign:left, whiteSpace:nowrap">
    <div style="display:inline">
        <span style="display:inline">hello</span>
    </div>
    <div style="display:inline"> secondDiv </div>
    <div style="display:inline"> thirdDiv </div>
</div>

for your jsx code it should be like:

<div style={{ textAlign: "left", whiteSpace: "nowrap" }}>
  <div style={{ display: "inline" }}>
    <span>hello</span>
  </div>
  {` `}
  <div style={{ display: "inline" }}> secondDiv </div>
  <div style={{ display: "inline" }}> thirdDiv </div>
</div>


问:
Display links from message as a link
I'm trying to replay any occurrence of a link in a text as a link, but I only get it to show the example.com as text in the message. (Just to be clear, it shows other message content if there is other content in the message than the link, but the link gets "linkified(as seen below)")

Here is the message component.

```<code>import React from "react";
import moment from "moment";
import { Comment, Image } from "semantic-ui-react";

const isOwnMessage = (message, user) => {
  return message.user.id === user.uid ? "message__self" : "";
};

const isImage = message => {
  return message.hasOwnProperty("image");
};

const timeFromNow = timestamp => moment(timestamp).fromNow();

function linkify(text) {
  var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, function(url) {
      return '<a href="' + url + '">' + url + '</a>';
  });
}

const Message = ({ message, user }) => (
  <Comment>
    <Comment.Avatar src={message.user.avatar} />
    <Comment.Content className={isOwnMessage(message, user)}>
      <Comment.Author as="a">{message.user.name}</Comment.Author>
      <Comment.Metadata>{timeFromNow(message.timestamp)}</Comment.Metadata>
      {isImage(message) ? (
        <Image src={message.image} className="message__image" />
      ) : (
        <div>
<Comment.Text>{linkify(message.content)}</Comment.Text>
        <React.Fragment dangerouslySetInnerHTML={linkify(message.content)}>
        </React.Fragment>
        </div>
      )}
    </Comment.Content>
  </Comment>
);

export default Message;
</code>```

答:
dangerouslySetInnerHTML prop needs an object with __html property

don't use React.Fragment when using dangerouslySetInnerHTML. Just use a div

Working demo

Code Snippet

function linkify(text) {
  var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
  return text.replace(urlRegex, function(url) {
    return '' + url + "";
  });
}
const text = `I'm trying to replay any occurrence of a link in a text as a link, but I only get it to show the example.com as text in the message. (Just to be clear, it shows other message content if there is other content in the message than the link, but the link gets "linkified(as seen below)")`;
export default function App() {
  return (

Hello CodeSandbox

; }

  );
}
```

Title: Display links from message as a link

Body:
I'm trying to replay any occurrence of a link in a text as a link, but I only get it to show the example.com as text in the message. (Just to be clear, it shows other message content if there is other content in the message than the link, but the link gets "linkified(as seen below)")

Here is the message component.

import React from "react";
import moment from "moment";
import { Comment, Image } from "semantic-ui-react";

const isOwnMessage = (message, user) => {
  return message.user.id === user.uid ? "message__self" : "";
};

const isImage = message => {
  return message.hasOwnProperty("image");
};

const timeFromNow = timestamp => moment(timestamp).fromNow();

function linkify(text) {
  var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, function(url) {
      return '' + url + '';
  });
}

const Message = ({ message, user }) => (
  <Comment>
    <Comment.Avatar src={message.user.avatar} />
    <Comment.Content className={isOwnMessage(message, user)}>
      <Comment.Author as="a">{message.user.name}</Comment.Author>
      <Comment.Metadata>{timeFromNow(message.timestamp)}</Comment.Metadata>
      {isImage(message) ? (
        <Image src={message.image} className="message__image" />
      ) : (

<Comment.Text>{linkify(message.content)}</Comment.Text>
        <React.Fragment dangerouslySetInnerHTML={linkify(message.content)}>
        </React.Fragment>

      )}
    </Comment.Content>
  </Comment>
);

export default Message;

Body:
dangerouslySetInnerHTML prop needs an object with __html property

don't use React.Fragment when using dangerouslySetInnerHTML. Just use a div

Working demo

Code Snippet

function linkify(text) {
  var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
  return text.replace(urlRegex, function(url) {
    return '<a href="' + url + '">' + url + "</a>";
  });
}
const text = `I'm trying to replay any occurrence of a link in a text as a link, but I only get it to show the <a href="example.com">example.com</a> as text in the message. (Just to be clear, it shows other message content if there is other content in the message than the link, but the link gets "linkified(as seen below)")`;
export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <br />
      <div dangerouslySetInnerHTML={{ __html: linkify(text) }} />; }
    </div>
  );
}