问:
CORS who has to send what?
I am having problems to understand which component has to sent which headers in what cases:

I have the following components

Browser: local, displays website

Webserver: remote, apache, serves http-website at port 80

REST-Server: remote, custom implementation in golang, serves resources at port 8080 and offers three types of ressources

/api/login (POST)

/api/foo (GET)

/api/bar/0/sub/1 (GET and POST)

Everything worked fine as long as I had the whole CORS setup working with localhost only. But now that I try to execute on the remove server I get CORS violations.

Most of the online documentation discusses what browser and server should do, but which of the servers (website vs. rest) has to do what?

Question: who has to set which Access-Control-Allow-Origin-Headers to post a login-request?

答:
The following notes gathered from various sources helped me as a CORS beginner (which I still most definitely am) - so, maybe they will also help others.

Also, I am sure the following notes are far from the full story.  And like @amon said, reverse proxying is also a way to solve for (i.e. sidestep) CORS.

1) That CORS Flowchart

See this question - the flowchart shown there is a summary describing who sends what. However, as a beginner, I found the flowchart initially difficult to understand in isolation.

I looked at this guide, which provides a lot more technical details on who can send which headers. For example, the second of its three scenarios shows who sends what for a request which includes a preflight request:

Three examples where preflighting is required are:

the request includes an authentication token

custom headers are included in the request

the request is an ajax call containing a JSON or XML payload.

In contrast, requests containing plain GETs are not preflighted.

One key point here is it is the browser - not the client application -  which manages these interactions from the browser to the server. The client application has no direct involvement in these interactions.

On the server, it is typically a CORS filter which controls the contents of the response from the server back to the browser (an example is provided below).

That might be all you need to get a reasonably complete answer to the "who sends what" question. But I was still confused.

I looked at an example, which helped me much more - see below.

I think the best insight I had, along the way, was that my client application did not need to do anything specific to address CORS restrictions. It was the browser in which my application was running which took care of client-side CORS handling. As @amon says, CORS is not intended to protect resources, but to help browsers protect users against malicious websites.

2) An Example

Looking at a specific example helped my understanding of who sends what.

Scenario: We have a client application running in a browser, at https://domainA.com. It makes an API request to an unrelated server (http://anotherdomainX.net).

The example server I show here is Tomcat - other servers may have significantly different ways of configuring a CORS filter (I don't know).  But the Tomcat example lays out a lot of the details in a relatively clear way.

See this ServerFault question for the example.

This is the XML from that example:

```<code><filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>
            http://domainA.com,
            https://domainA.com,
            http://localhost:4200
        </param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>
            Content-Type,
            X-Requested-With,
            Accept,
            Accept-Encoding,
            Accept-Language,
            Origin,
            Access-Control-Request-Method,
            Access-Control-Request-Headers,
            Connection,
            Host,
            authorization
        </param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>
            Access-Control-Allow-Origin,
            Access-Control-Allow-Credentials
        </param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

</code>```

(For Tomcat, this is added to the web.xml config file in CATALINA_HOME/conf.)

The various sections in the above filter are documented here (Tomcat 9).

But the key point is it is the above filter definition which controls what specific CORS-related are returned from the server.

The cors.allowed.origins section is where the whitelist is defined. By default, the list is empty, meaning no requests get through, except those from the same domain (origin) as the server - http://anotherdomainX.net.

3) Origin Names

This is basically what you see in the address bar of your client web-based application. It has to include the protocol, domain name and port number (if used). The root of the application context is not part of the origin name.

So, for a URL such as https://domainA.com/myapp/getdata, then https://domainA.com is the origin name.

4) Postman

This appears to crop up fairly frequently.  Why does my API call work in Postman, but not from my web client?

The basic answer is because Postman is a dev tool, not a browser.

My understanding is that it uses browser extensions, which have different rules regarding how XMLHttpRequests are handled.

Tools such as cURL are also not relevant for CORS because again as @amon says, CORS is not intended to protect resources, but to help browsers protect users against malicious websites.

5) null Origins

An example of a null origin is when you create a simple web page in a text file, open it in a browser, and have a URL like this:

```<code>file:///C:/temp/test.htm
</code>```

Here the protocol is file:.  See here for notes and warnings about this.

6) Public APIs

It's probably bad form for an answer to contain a question, but...

How do publicly available services handle CORS?  Do they just enable "everyone" in their cors-allowed-origins?

```<code><init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value> * </param-value>
</init-param>
</code>```

I guess the answer is yes. In its "common pitfalls" section, the linked article states:

CORS is a relaxation of same-origin policy while attempting to remain secure. Using * disables most security rules of CORS. There are use cases where wildcard is OK such as an open API that integrates into many 3rd party websites.

I would be delighted to edit the above notes to correct any errors, if that is appropriate.

Title: CORS who has to send what?

Body:
The following notes gathered from various sources helped me as a CORS beginner (which I still most definitely am) - so, maybe they will also help others.

Also, I am sure the following notes are far from the full story.  And like @amon said, reverse proxying is also a way to solve for (i.e. sidestep) CORS.

1) That CORS Flowchart

See this question - the flowchart shown there is a summary describing who sends what. However, as a beginner, I found the flowchart initially difficult to understand in isolation.

I looked at this guide, which provides a lot more technical details on who can send which headers. For example, the second of its three scenarios shows who sends what for a request which includes a preflight request:

Three examples where preflighting is required are:

the request includes an authentication token

custom headers are included in the request

the request is an ajax call containing a JSON or XML payload.

In contrast, requests containing plain GETs are not preflighted.

One key point here is it is the browser - not the client application -  which manages these interactions from the browser to the server. The client application has no direct involvement in these interactions.

On the server, it is typically a CORS filter which controls the contents of the response from the server back to the browser (an example is provided below).

That might be all you need to get a reasonably complete answer to the "who sends what" question. But I was still confused.

I looked at an example, which helped me much more - see below.

I think the best insight I had, along the way, was that my client application did not need to do anything specific to address CORS restrictions. It was the browser in which my application was running which took care of client-side CORS handling. As @amon says, CORS is not intended to protect resources, but to help browsers protect users against malicious websites.

2) An Example

Looking at a specific example helped my understanding of who sends what.

Scenario: We have a client application running in a browser, at https://domainA.com. It makes an API request to an unrelated server (http://anotherdomainX.net).

The example server I show here is Tomcat - other servers may have significantly different ways of configuring a CORS filter (I don't know).  But the Tomcat example lays out a lot of the details in a relatively clear way.

See this ServerFault question for the example.

This is the XML from that example:

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>
            http://domainA.com,
            https://domainA.com,
            http://localhost:4200
        </param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>
            Content-Type,
            X-Requested-With,
            Accept,
            Accept-Encoding,
            Accept-Language,
            Origin,
            Access-Control-Request-Method,
            Access-Control-Request-Headers,
            Connection,
            Host,
            authorization
        </param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>
            Access-Control-Allow-Origin,
            Access-Control-Allow-Credentials
        </param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

(For Tomcat, this is added to the web.xml config file in CATALINA_HOME/conf.)

The various sections in the above filter are documented here (Tomcat 9).

But the key point is it is the above filter definition which controls what specific CORS-related are returned from the server.

The cors.allowed.origins section is where the whitelist is defined. By default, the list is empty, meaning no requests get through, except those from the same domain (origin) as the server - http://anotherdomainX.net.

3) Origin Names

This is basically what you see in the address bar of your client web-based application. It has to include the protocol, domain name and port number (if used). The root of the application context is not part of the origin name.

So, for a URL such as https://domainA.com/myapp/getdata, then https://domainA.com is the origin name.

4) Postman

This appears to crop up fairly frequently.  Why does my API call work in Postman, but not from my web client?

The basic answer is because Postman is a dev tool, not a browser.

My understanding is that it uses browser extensions, which have different rules regarding how XMLHttpRequests are handled.

Tools such as cURL are also not relevant for CORS because again as @amon says, CORS is not intended to protect resources, but to help browsers protect users against malicious websites.

5) null Origins

An example of a null origin is when you create a simple web page in a text file, open it in a browser, and have a URL like this:

file:///C:/temp/test.htm

Here the protocol is file:.  See here for notes and warnings about this.

6) Public APIs

It's probably bad form for an answer to contain a question, but...

How do publicly available services handle CORS?  Do they just enable "everyone" in their cors-allowed-origins?

<init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value> * </param-value>
</init-param>

I guess the answer is yes. In its "common pitfalls" section, the linked article states:

CORS is a relaxation of same-origin policy while attempting to remain secure. Using * disables most security rules of CORS. There are use cases where wildcard is OK such as an open API that integrates into many 3rd party websites.

I would be delighted to edit the above notes to correct any errors, if that is appropriate.


来源: stackexchange

问:
Fast way of adding fields to a nested dict
I need a help with improving my code.
I've got a nested dict with many levels:

```<code>{
    "11": {
        "FacLC": {
            "immty": [
                "in_mm",
                "in_mm"
            ],
            "moood": [
                "in_oo",
                "in_oo"
            ]
        }
    },
    "22": {
        "FacLC": {
            "immty": [
                "in_mm",
                "in_mm",
                "in_mm"
            ]
        }
    }
}
</code>```

And I want to add additional fields on every level, so my output looks like this:

```<code>[
    {
        "id": "",
        "name": "11",
        "general": [
            {
                "id": "",
                "name": "FacLC",
                "specifics": [
                    {
                        "id": "",
                        "name": "immty",
                        "characteristics": [
                            {
                                "id": "",
                                "name": "in_mm"
                            },
                            {
                                "id": "",
                                "name": "in_mm"
                            }
                        ]
                    },
                    {
                        "id": "",
                        "name": "moood",
                        "characteristics": [
                            {
                                "id": "",
                                "name": "in_oo"
                            },
                            {
                                "id": "",
                                "name": "in_oo"
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "id": "",
        "name": "22",
        "general": [
            {
                "id": "",
                "name": "FacLC",
                "specifics": [
                    {
                        "id": "",
                        "name": "immty",
                        "characteristics": [
                            {
                                "id": "",
                                "name": "in_mm"
                            },
                            {
                                "id": "",
                                "name": "in_mm"
                            },
                            {
                                "id": "",
                                "name": "in_mm"
                            }
                        ]
                    }
                ]
            }
        ]
    }
]
</code>```

I managed to write a 4-times nested for loop, what I find inefficient and inelegant:

```<code>for main_name, general in my_dict.items():
    generals = []
    for general_name, specific in general.items():
        specifics = []
        for specific_name, characteristics in specific.items():
            characteristics_dicts = []
            for characteristic in characteristics:
                characteristics_dicts.append({
                    "id": "",
                    "name": characteristic,
                })
            specifics.append({
                "id": "",
                "name": specific_name,
                "characteristics": characteristics_dicts,
            })
        generals.append({
            "id": "",
            "name": general_name,
            "specifics": specifics,
        })
    my_new_dict.append({
        "id": "",
        "name": main_name,
        "general": generals,
    })
</code>```

I am wondering if there is more compact and efficient solution.

答:
In the past I created a function to do it. Basically you call this function everytime that you need to add new fields to a nested dict, independently on how many levels this nested dict have. You only have to inform the 'full path' , that I called the 'key_map'.
Like ['node1','node1a','node1apart3']</p>

```<code>def insert_value_using_map(_nodes_list_to_be_appended, _keys_map, _value_to_be_inserted):
    for _key in _keys_map[:-1]:
        _nodes_list_to_be_appended = _nodes_list_to_be_appended.setdefault(_key, {})
    _nodes_list_to_be_appended[_keys_map[-1]] = _value_to_be_inserted
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need a help with improving my code.
I've got a nested dict with many levels:

{
    "11": {
        "FacLC": {
            "immty": [
                "in_mm",
                "in_mm"
            ],
            "moood": [
                "in_oo",
                "in_oo"
            ]
        }
    },
    "22": {
        "FacLC": {
            "immty": [
                "in_mm",
                "in_mm",
                "in_mm"
            ]
        }
    }
}

And I want to add additional fields on every level, so my output looks like this:

[
    {
        "id": "",
        "name": "11",
        "general": [
            {
                "id": "",
                "name": "FacLC",
                "specifics": [
                    {
                        "id": "",
                        "name": "immty",
                        "characteristics": [
                            {
                                "id": "",
                                "name": "in_mm"
                            },
                            {
                                "id": "",
                                "name": "in_mm"
                            }
                        ]
                    },
                    {
                        "id": "",
                        "name": "moood",
                        "characteristics": [
                            {
                                "id": "",
                                "name": "in_oo"
                            },
                            {
                                "id": "",
                                "name": "in_oo"
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "id": "",
        "name": "22",
        "general": [
            {
                "id": "",
                "name": "FacLC",
                "specifics": [
                    {
                        "id": "",
                        "name": "immty",
                        "characteristics": [
                            {
                                "id": "",
                                "name": "in_mm"
                            },
                            {
                                "id": "",
                                "name": "in_mm"
                            },
                            {
                                "id": "",
                                "name": "in_mm"
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

I managed to write a 4-times nested for loop, what I find inefficient and inelegant:

for main_name, general in my_dict.items():
    generals = []
    for general_name, specific in general.items():
        specifics = []
        for specific_name, characteristics in specific.items():
            characteristics_dicts = []
            for characteristic in characteristics:
                characteristics_dicts.append({
                    "id": "",
                    "name": characteristic,
                })
            specifics.append({
                "id": "",
                "name": specific_name,
                "characteristics": characteristics_dicts,
            })
        generals.append({
            "id": "",
            "name": general_name,
            "specifics": specifics,
        })
    my_new_dict.append({
        "id": "",
        "name": main_name,
        "general": generals,
    })

I am wondering if there is more compact and efficient solution.

Body:
In the past I created a function to do it. Basically you call this function everytime that you need to add new fields to a nested dict, independently on how many levels this nested dict have. You only have to inform the 'full path' , that I called the 'key_map'.
Like ['node1','node1a','node1apart3']

def insert_value_using_map(_nodes_list_to_be_appended, _keys_map, _value_to_be_inserted):
    for _key in _keys_map[:-1]:
        _nodes_list_to_be_appended = _nodes_list_to_be_appended.setdefault(_key, {})
    _nodes_list_to_be_appended[_keys_map[-1]] = _value_to_be_inserted


问:
Get firebase/firestore SERVERTIME and convert to date (month and day)
I am trying to get the server time either from Firebase or Firestore. I have tried ServerValue.TIMESTAMP but it is not pulling a value when i try to view in Log.d("Time", "${SERVERValue.TIMESTAMP}").

What i would like to do is eventually convert this to a simple date i.e. month and day so that i can store the future expiry date of an account. e.g. take today's date, add 31 days and in the future once the date is reached lock the user out of the account if not renewed.

How would I retrieve the original stored date, convert to date and then do a logical check to see if expired or not?

答:
ServerValue.TIMESTAMP is a constant that is used as a placeholder value that once uploaded to the server, is replaced with the server time.

Based on the sensitivity of setting an account's expiry date, I would not handle this on your client and instead use one of the Admin SDKs on a trusted server or use Cloud Functions.

However, to get the current server time, you can make use of Kronos and the time.google.com NTP server (You can also use time1, time2, time3 and time4 appended with .google.com).


问:
How do I reduce a list in a Magnolia JavaScript model?
I'm attempting to reduce a FreeMarker list in a Magnolia JavaScript model. I want all items that start with a capital "P".

```<code>[#assign list = ["Poker", "Pet", "Dog", "Cat", "Penguin", "Paddle", "punk"]]
</code>```

My function should return:

```<code>["Poker", "Pet", "Penguin", "Paddle"]
</code>```

Attempts

I attempted to use Array.prototype.reduce().

var Model = function() {
  this.reduceList = function(list) {
    return list.reduce(function(reducedList, item) {
      if (item.indexOf('P') !== -1) {
        reducedList.push(item);
      }
      return reducedList;
    }, []);
  }
};

new Model();
```

```[#assign filteredList = model.reduceList(['Poker', 'Pet', 'Dog', 'Cat', 'Penguin', 'Paddle', 'punk'])]
```

<p>However, I get the following error.</p>

```jdk.nashorn.internal.runtime.ECMAException: TypeError: list.reduce is not a function
```

<p><strong>Note:</strong> Magnolia JavaScript models are built on Nashorn.</p>

<h2>Debugging</h2>

<p>When I return the type of the list:</p>

<pre class="lang-js prettyprint-override"><code>this.reduceList = function(list) {
  return typeof list;
}
</code>```

I get an object:

```<code>object
</code>```

When I return the list as a string:

this.reduceList = function(list) {
  return list.toString();
};
```

<p>I get a list:</p>

```[Poker, Pet, Dog, Cat, Penguin, Paddle, punk]
```

How do I reduce a list in a Magnolia JavaScript model?

答:
The typeof operator in JavaScript returns object for an array value (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof).

When you call toString(), you are simply printing out the values of the array that you have.

Also, Prasana Kannan is correct. This is not a good use of reduce. Reduce is used to return one value from a set of values (https://engineering.khanacademy.org/posts/lets-reduce.htm). Using filter would be more elegant here (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).

As for why reduce is not recognized as a function, you may have to look up your version of Nashorn to see if it even includes an implementation for reduce.

Body:
I'm attempting to reduce a FreeMarker list in a Magnolia JavaScript model. I want all items that start with a capital "P".

[#assign list = ["Poker", "Pet", "Dog", "Cat", "Penguin", "Paddle", "punk"]]

My function should return:

["Poker", "Pet", "Penguin", "Paddle"]

Attempts

I attempted to use Array.prototype.reduce().

var Model = function() {
  this.reduceList = function(list) {
    return list.reduce(function(reducedList, item) {
      if (item.indexOf('P') !== -1) {
        reducedList.push(item);
      }
      return reducedList;
    }, []);
  }
};

new Model();

[#assign filteredList = model.reduceList(['Poker', 'Pet', 'Dog', 'Cat', 'Penguin', 'Paddle', 'punk'])]

However, I get the following error.

jdk.nashorn.internal.runtime.ECMAException: TypeError: list.reduce is not a function

Note: Magnolia JavaScript models are built on Nashorn.

Debugging

When I return the type of the list:

this.reduceList = function(list) {
  return typeof list;
}

I get an object:

object

When I return the list as a string:

this.reduceList = function(list) {
  return list.toString();
};

I get a list:

[Poker, Pet, Dog, Cat, Penguin, Paddle, punk]

How do I reduce a list in a Magnolia JavaScript model?


问:
How to perform value check inside class
So the task is to make a universal Vector class to perform add method whatever(str or int) the x,y values are.
So here is the code that i've tried to execute just to check if try,except somehow works inside a class

```<code>class Vector():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __valuecheck__(self):
        try:
            self.x + "a"
        except TypeError:
            return str(self.x)
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    def __repr__(self):
        return "Vector({},{})".format(self.x,self.y)

a = Vector(1,"a")
b = Vector("a",2)
c = a.__add__(b)
print(c)
</code>```

The expected output is

```<code>Vector(1a,a2)
</code>```

I've tried different variants, defining classic function e.g. def valuecheck(), as well tried adding try,except to add and init method, but none seem to work. Need your help guys, any tip is very appreciated!
Cheers!

答:
I think I have found the answer.</p>

```<code>class Vector():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __valuecheck__(self):
        try:
            self.x + "a"
        except TypeError:
            return str(self.x)
    def __repr__(self):
        return "Vector({},{})".format(self.x,self.y)
    def __add__(self, other):
        mvbh = str(self.x), str(self.y) # My Vector Before Hand
        myVector = ''.join(mvbh)

        ovbh = str(other.x), str(other.y) # Other Vector Before Hand
        otherVector = ''.join(ovbh)

        final = "Vector({}, {})".format(myVector, otherVector) # Change this to create a new vector

        print(final)

a = Vector(1,"a")
b = Vector("a",2)
a.__add__(b)
</code>```

Title: How to perform value check inside class

Body:
So the task is to make a universal Vector class to perform add method whatever(str or int) the x,y values are.
So here is the code that i've tried to execute just to check if try,except somehow works inside a class

class Vector():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __valuecheck__(self):
        try:
            self.x + "a"
        except TypeError:
            return str(self.x)
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    def __repr__(self):
        return "Vector({},{})".format(self.x,self.y)

a = Vector(1,"a")
b = Vector("a",2)
c = a.__add__(b)
print(c)

The expected output is

Vector(1a,a2)

I've tried different variants, defining classic function e.g. def valuecheck(), as well tried adding try,except to add and init method, but none seem to work. Need your help guys, any tip is very appreciated!
Cheers!

Body:
I think I have found the answer.

class Vector():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __valuecheck__(self):
        try:
            self.x + "a"
        except TypeError:
            return str(self.x)
    def __repr__(self):
        return "Vector({},{})".format(self.x,self.y)
    def __add__(self, other):
        mvbh = str(self.x), str(self.y) # My Vector Before Hand
        myVector = ''.join(mvbh)

        ovbh = str(other.x), str(other.y) # Other Vector Before Hand
        otherVector = ''.join(ovbh)

        final = "Vector({}, {})".format(myVector, otherVector) # Change this to create a new vector

        print(final)

a = Vector(1,"a")
b = Vector("a",2)
a.__add__(b)


问:
Calling multiple API requests and waiting for response using Kotlin Coroutines
Code changes applied.

I followed a guide on how to create a kotlin coroutine and do network request and ended up with:

```<code>suspend fun <T : Any> safeApiCall(call: suspend () -> Response<T>): ApiResult<T> {
    return safeApiResult(call)
}

private suspend fun <T: Any> safeApiResult(call: suspend ()-> Response<T>) : ApiResult<T>{
    val response = call.invoke()

    return if (response.isSuccessful) {
        val body = response.body()

        if (body == null) {
            ApiResult.Error(response.code())
        } else {
            ApiResult.Success(body)
        }
    } else {
        ApiResult.Error(response.code())
    }
}

suspend fun getSnappedPoints(path: String): ApiResult<SnappedPointsData> {
    return safeApiCall(
        call = { googleRoadsService.getSnappedPoints(path).await()}
    )
}
</code>```

and calling the network request looks like this:

```<code>private fun getSnappedPoints() {
    val paths = Utils.getPathFromLocations(locations)

    CoroutineScope(Dispatchers.IO).launch {
        val results = paths.map {
            async { googleRoadsRepository.getSnappedPoints(it) }
        }.awaitAll()

        Timber.i("results: ${results.size}")

        val snappedPoints = ArrayList<LocationSnap>()

        results.forEach {
            if (it is ApiResult.Success) {
                snappedPoints.addAll(it.data.snappedPoints)
            }
        }

        withContext(Dispatchers.Main) {
            if (snappedPoints.isNotEmpty()) {
                drawPolyline(snappedPoints)
            } else {
                showError()
            }
        }
    }
}
</code>```

Current problem:

The function getSnappedPoints() is called when I click on specific item. For the very first time it actually calls google API and result is > 0 (size), but if I go back and click second time on the same/other item, getSnappedPoints() is called, paths is not Empty, but somehow it does not call googleRoadsRepository.getSnappedPoints(it) and kinda skips that step in debug and all I can see is that result is always 0. What could cause this?

答:
Each coroutine (launch) is a unit of concurrency, if you want to run each request concurrently, you'll have to do a launch/async for each concurrent request.

```<code>private fun getPoints() {
    val multipleParams = Utils.getArrayListOfParams()

    coroutineJob = CoroutineScope(Dispatchers.IO).launch {
        val results = multipleParams.map {
            async { Repository.getPoints(it) }
        }.awaitAll()

        // Do something with results, once all have been gotten.
        // result and result2, result[it] has finished, continue)
    }
}
</code>```

Bonus:

If you create a CoroutineScope without cancelling it, then you should use GlobalScope as an optimisation. (Like so GlobalScope.launch(Dispatchers.IO))

You don't need Dispatchers.IO to do this, since it appears you are not blocking the coroutine/thread. Dispatchers.Default will do just fine.

I'm not sure what you're using coroutineJob variable for but it looks suspicious.

Body:
Code changes applied.

I followed a guide on how to create a kotlin coroutine and do network request and ended up with:

suspend fun <T : Any> safeApiCall(call: suspend () -> Response<T>): ApiResult<T> {
    return safeApiResult(call)
}

private suspend fun <T: Any> safeApiResult(call: suspend ()-> Response<T>) : ApiResult<T>{
    val response = call.invoke()

    return if (response.isSuccessful) {
        val body = response.body()

        if (body == null) {
            ApiResult.Error(response.code())
        } else {
            ApiResult.Success(body)
        }
    } else {
        ApiResult.Error(response.code())
    }
}

suspend fun getSnappedPoints(path: String): ApiResult<SnappedPointsData> {
    return safeApiCall(
        call = { googleRoadsService.getSnappedPoints(path).await()}
    )
}

and calling the network request looks like this:

private fun getSnappedPoints() {
    val paths = Utils.getPathFromLocations(locations)

    CoroutineScope(Dispatchers.IO).launch {
        val results = paths.map {
            async { googleRoadsRepository.getSnappedPoints(it) }
        }.awaitAll()

        Timber.i("results: ${results.size}")

        val snappedPoints = ArrayList<LocationSnap>()

        results.forEach {
            if (it is ApiResult.Success) {
                snappedPoints.addAll(it.data.snappedPoints)
            }
        }

        withContext(Dispatchers.Main) {
            if (snappedPoints.isNotEmpty()) {
                drawPolyline(snappedPoints)
            } else {
                showError()
            }
        }
    }
}

Current problem:

The function getSnappedPoints() is called when I click on specific item. For the very first time it actually calls google API and result is > 0 (size), but if I go back and click second time on the same/other item, getSnappedPoints() is called, paths is not Empty, but somehow it does not call googleRoadsRepository.getSnappedPoints(it) and kinda skips that step in debug and all I can see is that result is always 0. What could cause this?

Body:
Each coroutine (launch) is a unit of concurrency, if you want to run each request concurrently, you'll have to do a launch/async for each concurrent request.

private fun getPoints() {
    val multipleParams = Utils.getArrayListOfParams()

    coroutineJob = CoroutineScope(Dispatchers.IO).launch {
        val results = multipleParams.map {
            async { Repository.getPoints(it) }
        }.awaitAll()

        // Do something with results, once all have been gotten.
        // result and result2, result[it] has finished, continue)
    }
}

Bonus:

If you create a CoroutineScope without cancelling it, then you should use GlobalScope as an optimisation. (Like so GlobalScope.launch(Dispatchers.IO))

You don't need Dispatchers.IO to do this, since it appears you are not blocking the coroutine/thread. Dispatchers.Default will do just fine.

I'm not sure what you're using coroutineJob variable for but it looks suspicious.


问:
Await function to finish calling another API
I am new to using async/await and having a couple issues.

I have the code below, which seems to not wait until the previous function is finished?

```<code>var url = require('url');
var path = require('path');
var https = require('https');
var request = require('request');
var url1 =
var url2 =
var url3 =

module.exports = async function (context, req) {
    var call = await callUrl(context, url1);
    context.log(call);
    var call2 = await callUrl(context, url2);
    context.log(call2);
    var call3 = await callUrl(context, url3);
    context.log(call3);
};

function callUrl (context, web) {
    var requestUrl = url.parse(web);
    const requestOptions = {
        hostname: requestUrl.hostname,
        path: requestUrl.path,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    };
    var request = https.request(requestOptions, function(res) {
        var data = "";
        res.on('data', function (chunk) {
            data += chunk;
        });
        res.on('end', function () {
            var jsonData = JSON.parse(data);
            return jsonData;
        });
    }).on('error', function(error) {
        context.log("request error:", error);
        return context.done();
    });
    request.end();
}
</code>```

I am trying to get call to happen, then when it is finished call2, then when that is finished call3.

Can someone pinpoint why this does not occur? Currently, it hits all 3 pretty much asap, and each context.log is undefined presumably because the endpoints don't return anything. Each url is another azure function app API I have created.

There is nothing I am requiring to return from each call to use, I simply want them to finish before moving on the the next function.

答:
Your  callUrl method, which you call with await, needs to be either async itself or return a Promise. Why? because the work it does is itself asynchronous.

Here's your function adapted to use a Promise and return its actual value via the resolve() callback.

```<code>function callUrl (context, web) {
  var requestUrl = url.parse(web);
  const requestOptions = {
    hostname: requestUrl.hostname,
    path: requestUrl.path,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    }
  };
  return new Promise(function (resolve,reject) {
    var request = https.request( requestOptions, function( res ) {
      var data = "";
      res.on( 'data', function( chunk ) {
        data += chunk;
      } );
      res.on( 'end', function() {
        var jsonData = JSON.parse( data );
        resolve( jsonData );
      } );
    } )
    .on( 'error', function( error ) {
      reject(error);
    } );
    request.end();
  });
}
</code>```

Notice that you use a POST operation with no body. That's a little unconventional.

Body:
I am new to using async/await and having a couple issues.

I have the code below, which seems to not wait until the previous function is finished?

var url = require('url');
var path = require('path');
var https = require('https');
var request = require('request');
var url1 =
var url2 =
var url3 =

module.exports = async function (context, req) {
    var call = await callUrl(context, url1);
    context.log(call);
    var call2 = await callUrl(context, url2);
    context.log(call2);
    var call3 = await callUrl(context, url3);
    context.log(call3);
};

function callUrl (context, web) {
    var requestUrl = url.parse(web);
    const requestOptions = {
        hostname: requestUrl.hostname,
        path: requestUrl.path,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    };
    var request = https.request(requestOptions, function(res) {
        var data = "";
        res.on('data', function (chunk) {
            data += chunk;
        });
        res.on('end', function () {
            var jsonData = JSON.parse(data);
            return jsonData;
        });
    }).on('error', function(error) {
        context.log("request error:", error);
        return context.done();
    });
    request.end();
}

I am trying to get call to happen, then when it is finished call2, then when that is finished call3.

Can someone pinpoint why this does not occur? Currently, it hits all 3 pretty much asap, and each context.log is undefined presumably because the endpoints don't return anything. Each url is another azure function app API I have created.

There is nothing I am requiring to return from each call to use, I simply want them to finish before moving on the the next function.

Body:
Your  callUrl method, which you call with await, needs to be either async itself or return a Promise. Why? because the work it does is itself asynchronous.

Here's your function adapted to use a Promise and return its actual value via the resolve() callback.

function callUrl (context, web) {
  var requestUrl = url.parse(web);
  const requestOptions = {
    hostname: requestUrl.hostname,
    path: requestUrl.path,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    }
  };
  return new Promise(function (resolve,reject) {
    var request = https.request( requestOptions, function( res ) {
      var data = "";
      res.on( 'data', function( chunk ) {
        data += chunk;
      } );
      res.on( 'end', function() {
        var jsonData = JSON.parse( data );
        resolve( jsonData );
      } );
    } )
    .on( 'error', function( error ) {
      reject(error);
    } );
    request.end();
  });
}

Notice that you use a POST operation with no body. That's a little unconventional.


问:
Replace all strings with numbers based on conditions
I have a column of data that describes possible diseases. I am trying to change these qualitative values into quantitative ones. So for example setting conditions such as "if a row contains words "blood pressure" delete all characters and replace to be 3, if row contains "heart" replace to be 2, if the row contains "diabetes" or "kidney disease" replace to be 1, if any other condition replace to be 0.5"

For example my data looks like:

```<code>Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease
Gene4    Name=Childhood ear infection
Gene5    NA
Gene6    Name=kidney disease
</code>```

The output I am trying to reach based on my mentioned conditions is:

```<code>Gene Condition
Gene1    0.5
Gene2    3
Gene3    2
Gene4    0.5
Gene5    NA
Gene6    1
</code>```

I am new to R and so not sure if the way I'm trying is the best, but I'm trying to run  my conditions to replace the specific strings (but not all characters), producing multiple numbers in a row (mixed with strings) if more than 1 condition is met, then applying a getmaxfunction for each row to get the largest number available. However I am stuck on setting up conditions to perform the string to number conversation.
I've been trying to do:

```<code>data$condition[data$condition == "blood pressure"] <- "3"
data$condition[data$condition == "heart disease"] <- "2"
data$condition[data$condition == "diabetes" | "kidney disease"] <- "1"
data$condition[data$condition == "Name" && !"diabetes" | "kidney disease" | "blood pressure" | "heart disease"] <- "0.5"
</code>```

However this gives an error that ' 'object of type 'closure' is not subsettable', and for this approach at least, I can't find the solution for this error online. Any help would be appreciated.

Example data (first time trying to give data, please let me know if something is amiss):

```<code>structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition = c("    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"    Name=blood pressure, Name=diabetes", "Name=heart disease",
"Name=Childhood ear infection", NA, "Name=kidney disease")), row.names = c(NA,
-6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x000001bea99a1ef0>)
</code>```

答:
Using grepl:

```<code>data$Condition[ grepl("blood pressure", data$Condition) ] <- "3"
data$Condition[ grepl("heart disease",  data$Condition) ] <- "2"
# etc...
</code>```

Or slightly better approach, when there are multiple conditions convert them into new rows, then we can do direct comparison using == instead of regex match grepl:

```<code>res <- data[, list(Condition = unlist(strsplit(Condition, ","))), by = Gene
            ][, Condition := gsub("Name=", "", Condition) ]

res
# Gene                                         Condition
# 1: Gene1               Asymmetrical dimethylarginine level
# 2: Gene1                Bipolar disorder and schizophrenia
# 3: Gene1  3-hydroxypropylmercapturic acid levels in smoker
# 4: Gene2                                    blood pressure
# 5: Gene2                                          diabetes
# 6: Gene3                                     heart disease
# 7: Gene4                           Childhood ear infection
# 8: Gene5                                              <NA>
# 9: Gene6                                    kidney disease
</code>```

Body:
I have a column of data that describes possible diseases. I am trying to change these qualitative values into quantitative ones. So for example setting conditions such as "if a row contains words "blood pressure" delete all characters and replace to be 3, if row contains "heart" replace to be 2, if the row contains "diabetes" or "kidney disease" replace to be 1, if any other condition replace to be 0.5"

For example my data looks like:

Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease
Gene4    Name=Childhood ear infection
Gene5    NA
Gene6    Name=kidney disease

The output I am trying to reach based on my mentioned conditions is:

Gene Condition
Gene1    0.5
Gene2    3
Gene3    2
Gene4    0.5
Gene5    NA
Gene6    1

I am new to R and so not sure if the way I'm trying is the best, but I'm trying to run  my conditions to replace the specific strings (but not all characters), producing multiple numbers in a row (mixed with strings) if more than 1 condition is met, then applying a getmaxfunction for each row to get the largest number available. However I am stuck on setting up conditions to perform the string to number conversation.
I've been trying to do:

data$condition[data$condition == "blood pressure"] <- "3"
data$condition[data$condition == "heart disease"] <- "2"
data$condition[data$condition == "diabetes" | "kidney disease"] <- "1"
data$condition[data$condition == "Name" && !"diabetes" | "kidney disease" | "blood pressure" | "heart disease"] <- "0.5"

However this gives an error that ' 'object of type 'closure' is not subsettable', and for this approach at least, I can't find the solution for this error online. Any help would be appreciated.

Example data (first time trying to give data, please let me know if something is amiss):

structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition = c("    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"    Name=blood pressure, Name=diabetes", "Name=heart disease",
"Name=Childhood ear infection", NA, "Name=kidney disease")), row.names = c(NA,
-6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x000001bea99a1ef0>)

Body:
Using grepl:

data$Condition[ grepl("blood pressure", data$Condition) ] <- "3"
data$Condition[ grepl("heart disease",  data$Condition) ] <- "2"
# etc...

Or slightly better approach, when there are multiple conditions convert them into new rows, then we can do direct comparison using == instead of regex match grepl:

res <- data[, list(Condition = unlist(strsplit(Condition, ","))), by = Gene
            ][, Condition := gsub("Name=", "", Condition) ]

res
# Gene                                         Condition
# 1: Gene1               Asymmetrical dimethylarginine level
# 2: Gene1                Bipolar disorder and schizophrenia
# 3: Gene1  3-hydroxypropylmercapturic acid levels in smoker
# 4: Gene2                                    blood pressure
# 5: Gene2                                          diabetes
# 6: Gene3                                     heart disease
# 7: Gene4                           Childhood ear infection
# 8: Gene5                                              <NA>
# 9: Gene6                                    kidney disease


问:
how to use SymPy or other library to have a numerical solution
I was trying to solve two equations for two unknown symbols 'Diff' and 'OHs'. the equations are shown below

```<code>x = (8.67839580228369e-26*Diff + 7.245e-10*OHs**3 +
1.24402291559836e-10*OHs**2 + OHs*(-2.38073807380738e-19*Diff -
2.8607855978291e-18) - 1.01141409254177e-29)

J= (-0.00435840284294195*Diff**0.666666666666667*(1 +
3.64525434266056e-7/OHs) - 1)

solution = sym.nsolve ((x, J), (OHs, Diff), (0.000001, 0.000001))
print (solution)
</code>```

is this the correct way to solve for the two unknowns?

Thanks for your help :)

答:
Your expressions do not meet Sympy requirements, including the exponential expressions. May be it is easier to start with a simpler system to solve with two unknowns and only a square such as:

```<code>from sympy.abc import a,b,x, y
from sympy import solve,exp
eq1= a*x**2 + b*y+ exp(0)
eq2= x + y + 2
sol=solve((eq1, eq2),(x,y),dict=True)
</code>```

sol includes your answers and you have access to solutions with sol[0][x] and sol[0][y]. Giving values to the parameters is done with the .sub() method:

```<code>sol[0][x].subs({a:1, b:2}) #gives -1
sol[0][y].subs({a:1, b:2}) #gives -1
</code>```

Body:
I was trying to solve two equations for two unknown symbols 'Diff' and 'OHs'. the equations are shown below

x = (8.67839580228369e-26*Diff + 7.245e-10*OHs**3 +
1.24402291559836e-10*OHs**2 + OHs*(-2.38073807380738e-19*Diff -
2.8607855978291e-18) - 1.01141409254177e-29)

J= (-0.00435840284294195*Diff**0.666666666666667*(1 +
3.64525434266056e-7/OHs) - 1)

solution = sym.nsolve ((x, J), (OHs, Diff), (0.000001, 0.000001))
print (solution)

is this the correct way to solve for the two unknowns?

Thanks for your help :)

Body:
Your expressions do not meet Sympy requirements, including the exponential expressions. May be it is easier to start with a simpler system to solve with two unknowns and only a square such as:

from sympy.abc import a,b,x, y
from sympy import solve,exp
eq1= a*x**2 + b*y+ exp(0)
eq2= x + y + 2
sol=solve((eq1, eq2),(x,y),dict=True)

sol includes your answers and you have access to solutions with sol[0][x] and sol[0][y]. Giving values to the parameters is done with the .sub() method:

sol[0][x].subs({a:1, b:2}) #gives -1
sol[0][y].subs({a:1, b:2}) #gives -1


问:
How can I connect a MonoDevelop project to BitBucket using git or svn?
i'm using BitBucket to host my code because I can have a free PRIVATE repository.

Can someone show me the connection details if wish to use MonoDevelop to connect to bitbuck via git, svn please? I'm under the impression that HG is not support in MonoDevelop.

答: Look here on how you can use Git and have a free private Hg repo on BitBucket - http://quirkygba.blogspot.com/2011/02/how-to-use-bitbuckets-free-private.html</p>

ContentLicense: CC BY-SA 3.0


问:
extending or inferring (PID / UFD) in a Lean class definition
Why is mathlib's definition of UFD this:

```<code>class unique_factorization_domain (α : Type*) [integral_domain α] :=
(factors : α → multiset α)
(factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a)
(prime_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, prime x)
</code>```

(asking for the integral domain structure to be inferred by type class inference) but its definition of PID is this:

```<code>class principal_ideal_domain (α : Type*) extends integral_domain α :=
(principal : ∀ (S : ideal α), S.is_principal)
</code>```

extending the integral domain structure? What is the difference? Does the old structure command have something to do with it?

答: My impression from the discussion on the Lean chat is that for subtle reasons related to type class inference it is probably better to extend the class, and so perhaps the definition of UFD needs to be refactored. </p>

Body:
Why is mathlib's definition of UFD this:

class unique_factorization_domain (α : Type*) [integral_domain α] :=
(factors : α → multiset α)
(factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a)
(prime_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, prime x)

(asking for the integral domain structure to be inferred by type class inference) but its definition of PID is this:

class principal_ideal_domain (α : Type*) extends integral_domain α :=
(principal : ∀ (S : ideal α), S.is_principal)

extending the integral domain structure? What is the difference? Does the old structure command have something to do with it?


问:
How to add the style to div that has adjacent sibling using react?
i want to add a class to a div that has adjacent sibling selector.

What i am trying to do?
I have two divs which appear on top of each other. so was thinking to move one div (prev_div) slightly above div(next_div) so they are visible. when next_div is closed the prev_div should get back to its original position.

Below is the html code,

```<code><div class="wrapper">
    <div class="prev_div">previous</div>
    <div class="next_div">next</div>
</div>
</code>```

I want to add margin property to the div with class "prev_div". I tried doing that with css as below,

```<code>.wrapper div.prev_div + div.next_div {
    position: relative;
    bottom: 70px;
 }
</code>```

But the above adds the margin to the div with class next_div instead i wanted the position style for the prev_div.

So i tried doing the same using the javascript by finding the element with prev_div and next_div. if next_div present adding a class "additional" to the prev_div. once class additional added and if the next_div not present remove the additional class for prev_div. but this doesnt work...there is a delay in removing the class added when next_div not present.

this next_div can be closed with close button. and i am doing the node calculations in render method. the next_div is removed there is no trigger to render...it is taking time to detect it...can i do it in componentdidupdate or so.

could someone help me fix this. thanks.
I think since i am

```<code>render = () => {
    const prev_div = document.querySelector('.wrapper div.prev_div');
    const next_div = document.querySelector('.wrapper div.prev_div + div.next_div');
    if (next_div) {
        prev_div.classList.add('additional');
    } else {
        if (prev_div && prev_div.classList.contains('additional')) {
            prev_div.classList.remove('additional');
        }
    }
}
</code>```

Also the above doesnt work cause the next_div in the dom is from child component. so even if i put these calculations for node and clases in componentdidupdate...closing the next_div is not recognised soon. there is a delay in it.

thanks.

答:
```<code>.wrapper .next_div {
    margin-left: 10px;
 }
</code>```

If this is a react project it wouldn't work. You're using class instead of className in your html.

Body:
i want to add a class to a div that has adjacent sibling selector.

What i am trying to do?
I have two divs which appear on top of each other. so was thinking to move one div (prev_div) slightly above div(next_div) so they are visible. when next_div is closed the prev_div should get back to its original position.

Below is the html code,

previous

next

I want to add margin property to the div with class "prev_div". I tried doing that with css as below,

.wrapper div.prev_div + div.next_div {
    position: relative;
    bottom: 70px;
 }

But the above adds the margin to the div with class next_div instead i wanted the position style for the prev_div.

So i tried doing the same using the javascript by finding the element with prev_div and next_div. if next_div present adding a class "additional" to the prev_div. once class additional added and if the next_div not present remove the additional class for prev_div. but this doesnt work...there is a delay in removing the class added when next_div not present.

this next_div can be closed with close button. and i am doing the node calculations in render method. the next_div is removed there is no trigger to render...it is taking time to detect it...can i do it in componentdidupdate or so.

could someone help me fix this. thanks.
I think since i am

render = () => {
    const prev_div = document.querySelector('.wrapper div.prev_div');
    const next_div = document.querySelector('.wrapper div.prev_div + div.next_div');
    if (next_div) {
        prev_div.classList.add('additional');
    } else {
        if (prev_div && prev_div.classList.contains('additional')) {
            prev_div.classList.remove('additional');
        }
    }
}

Also the above doesnt work cause the next_div in the dom is from child component. so even if i put these calculations for node and clases in componentdidupdate...closing the next_div is not recognised soon. there is a delay in it.

thanks.

Body:
.wrapper .next_div {
    margin-left: 10px;
 }

If this is a react project it wouldn't work. You're using class instead of className in your html.


问:
How to get first element in a list of tuples?
I have a list like below where the first element is the id and the other is a string:

```<code>[(1, u'abc'), (2, u'def')]
</code>```

I want to create a list of ids only from this list of tuples as below:

```<code>[1,2]
</code>```

I'll use this list in __in so it needs to be a list of integer values.

答:
you can unpack your tuples and get only the first element using a list comprehension:

```<code>l = [(1, u'abc'), (2, u'def')]
[f for f, *_ in l]
</code>```

output:

```<code>[1, 2]
</code>```

this will work no matter how many elements you have in a tuple:

```<code>l = [(1, u'abc'), (2, u'def', 2, 4, 5, 6, 7)]
[f for f, *_ in l]
</code>```

output:

```<code>[1, 2]
</code>```

Body:
I have a list like below where the first element is the id and the other is a string:

[(1, u'abc'), (2, u'def')]

I want to create a list of ids only from this list of tuples as below:

[1,2]

I'll use this list in __in so it needs to be a list of integer values.

Body:
you can unpack your tuples and get only the first element using a list comprehension:

l = [(1, u'abc'), (2, u'def')]
[f for f, *_ in l]

output:

[1, 2]

this will work no matter how many elements you have in a tuple:

l = [(1, u'abc'), (2, u'def', 2, 4, 5, 6, 7)]
[f for f, *_ in l]

output:

[1, 2]


问:
Detecting a Nullable Type via reflection
Surprisingly the following code fails the Assert:

```<code>int? wtf = 0;
Assert.IsType<Nullable<int>>(wtf);
</code>```

So just out curiosity, how can you determine if a given instance is a Nullable<> object or not?

答:
What namespace is Assert in?

The following returns true as you would expect:

```<code>int? wtf = 0;
if (typeof(Nullable<int>).IsInstanceOfType(wtf))
{
    // Do things
}
</code>```

Although its worth noting that typeof(Nullable<int>).IsInstanceOfType(42) also returns true - this is because this method accepts an object and so gets boxed as a Nullable<int>.

Body:
Surprisingly the following code fails the Assert:

int? wtf = 0;
Assert.IsType<Nullable<int>>(wtf);

So just out curiosity, how can you determine if a given instance is a Nullable<> object or not?

Body:
What namespace is Assert in?

The following returns true as you would expect:

int? wtf = 0;
if (typeof(Nullable<int>).IsInstanceOfType(wtf))
{
    // Do things
}

Although its worth noting that typeof(Nullable<int>).IsInstanceOfType(42) also returns true - this is because this method accepts an object and so gets boxed as a Nullable<int>.


问:
Getting NoSuchElementException while reading a variable
I'am trying to call a method called "cnpPacient".After running this i get a NoSuchElementException in the line where i read variable " cnp ".

```<code>static void cnpPacient() {
    Scanner x = new Scanner(System.in);
    System.out.println("INTRODUCETI CNP-ul PACIENTULUI :");
    int cnp = x.nextInt();
    x.close();
}
</code>```

How can i fix it ?

答:
Works fine for me when provide 2 as input and it printed the same.

```<code>public static void main(String[] args) {
     cnpPacient();
}

static void cnpPacient() {
    Scanner x = new Scanner(System.in);
    System.out.println("INTRODUCETI CNP-ul PACIENTULUI :");
    int cnp = x.nextInt();
    System.out.println(cnp);
    x.close();
}
</code>```

Output:

```<code>INTRODUCETI CNP-ul PACIENTULUI :
2
2
</code>```

Body:
I'am trying to call a method called "cnpPacient".After running this i get a NoSuchElementException in the line where i read variable " cnp ".

static void cnpPacient() {
    Scanner x = new Scanner(System.in);
    System.out.println("INTRODUCETI CNP-ul PACIENTULUI :");
    int cnp = x.nextInt();
    x.close();
}

How can i fix it ?

Body:
Works fine for me when provide 2 as input and it printed the same.

public static void main(String[] args) {
     cnpPacient();
}

static void cnpPacient() {
    Scanner x = new Scanner(System.in);
    System.out.println("INTRODUCETI CNP-ul PACIENTULUI :");
    int cnp = x.nextInt();
    System.out.println(cnp);
    x.close();
}

Output:

INTRODUCETI CNP-ul PACIENTULUI :
2
2


问:
How to refresh state when navigating back
I would like to be able to navigate to the previous page in my app but I don't want the page to keep it's previous state. How would I go about doing this?</p>

答:
Well you can manage the value you know ?
Imagine the value is 'bool' :

```<code>    onPressed: () async {
              var value = await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) {
                    return SecondPage();
                  },
                ),
              );
              // get the callback
              // handle error
              if (value) {
                try {
                  // reload your api call ?
                } catch (e) {
                  print('Errors');
                }
              }
            },
</code>```

You can also wrap your data inside a Refresh indicator by manually scroll from the top to refresh your data. In that case, you might refresh whenever you want your api call ...

Think that way, your page data need to be rebuild in some way to refresh the data. By just navigating back it will not. The screen need an order from somewhere.

Body:
Well you can manage the value you know ?
Imagine the value is 'bool' :

    onPressed: () async {
              var value = await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) {
                    return SecondPage();
                  },
                ),
              );
              // get the callback
              // handle error
              if (value) {
                try {
                  // reload your api call ?
                } catch (e) {
                  print('Errors');
                }
              }
            },

You can also wrap your data inside a Refresh indicator by manually scroll from the top to refresh your data. In that case, you might refresh whenever you want your api call ...

Think that way, your page data need to be rebuild in some way to refresh the data. By just navigating back it will not. The screen need an order from somewhere.


问:
Error count and $Error automatic variable not consistent
I'm trying to grasp the Write-Error and $Error automatic variable with the code sample below, which is supposed to generate a single error:

```<code>function Test-Error
{
    [CmdletBinding()]
    param()
    Write-Error -Message "Error message" -Category PermissionDenied -ErrorId SampleID
}

$Error.Clear()
$ErrorActionPreference = "Stop"

Test-Error
</code>```

According to documentation:

$Error Contains an array of error objects that represent the most
  recent errors. The most recent error is the first error object in the
  array $Error[0].

OK so let's take a look at error contents now:

```<code>$Error[0] | select -property *
</code>```

This will print out the error, (I'm not pasting it here because it's not relevant to the question)

So according to docs this the error, but it looks like docs are wrong:

```<code>$Error[1] | select -property *
</code>```

This will also print out something!

The question is how is that single error happens to be split into 2 pieces?

Isn't just $Error[0] supposed to contain last error as the docs say?

Obviously I did clear the variable so only single element is supposed to be in the array, not 2.

both elements seem to be pointing to single error, but what's the purpose of 2 array elements for single error?

and if the $Error variable happens to have 30 or so errors how do tell which 2 are relating to same error? because that means 60 elements for 30 errors!

答: The other error is due to $ErrorActionPreference = "Stop" - the error message that you did not post would have clarified it, the Message property is The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Error message. If you do not use that, you get only one element in $Error.

Body:
I'm trying to grasp the Write-Error and $Error automatic variable with the code sample below, which is supposed to generate a single error:

function Test-Error
{
    [CmdletBinding()]
    param()
    Write-Error -Message "Error message" -Category PermissionDenied -ErrorId SampleID
}

$Error.Clear()
$ErrorActionPreference = "Stop"

Test-Error

According to documentation:

$Error Contains an array of error objects that represent the most
  recent errors. The most recent error is the first error object in the
  array $Error[0].

OK so let's take a look at error contents now:

$Error[0] | select -property *

This will print out the error, (I'm not pasting it here because it's not relevant to the question)

So according to docs this the error, but it looks like docs are wrong:

$Error[1] | select -property *

This will also print out something!

The question is how is that single error happens to be split into 2 pieces?

Isn't just $Error[0] supposed to contain last error as the docs say?

Obviously I did clear the variable so only single element is supposed to be in the array, not 2.

both elements seem to be pointing to single error, but what's the purpose of 2 array elements for single error?

and if the $Error variable happens to have 30 or so errors how do tell which 2 are relating to same error? because that means 60 elements for 30 errors!


问:
python create a metaclass which auto __init__ for *args and **kwargs

Backround

When I create a python class and in the init method I just write:

```<code>self.name1 = name1
self.name2 = name2
....
</code>```

for all arguments.

Question

SO, how to elegently write a __init__ for different *args and **kwargs?

I want write a metaclass to automatically set attributes for *args and **kwargs:

```<code>#the metaclass to be used
class LazyInit():
     # code here

</code>```

And then when I create child classes of it, child classes will auto __init__ for their own *args and **kwargs.

```<code>class Hospital(metaclass = LazyInit):
  def __init__(self, *args,**kwargs): pass

class Basketball(metaclass = LazyInit):
  def __init__(self, *args, **kwargs): pass

a = 1
b = 2
c = 3
a_hospital = Hospital(a, b, kw1 =1, kw2 =2)
a_circle = Basketball(a, c, kw3 = 10, kw4 = 20)
</code>```

My attempt

I only know that we can use setattr to do it only for **kwargs:

```<code>class LazyInit():
    def __init__(self,**kwargs):
        for k,v in kwargs.items():
            setattr(self,k,v)
LazyInit(a=1).a
</code>```

1

However, this is not a meta class which can be used in child classes. I should write this code snippet in each of my child classes...

答:
First, make a decorator to do the binding.

```<code>from functools import wraps
from inspect import signature

def binds(f):
    @wraps(f)
    def __init__(self, *args, **kwargs):
        # Update self attributes with inspected binding of arg names to values.
        vars(self).update(signature(f).bind(None, *args, **kwargs).arguments)
        # `self` is also an arg, but we didn't really want to save this one.
        del self.self
    return __init__
</code>```

Here's how you could use it.

```<code>class Foo:
    @binds
    def __init__(self, foo, bar, *args, baz, **kwargs):
        pass
</code>```

And a demonstration:

```<code>>>> vars(Foo(1,2,3,4,baz=5,quux=10))
{'foo': 1, 'bar': 2, 'args': (3, 4), 'baz': 5, 'kwargs': {'quux': 10}}
</code>```

Now all that's left is to make a metaclass apply this decorator automatically.

```<code>class AutoInit(type):
    def __new__(cls, name, bases, namespace):
        namespace['__init__'] = store_args(namespace['__init__'])
        return type.__new__(cls, name, bases, namespace)
</code>```

AutoInit is a subclass of the default metaclass type. On construction it finds the init method and replaces it with the wrapped version. type handles the rest.

Now you can use it like any other metaclass:

```<code>class Bar(metaclass=AutoInit):
    def __init__(self, spam, eggs, *, bacon):
        pass
</code>```

Demonstration:

```<code>>>> vars(Bar(1,2,bacon=3))
{'spam': 1, 'eggs': 2, 'bacon': 3}
</code>```

And this behavior will be inherited as well.

```<code>class Baz(Bar):
    def __init__(self, spam, eggs, sausage, *, bacon):
        super().__init__(spam, eggs, bacon=bacon)
</code>```

Demonstration (note the 'sausage'):

```<code>>>> vars(Baz(1,2,3,bacon=4))
{'spam': 1, 'eggs': 2, 'sausage': 3, 'bacon': 4}
</code>```

Metaclasses are deep magic. Powerful, but obscure. You almost never need them (if you're not sure, assume that you don't). Code that uses metaclasses too much can become very hard to understand and maintain.

In this case, you should probably stop at the decorator. It does almost everything you want, without being so confusing. Explicit is better than implicit. Code is read more than it is written. Readability counts.

Body:
Backround

When I create a python class and in the init method I just write:

self.name1 = name1
self.name2 = name2
....

for all arguments.

Question

SO, how to elegently write a __init__ for different *args and **kwargs?

I want write a metaclass to automatically set attributes for *args and **kwargs:

#the metaclass to be used
class LazyInit():
     # code here

And then when I create child classes of it, child classes will auto __init__ for their own *args and **kwargs.

class Hospital(metaclass = LazyInit):
  def __init__(self, *args,**kwargs): pass

class Basketball(metaclass = LazyInit):
  def __init__(self, *args, **kwargs): pass

a = 1
b = 2
c = 3
a_hospital = Hospital(a, b, kw1 =1, kw2 =2)
a_circle = Basketball(a, c, kw3 = 10, kw4 = 20)

My attempt

I only know that we can use setattr to do it only for **kwargs:

class LazyInit():
    def __init__(self,**kwargs):
        for k,v in kwargs.items():
            setattr(self,k,v)
LazyInit(a=1).a

1

However, this is not a meta class which can be used in child classes. I should write this code snippet in each of my child classes...

Body:
First, make a decorator to do the binding.

from functools import wraps
from inspect import signature

def binds(f):
    @wraps(f)
    def __init__(self, *args, **kwargs):
        # Update self attributes with inspected binding of arg names to values.
        vars(self).update(signature(f).bind(None, *args, **kwargs).arguments)
        # `self` is also an arg, but we didn't really want to save this one.
        del self.self
    return __init__

Here's how you could use it.

class Foo:
    @binds
    def __init__(self, foo, bar, *args, baz, **kwargs):
        pass

And a demonstration:

>>> vars(Foo(1,2,3,4,baz=5,quux=10))
{'foo': 1, 'bar': 2, 'args': (3, 4), 'baz': 5, 'kwargs': {'quux': 10}}

Now all that's left is to make a metaclass apply this decorator automatically.

class AutoInit(type):
    def __new__(cls, name, bases, namespace):
        namespace['__init__'] = store_args(namespace['__init__'])
        return type.__new__(cls, name, bases, namespace)

AutoInit is a subclass of the default metaclass type. On construction it finds the init method and replaces it with the wrapped version. type handles the rest.

Now you can use it like any other metaclass:

class Bar(metaclass=AutoInit):
    def __init__(self, spam, eggs, *, bacon):
        pass

Demonstration:

>>> vars(Bar(1,2,bacon=3))
{'spam': 1, 'eggs': 2, 'bacon': 3}

And this behavior will be inherited as well.

class Baz(Bar):
    def __init__(self, spam, eggs, sausage, *, bacon):
        super().__init__(spam, eggs, bacon=bacon)

Demonstration (note the 'sausage'):

>>> vars(Baz(1,2,3,bacon=4))
{'spam': 1, 'eggs': 2, 'sausage': 3, 'bacon': 4}

Metaclasses are deep magic. Powerful, but obscure. You almost never need them (if you're not sure, assume that you don't). Code that uses metaclasses too much can become very hard to understand and maintain.

In this case, you should probably stop at the decorator. It does almost everything you want, without being so confusing. Explicit is better than implicit. Code is read more than it is written. Readability counts.


问:
Parsing field access flags in java
I have an assignment wherein I have to parse the field access flags of a java .class file.
The specification for a .class file can be found here: Class File Format (page 26 & 27 have the access flags and hex vals).

This is fine, I can do this no worries.
My issue is that there is a large number of combinations.

I know the public, private and protected are mutually exclusive, which reduces the combinations somewhat. Final and transient are also mutually exclusive. The rest however are not.

At the moment, I have a large switch statement to do the comparison. I read in the hex value of the access flag and then increment a counter, depending on if it is public, private or protected. This works fine, but it seems quite messy to just have every combination listed in a switch statement. i.e. public static, public final, public static final, etc.

I thought of doing modulo on the access flag and the appropriate hex value for public, private or protected, but public is 0x0001, so that won't work.

Does anyone else have any ideas as to how I could reduce the amount of cases in my switch statement?

答:
What is the problem? The specification says that it's a bit flag, that means that you should look at a value as a binary number, and that you can test if a specific value is set by doing a bitwise AND.

E.g

```<code>/*
ACC_VOLATILE = 0x0040 = 10000000
ACC_PUBLIC   = 0x0001 = 00000001
Public and volatile is= 10000001
*/

publicCount += flag & ACC_PUBLIC > 0 ? 1 : 0;
volatileCount += flag & ACC_VOLATILE > 0 ? 1 : 0;
</code>```

Title: Parsing field access flags in java

Body:
What is the problem? The specification says that it's a bit flag, that means that you should look at a value as a binary number, and that you can test if a specific value is set by doing a bitwise AND.

E.g

/*
ACC_VOLATILE = 0x0040 = 10000000
ACC_PUBLIC   = 0x0001 = 00000001
Public and volatile is= 10000001
*/

publicCount += flag & ACC_PUBLIC > 0 ? 1 : 0;
volatileCount += flag & ACC_VOLATILE > 0 ? 1 : 0;


问:
PHP: How to loop and skip over database tables without corresponding data in another table?
I'm relatively new to PHP and still learning, and I recognize that this is a rookie question, but I'd love and appreciate any help that you can provide.

I'm currently working on coding a website that uses PHP and MySQL to pull and organize data from both a "courses" and "categories" database table.  Each row in the "courses" table is associated with a particular course category through the column "category_id," which is linked to the relevant "id" column in the "categories" table.

So, for example, if category 3 in the "categories" table is "Music" and a particular course is on music, that course's "category_id" column value will be set to "3" in the "courses" table. (I hope that I explained all of that appropriately; my apologies if it's unclear).

I'd like to display all of the course category names that currently contain courses, and also display all of the course names within each of those categories underneath each category name.  So, for example:

Music: (1) Rock, (2) Jazz

Painting: (1) Watercolor, (2) Acrylic

Here is the code that I'm using to do this.  I'm using an MVC framework in which I've passed all of the data from both the "courses" and "categories" tables into this view as the associative arrays $categories and $courses.

```<code><?php foreach ($categories as $category) : ?>

    <h4><?php echo ($category['name']); ?></h4>

    <?php foreach ($courses as $course) {

        if ($course['category_id'] == $category['id']) : ?>
            <p><?php echo ($course['name']); ?></p>
        <?php endif;
    }

endforeach; ?>
</code>```

The problem that I'm running into is that I have category rows in my "categories" table for which I don't currently yet have any corresponding courses in the "courses" table.  As I build out the website, this will change, but for now and for organization sake I don't want to delete those rows from the "categories" table.

So now, given the above code, I'm outputting a list of categories and courses that looks like this:

Dance:

Sculpture:

Music: (1) Rock, (2) Jazz

Painting: (1) Watercolor, (2) Acrylic

So finally, my question: how would I go about looping through each of the categories, and only displaying the category name if there are corresponding courses associated with that category_id in the "courses" table? (In reference to the example above, to skip over and not display the "Dance" and "Sculpture" categories because there aren't yet any courses associated with those categories).

Again, my apologies if anything above is unclear, and I very much appreciate anyone's help!

Best,
Josh

答:
This isn't how I would do it my own code - But starting from what you already have, I would generate a nested array which maps category IDs to an array of corresponding courses:

```<code><?php
    $coursesByCategory = [];
    foreach ($courses as $course) {
        $coursesByCategory[$course['category_id']][] = $course;
    }
?>
</code>```

The array should look like:

```<code>[
    3 => ['Rock', 'Jazz'],
    4 => ['Watercolor', 'Acrylic']
]
</code>```

Where 3 is the ID of Music and 4 the ID of Painting.

Then change your template code to:

```<code><?php foreach ($categories as $category) : ?>
    <?php if (!empty($coursesByCategory[$category['id']])) : ?>

        <h4><?php echo $category['name']; ?></h4>

        <?php foreach ($coursesByCategory[$category['id']] as $course) : ?>
            <p><?php echo $course['name']; ?></p>
        <?php endforeach; ?>

    <?php endif; ?>
<?php endforeach; ?>
</code>```

Body:
I'm relatively new to PHP and still learning, and I recognize that this is a rookie question, but I'd love and appreciate any help that you can provide.

I'm currently working on coding a website that uses PHP and MySQL to pull and organize data from both a "courses" and "categories" database table.  Each row in the "courses" table is associated with a particular course category through the column "category_id," which is linked to the relevant "id" column in the "categories" table.

So, for example, if category 3 in the "categories" table is "Music" and a particular course is on music, that course's "category_id" column value will be set to "3" in the "courses" table. (I hope that I explained all of that appropriately; my apologies if it's unclear).

I'd like to display all of the course category names that currently contain courses, and also display all of the course names within each of those categories underneath each category name.  So, for example:

Music: (1) Rock, (2) Jazz

Painting: (1) Watercolor, (2) Acrylic

Here is the code that I'm using to do this.  I'm using an MVC framework in which I've passed all of the data from both the "courses" and "categories" tables into this view as the associative arrays $categories and $courses.

<?php foreach ($categories as $category) : ?>

<?php echo ($category['name']); ?>

    <?php foreach ($courses as $course) {

        if ($course['category_id'] == $category['id']) : ?>

<?php echo ($course['name']); ?>

        <?php endif;
    }

endforeach; ?>

The problem that I'm running into is that I have category rows in my "categories" table for which I don't currently yet have any corresponding courses in the "courses" table.  As I build out the website, this will change, but for now and for organization sake I don't want to delete those rows from the "categories" table.

So now, given the above code, I'm outputting a list of categories and courses that looks like this:

Dance:

Sculpture:

Music: (1) Rock, (2) Jazz

Painting: (1) Watercolor, (2) Acrylic

So finally, my question: how would I go about looping through each of the categories, and only displaying the category name if there are corresponding courses associated with that category_id in the "courses" table? (In reference to the example above, to skip over and not display the "Dance" and "Sculpture" categories because there aren't yet any courses associated with those categories).

Again, my apologies if anything above is unclear, and I very much appreciate anyone's help!

Best,
Josh

Body:
This isn't how I would do it my own code - But starting from what you already have, I would generate a nested array which maps category IDs to an array of corresponding courses:

<?php
    $coursesByCategory = [];
    foreach ($courses as $course) {
        $coursesByCategory[$course['category_id']][] = $course;
    }
?>

The array should look like:

[
    3 => ['Rock', 'Jazz'],
    4 => ['Watercolor', 'Acrylic']
]

Where 3 is the ID of Music and 4 the ID of Painting.

Then change your template code to:

<?php foreach ($categories as $category) : ?>
    <?php if (!empty($coursesByCategory[$category['id']])) : ?>

        <h4><?php echo $category['name']; ?></h4>

        <?php foreach ($coursesByCategory[$category['id']] as $course) : ?>
            <p><?php echo $course['name']; ?></p>
        <?php endforeach; ?>

    <?php endif; ?>
<?php endforeach; ?>


问:
Custom Java annotation that calls a REST API
I would like to create a Java annotation @Ping that sends a POST request to a REST API that I deployed in a Docker container.

So far, I created this annotation:

```<code>@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Ping {
    String endpoint();
}
</code>```

As you can see, I would like this annotation to be based on methods. This method will allow me to give a status (available or unavailable) to my other services.

I also would like to store this code as a Maven artifact on my own repo, where I will add a couple more annotations, so that I can use it on my other services.

I have seen a couple tutorials but couldn't figure out how to externalize this behavior, and I couldn't have this working in the first place anyway.

From what I understand, now I need a handler that contains the logic (i.e. that sends a POST request to my API), but I am not sure how to do that.
Any chance you can help me get started on this? Is an annotation a good idea to do something like this?

Thanks!

答:
To add to @Urvil Joshi's answer, considering I didn't want to have add a Spring dependency, I created a PingAspect.aj file with this content:

```<code>public aspect PingAspect {

    pointcut hasPingAnnotation(Ping ping): @annotation(ping);

    pointcut execute() : execution(* * (..));

    Object around(Ping ping) : execute() && hasPingAnnotation(ping) {
        System.out.println("Before method execution");
        String endpoint = ping.endpoint();
        System.out.println("Endpoint = " + endpoint);
        Object result = proceed(ping);
        System.out.println("After");
        return result;
    }
}
</code>```

Works perfectly well with the ajc compiler!
Hope it can help

Body:
I would like to create a Java annotation @Ping that sends a POST request to a REST API that I deployed in a Docker container.

So far, I created this annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Ping {
    String endpoint();
}

As you can see, I would like this annotation to be based on methods. This method will allow me to give a status (available or unavailable) to my other services.

I also would like to store this code as a Maven artifact on my own repo, where I will add a couple more annotations, so that I can use it on my other services.

I have seen a couple tutorials but couldn't figure out how to externalize this behavior, and I couldn't have this working in the first place anyway.

From what I understand, now I need a handler that contains the logic (i.e. that sends a POST request to my API), but I am not sure how to do that.
Any chance you can help me get started on this? Is an annotation a good idea to do something like this?

Thanks!

Body:
To add to @Urvil Joshi's answer, considering I didn't want to have add a Spring dependency, I created a PingAspect.aj file with this content:

public aspect PingAspect {

    pointcut hasPingAnnotation(Ping ping): @annotation(ping);

    pointcut execute() : execution(* * (..));

    Object around(Ping ping) : execute() && hasPingAnnotation(ping) {
        System.out.println("Before method execution");
        String endpoint = ping.endpoint();
        System.out.println("Endpoint = " + endpoint);
        Object result = proceed(ping);
        System.out.println("After");
        return result;
    }
}

Works perfectly well with the ajc compiler!
Hope it can help


问:
How can I calculate the colorspace Delta E in python using only OpenCV/numpy/scipy?
I am trying to calculate Delta E (see e.g. here) in order to measure the color/colour difference between two different images.

I am following the method at How to compute the Delta E between two images, but (partly in order to reduce dependencies on other libraries), I would like to calculate Delta E in python using only opencv (and/or numpy/scipy) and its dependencies.

How?

答:
I think it is pretty straightforward. Just compute the math from the Wikipedia reference. Here is a Python/OpenCV/Numpy only solution.

Input A:

Input B:

```<code>import cv2
import numpy as np

# read image_A and convert to float
image_A = cv2.imread('barn.jpg').astype("float32")

# read image_B as grayscale and convert to float
image_B = cv2.imread('barn_mod.jpg').astype("float32")

# convert image_A and image_B from BGR to LAB
image_A = cv2.cvtColor(image_A,cv2.COLOR_BGR2LAB)
image_B = cv2.cvtColor(image_B,cv2.COLOR_BGR2LAB)

# compute difference
diff = cv2.add(image_A,-image_B)

# separate into L,A,B channel diffs
diff_L = diff[:,:,0]
diff_A = diff[:,:,1]
diff_B = diff[:,:,2]

# compute delta_e as mean over every pixel using equation from
# https://en.wikipedia.org/wiki/Color_difference#CIELAB_ΔE*
delta_e = np.mean( np.sqrt(diff_L*diff_L + diff_A*diff_A + diff_B*diff_B) )

# print results
print (delta_e)
</code>```

delta_e:

```<code>0.29771116
</code>```

See also:

https://python-colormath.readthedocs.io/en/latest/delta_e.html

https://python-colormath.readthedocs.io/en/latest/_modules/colormath/color_diff.html

https://github.com/scikit-image/scikit-image/blob/master/skimage/color/delta_e.py

Body:
I think it is pretty straightforward. Just compute the math from the Wikipedia reference. Here is a Python/OpenCV/Numpy only solution.

Input A:

Input B:

import cv2
import numpy as np

# read image_A and convert to float
image_A = cv2.imread('barn.jpg').astype("float32")

# read image_B as grayscale and convert to float
image_B = cv2.imread('barn_mod.jpg').astype("float32")

# convert image_A and image_B from BGR to LAB
image_A = cv2.cvtColor(image_A,cv2.COLOR_BGR2LAB)
image_B = cv2.cvtColor(image_B,cv2.COLOR_BGR2LAB)

# compute difference
diff = cv2.add(image_A,-image_B)

# separate into L,A,B channel diffs
diff_L = diff[:,:,0]
diff_A = diff[:,:,1]
diff_B = diff[:,:,2]

# compute delta_e as mean over every pixel using equation from
# https://en.wikipedia.org/wiki/Color_difference#CIELAB_ΔE*
delta_e = np.mean( np.sqrt(diff_L*diff_L + diff_A*diff_A + diff_B*diff_B) )

# print results
print (delta_e)

delta_e:

0.29771116

See also:

https://python-colormath.readthedocs.io/en/latest/delta_e.html

https://python-colormath.readthedocs.io/en/latest/_modules/colormath/color_diff.html

https://github.com/scikit-image/scikit-image/blob/master/skimage/color/delta_e.py


问:
I am trying to use regular expression for extracting the Filename filed in Splunk,I have attached the same text
ID=6913&Filename=C%3A%5CUsers%5CTHanse04%5CAppData%5CRoaming%5CDocumentum%5CViewed%5C181019_ERS_321_102_500857.pdf&Download=65536&DownloadSize=79243 HTTP/1.1" 200 3 "-" "Java/1.8.0_192"

I need to extract and after extract i need Thanse04 from it
Filename=C%3A%5CUsers%5CTHanse04%5CAppData%5CRoaming%5CDocumentum%5CViewed%5C181019_ERS_321_102_500857.pdf

Body: Try Filename=%3A%5CUsers%5C(?<user>[^%]+).