Title: Cumsum on one column conditional on number of occurence of values from another column

Body:
The title really is just a very rough idea and very likely not a good match for the actual problem.

I have some stock data, which looks likes this:

"DateTime","Price","Volume","Group"
2020-05-01 13:30:01.354,174.003,750,2020-05-01
2020-05-01 13:30:01.454,174.003,750,2020-05-01
2020-05-01 13:30:01.612,174.592,750,2020-05-01
2020-05-01 13:30:01.663,174.812,750,2020-05-01
2020-05-01 13:30:01.775,174.742,750,2020-05-01
2020-05-01 13:30:02.090,174.742,2000.0001,2020-05-01
2020-05-01 13:30:02.139,174.742,750,2020-05-01
2020-05-01 13:30:02.190,174.743,2000.0001,2020-05-01
2020-05-01 13:30:02.308,174.612,2000.0001,2020-05-01
2020-05-01 13:30:02.428,174.612,750,2020-05-01
2020-05-01 13:30:02.554,174.522,2000.0001,2020-05-01
2020-05-01 13:30:02.656,174.552,750,2020-05-01
2020-05-01 13:30:02.705,174.522,2000.0001,2020-05-01
2020-05-01 13:30:02.913,174.645,750,2020-05-01
2020-05-01 13:30:02.963,175.002,750,2020-05-01
2020-05-01 13:30:03.013,175.002,2000.0001,2020-05-01
2020-05-01 13:30:03.125,175.002,750,2020-05-01
2020-05-01 13:30:03.312,174.803,750,2020-05-01
2020-05-01 13:30:03.362,175.002,2000.0001,2020-05-01
2020-05-01 13:30:03.876,174.772,750,2020-05-01
2020-05-01 13:30:03.927,174.802,2000.0001,2020-05-01
2020-05-01 13:30:04.052,174.802,2000.0001,2020-05-01
2020-05-01 13:30:04.154,174.692,750,2020-05-01
2020-05-01 13:30:04.203,174.802,750,2020-05-01
2020-05-01 13:30:04.255,174.803,2000.0001,2020-05-01
2020-05-01 13:30:04.304,174.803,2000.0001,2020-05-01
2020-05-01 13:30:04.404,174.802,750,2020-05-01
2020-05-01 13:30:04.455,175.003,2000.0001,2020-05-01
2020-05-01 13:30:04.521,174.803,750,2020-05-01
2020-05-01 13:30:04.649,174.802,750,2020-05-01
2020-05-01 13:30:04.771,174.803,2000.0001,2020-05-01
2020-05-01 13:30:04.822,174.803,2000.0001,2020-05-01
2020-05-01 13:30:04.899,174.702,750,2020-05-01
2020-05-01 13:30:04.950,174.802,750,2020-05-01
2020-05-01 13:30:06.498,174.722,750,2020-05-01
2020-05-01 13:30:07.794,174.723,750,2020-05-01
2020-05-01 13:30:07.843,175.003,2000.0001,2020-05-01
2020-05-01 13:30:08.095,175.002,750,2020-05-01
2020-05-01 13:30:08.466,175.002,750,2020-05-01
2020-05-01 13:30:08.567,175.002,750,2020-05-01
2020-05-01 13:30:08.743,174.982,2000.0001,2020-05-01
2020-05-01 13:30:09.123,175.002,750,2020-05-01
2020-05-01 13:30:09.381,174.982,750,2020-05-01
2020-05-01 13:30:09.893,175.002,750,2020-05-01
2020-05-01 13:30:09.942,174.882,750,2020-05-01
2020-05-01 13:30:09.993,174.962,750,2020-05-01
2020-05-01 13:30:11.404,175.002,2000.0001,2020-05-01
2020-05-01 13:30:11.716,174.963,750,2020-05-01
2020-05-01 13:30:11.932,174.963,750,2020-05-01
2020-05-01 13:30:11.983,175.002,750,2020-05-01
2020-05-01 13:30:12.038,174.962,750,2020-05-01
2020-05-01 13:30:12.414,174.963,2000.0001,2020-05-01
2020-05-01 13:30:12.533,174.863,750,2020-05-01
2020-05-01 13:30:12.585,174.962,2000.0001,2020-05-01
2020-05-01 13:30:13.763,175.002,750,2020-05-01
2020-05-01 13:30:14.473,174.962,750,2020-05-01
2020-05-01 13:30:16.157,174.962,750,2020-05-01
2020-05-01 13:30:16.207,175.002,2000.0001,2020-05-01
2020-05-01 13:30:16.268,175.002,750,2020-05-01
2020-05-01 13:30:18.455,175.002,750,2020-05-01
2020-05-01 13:30:18.506,175.322,750,2020-05-01
2020-05-01 13:30:19.289,175.322,750,2020-05-01
2020-05-01 13:30:19.340,175.342,750,2020-05-01
2020-05-01 13:30:19.953,175.343,750,2020-05-01
2020-05-01 13:30:20.761,175.362,2000.0001,2020-05-01
2020-05-01 13:30:21.588,175.363,750,2020-05-01
2020-05-01 13:30:21.638,175.382,750,2020-05-01
2020-05-01 13:30:22.387,175.383,750,2020-05-01
2020-05-01 13:30:22.486,175.442,750,2020-05-01
2020-05-01 13:30:22.580,175.382,750,2020-05-01
2020-05-01 13:30:23.595,175.442,750,2020-05-01
2020-05-01 13:30:23.645,175.383,750,2020-05-01
2020-05-01 13:30:23.762,175.442,750,2020-05-01
2020-05-01 13:30:24.085,175.382,750,2020-05-01
2020-05-01 13:30:24.134,175.273,2000.0001,2020-05-01
2020-05-01 13:30:24.608,175.272,750,2020-05-01
2020-05-01 13:30:24.658,175.272,750,2020-05-01
2020-05-01 13:30:25.019,175.272,750,2020-05-01
2020-05-01 13:30:25.070,175.332,750,2020-05-01
2020-05-01 13:30:25.238,175.283,750,2020-05-01
2020-05-01 13:30:25.289,175.282,2000.0001,2020-05-01
2020-05-01 13:30:25.749,175.273,750,2020-05-01
2020-05-01 13:30:25.799,175.273,2000.0001,2020-05-01
2020-05-01 13:30:25.863,175.273,750,2020-05-01
2020-05-01 13:30:25.914,175.333,2000.0001,2020-05-01
2020-05-01 13:30:26.073,175.283,750,2020-05-01
2020-05-01 13:30:26.124,175.282,2000.0001,2020-05-01
2020-05-01 13:30:26.187,175.203,750,2020-05-01
2020-05-01 13:30:26.237,175.182,2000.0001,2020-05-01
2020-05-01 13:30:26.710,175.282,2000.0001,2020-05-01
2020-05-01 13:30:27.511,175.282,2000.0001,2020-05-01
2020-05-01 13:30:27.763,175.332,2000.0001,2020-05-01
2020-05-01 13:30:28.187,175.233,750,2020-05-01
2020-05-01 13:30:28.236,175.232,750,2020-05-01
2020-05-01 13:30:28.302,175.232,750,2020-05-01
2020-05-01 13:30:28.353,175.232,2000.0001,2020-05-01
2020-05-01 13:30:28.457,175.152,750,2020-05-01
2020-05-01 13:30:28.507,175.152,750,2020-05-01
2020-05-01 13:30:28.601,175.153,2000.0001,2020-05-01
2020-05-01 13:30:28.894,175.093,750,2020-05-01
2020-05-01 13:30:28.945,175.092,750,2020-05-01
2020-05-01 13:30:29.049,175.093,2000.0001,2020-05-01

What I wanted to do was to calculate a cumsum for Volume based on the sequential frequencies of values in Price column. Following is an example r output of above csv as data.frame/data.table.

                  DateTime   Price Volume      Group
 1: 2020-05-01 13:30:01.354 174.003    750 2020-05-01
 2: 2020-05-01 13:30:01.454 174.003    750 2020-05-01
 3: 2020-05-01 13:30:01.612 174.592    750 2020-05-01
 4: 2020-05-01 13:30:01.663 174.812    750 2020-05-01
 5: 2020-05-01 13:30:01.775 174.742    750 2020-05-01
 6: 2020-05-01 13:30:02.090 174.742   2000 2020-05-01
 7: 2020-05-01 13:30:02.139 174.742    750 2020-05-01
 8: 2020-05-01 13:30:02.190 174.743   2000 2020-05-01
 9: 2020-05-01 13:30:02.308 174.612   2000 2020-05-01
10: 2020-05-01 13:30:02.428 174.612    750 2020-05-01
 8: 2020-05-01 13:30:02.554 174.522   2000 2020-05-01
 9: 2020-05-01 13:30:02.656 174.552   2000 2020-05-01
10: 2020-05-01 13:30:02.705 174.522    750 2020-05-01

To explain in more details, I'll take first 2 rows and sum up their corresponding volumes into one element of an output data object (preferably data.frame); the prices of row 3 and row 4 have a frequency of 1 (unique occurrence in the price series) therefore their volumes do not need to be summed up and would produce 2 rows in output data object. price for row 5,6,7 was the same 174.742, then again I'd sum up 3 volumes and produce 1 row in output data object. The same logic applies to the rest of the data.

I've been experimenting with dplyr but to no avail; the best I could get was the index groups for each price occurrence but the natural order could not be reserved.  I can't think of a way to even get close to the result I wanted (in a vectorised flavour I was trying to avoid plain looping and writing too much logic).

as suggested by @RonakShah I'll add this expected output example. Sorry I didn't add one earlier as I really wasn't sure what it would look like. But as I thought over once again, I think I would just need an output for the cumsum volume sequence, as a single column. I don't really need another column for indexing (although apparently any additional column would serve as very-nice-to-have).

Example output:

         Cumsum.Volume
    1:       1500  # aggregated from row 1,2 as they have same price
    2:       750   # no aggregation as row 3 has occurred only once
    3:       750   # same as above
    4:       3500  # aggregation from row 4,5,6 as they have the same price
    5:       2000  # row 7 no aggregation for unique price occurrence in sequence
    6:       2750  # row 8,9 maps to same price so add them up
    7:       2000  # row 10 needs no aggregation
    8:       2000  # row 11 needs no aggregation
    9:       750   # row 12 needs no aggregation

Here's a mapping between price and volume:

`174.003` appeared twice together, so we cumsum their volumes
`174.592` appeared by itself, so we keep its volume
`174.812` appeared by itself, so we keep its volume
`174.742` appeared 3 times consecutively, so we cumsum/aggregate their volumes
`174.743` appeared by itself, so we keep its volume
`174.612` appeared twice together, so we cumsum their volumes
`174.522` appeared once by itself, we keep its volume
`174.552` appeared by itself, we keep its volume
`174,522` appeared again by itself, we keep its volume

I hope above addition could give you guys a better idea; the order of the cumsum volume was in correspondence with the natural order of the price column, but I don't need to keep the price column.

Any tips for a right direction?

Body:
Group by the date part of DateTime and by Price

library(tidyverse)

data <- tibble(
          DateTime=ymd_hms(c("2020-05-01 13:30:01.354", "2020-05-01 13:30:01.454", "2020-05-01 13:30:01.612",
                                        "2020-05-01 13:30:01.663", "2020-05-01 13:30:01.775", "2020-05-01 13:30:02.090",
                                        "2020-05-01 13:30:02.139", "2020-05-01 13:30:02.190", "2020-05-01 13:30:02.308",
                                        "2020-05-01 13:30:02.428")),

          Price=c(174.003, 174.003, 174.592, 174.812, 174.742, 174.742, 174.742, 174.743, 174.612, 174.612),
          Volume=c(750, 750, 750, 750, 750, 2000, 750, 2000, 2000, 750))

groupedData <- data %>%
  mutate(Date=lubridate::as_date(DateTime)) %>%
  group_by(Date, Price) %>%
  summarise(Volume=sum(Volume)) %>%
  ungroup()

groupedData

Giving

# A tibble: 6 x 3
  Date       Price Volume
  <date>     <dbl>  <dbl>
1 2020-05-01  174.   1500
2 2020-05-01  175.    750
3 2020-05-01  175.   2750
4 2020-05-01  175.   3500
5 2020-05-01  175.   2000
6 2020-05-01  175.    750


来源: stackexchange

问:
multitple matplotlib-axes from gdal-rasters
I am a little stuck in plotting multiple rasters in one figure with matplotlib.
I have a list with the 6 paths to the rasters and I would make a figure with 3x2 subplots. I'm not really sure which of the matplotlib-approaches works best for this. Moreover I have the problem, that I don't know how to make one single colorbar/legend for all plots.

my somewhat messy code looks like this at the moment but doesn't feel really good...

```<code>fig, axs = plt.subplots(3, 2, figsize=(18, 10))
i = 0
j = 0

fig.suptitle("Multiple Images")

for c, img in enumerate(imgs):
    name = img.split(os.sep)[1]
    gdalobj = gdal.Open(img, gdal.GA_ReadOnly)
    img_array = gdalobj.GetRasterBand(2).ReadAsArray()
    if c < 2:
        axs[0,c].imshow(img_array, cmap="gray")
        axs[0,c].set_title(name)
    elif 2 <= c < 4:
        axs[1,i].imshow(img_array, cmap="gray")
        axs[1,i].set_title(name)
        i+=1
    else:
        axs[2,j].imshow(img_array, cmap="gray")
        axs[2,j].set_title(name)
        j+=1
</code>```

I really don't think that this is the best way, but it somehow works. However, I would like to generate one single colorbar and I don't know how to do it...

答:
You can reduce your messy code to the following by iterating over the flattened array of axis objects. As for the color bar, you can refer to the existing posts, for example this one</p>

```<code>for ax, img in zip(axs.flatten(), imgs):
    name = img.split(os.sep)[1]
    gdalobj = gdal.Open(img, gdal.GA_ReadOnly)
    img_array = gdalobj.GetRasterBand(2).ReadAsArray()
    ax.imshow(img_array, cmap="gray")
    ax.set_title(name)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am a little stuck in plotting multiple rasters in one figure with matplotlib.
I have a list with the 6 paths to the rasters and I would make a figure with 3x2 subplots. I'm not really sure which of the matplotlib-approaches works best for this. Moreover I have the problem, that I don't know how to make one single colorbar/legend for all plots.

my somewhat messy code looks like this at the moment but doesn't feel really good...

fig, axs = plt.subplots(3, 2, figsize=(18, 10))
i = 0
j = 0

fig.suptitle("Multiple Images")

for c, img in enumerate(imgs):
    name = img.split(os.sep)[1]
    gdalobj = gdal.Open(img, gdal.GA_ReadOnly)
    img_array = gdalobj.GetRasterBand(2).ReadAsArray()
    if c < 2:
        axs[0,c].imshow(img_array, cmap="gray")
        axs[0,c].set_title(name)
    elif 2 <= c < 4:
        axs[1,i].imshow(img_array, cmap="gray")
        axs[1,i].set_title(name)
        i+=1
    else:
        axs[2,j].imshow(img_array, cmap="gray")
        axs[2,j].set_title(name)
        j+=1

I really don't think that this is the best way, but it somehow works. However, I would like to generate one single colorbar and I don't know how to do it...

Body:
You can reduce your messy code to the following by iterating over the flattened array of axis objects. As for the color bar, you can refer to the existing posts, for example this one

for ax, img in zip(axs.flatten(), imgs):
    name = img.split(os.sep)[1]
    gdalobj = gdal.Open(img, gdal.GA_ReadOnly)
    img_array = gdalobj.GetRasterBand(2).ReadAsArray()
    ax.imshow(img_array, cmap="gray")
    ax.set_title(name)


问:
Parsing URL with port and without scheme
I am trying to parse a URL in Go and get host and scheme from the URL. But while parsing the URL with port and without scheme I am getting unexpected result.

```<code>u, err := url.ParseRequestURI("hello.com:81")
fmt.Println("host :",u.Host)
fmt.Println("scheme :",u.Scheme)

</code>```

I am getting unexpected result

```<code>host :
scheme: hello.com
</code>```

I wanted this instead

```<code>host : hello.com:80
scheme:
</code>```

答:
The format defined in the net.URL docs is one of the following:

[scheme:][//[userinfo@]host][/]path[?query][#fragment]

scheme:opaque[?query][#fragment]

The scheme: is optional, but the double slash is part of the host field. This means that a valid string for your input would be: //hello.com:81 which results in:

```<code>u, _ := url.Parse("//hello.com:81")
fmt.Println("host:", u.Host)
// Output: host: hello.com:81
</code>```

You'll need to turn your input into something valid. If you know that the string never includes the scheme, you can simply prepend //. If you only sometimes have a scheme specified, you can try to conditionally manipulate the input.

Body:
I am trying to parse a URL in Go and get host and scheme from the URL. But while parsing the URL with port and without scheme I am getting unexpected result.

u, err := url.ParseRequestURI("hello.com:81")
fmt.Println("host :",u.Host)
fmt.Println("scheme :",u.Scheme)

I am getting unexpected result

host :
scheme: hello.com

I wanted this instead

host : hello.com:80
scheme:

Body:
The format defined in the net.URL docs is one of the following:

[scheme:][//[userinfo@]host][/]path[?query][#fragment]

scheme:opaque[?query][#fragment]

The scheme: is optional, but the double slash is part of the host field. This means that a valid string for your input would be: //hello.com:81 which results in:

u, _ := url.Parse("//hello.com:81")
fmt.Println("host:", u.Host)
// Output: host: hello.com:81

You'll need to turn your input into something valid. If you know that the string never includes the scheme, you can simply prepend //. If you only sometimes have a scheme specified, you can try to conditionally manipulate the input.


问:
Issue with Reacts render method :Giving Parsing error
Im getting the following error Parsing error: Unexpected token, expected ",",for the below code

```<code>class ProductDetails extends React.Component{
constructor(){
    super();
    this.state = {timer:0};
}
start = () => {
    this.setState({timer:this.state.timer + 1});
}
componentDidMount(){
    setInterval(this.start,1000)
}
render(){
    var data = [{ _id:12345,
                pdtName:"Gaming Laptop",
                pdtPrice:35000,
                pdtDescription:"An excellent choice for great gaming experience",
                img:'images/Laptop.jpg',
                rating:5,
                isDiscontinued:false

            }];

    return(
            <h3>Timer: {this.state.timer} </h3>

             data.map(product =>{
                return <Product pimg={product.img} pid = {product._id} pname = {product.pdtName} pprice = {product.pdtPrice} pdesc = {product.pdtDescription}
                 prating = {product.rating} pisdiscon = {product.isDiscontinued} key={product._id}/>
            })

        )
}
</code>```

}

When I remove
Timer: {this.state.timer}
 from render() Im not getting the error.Simillarly if i remove data.map leaving  not getting error..But when using both getting the above error.How to fix it?

Thanks

答:
React component can return only one element. You can wrap return inside another element, e.g.
...
, or use React.Fragment
 which not adding extra nodes to the DOM.

```<code>return (
    <React.Fragment>
        <h3>Timer: {this.state.timer} </h3>
        {data.map(product => {
            return (
                <Product
                    pimg={product.img}
                    pid={product._id}
                    pname={product.pdtName}
                    pprice={product.pdtPrice}
                    pdesc={product.pdtDescription}
                    prating={product.rating}
                    pisdiscon={product.isDiscontinued}
                    key={product._id}
                />
            );
        })}
    </React.Fragment>
);
</code>```

Body:
Im getting the following error Parsing error: Unexpected token, expected ",",for the below code

class ProductDetails extends React.Component{
constructor(){
    super();
    this.state = {timer:0};
}
start = () => {
    this.setState({timer:this.state.timer + 1});
}
componentDidMount(){
    setInterval(this.start,1000)
}
render(){
    var data = [{ _id:12345,
                pdtName:"Gaming Laptop",
                pdtPrice:35000,
                pdtDescription:"An excellent choice for great gaming experience",
                img:'images/Laptop.jpg',
                rating:5,
                isDiscontinued:false

            }];

    return(

Timer: {this.state.timer}

             data.map(product =>{
                return <Product pimg={product.img} pid = {product._id} pname = {product.pdtName} pprice = {product.pdtPrice} pdesc = {product.pdtDescription}
                 prating = {product.rating} pisdiscon = {product.isDiscontinued} key={product._id}/>
            })

        )
}

}

When I remove
Timer: {this.state.timer}
 from render() Im not getting the error.Simillarly if i remove data.map leaving  not getting error..But when using both getting the above error.How to fix it?

Thanks

Body:
React component can return only one element. You can wrap return inside another element, e.g. <div>...</div>, or use React.Fragment
 which not adding extra nodes to the DOM.

return (
    <React.Fragment>
        <h3>Timer: {this.state.timer} </h3>
        {data.map(product => {
            return (
                <Product
                    pimg={product.img}
                    pid={product._id}
                    pname={product.pdtName}
                    pprice={product.pdtPrice}
                    pdesc={product.pdtDescription}
                    prating={product.rating}
                    pisdiscon={product.isDiscontinued}
                    key={product._id}
                />
            );
        })}
    </React.Fragment>
);


问:
Laravel 5.1 Route::controller with optional url params?
I have this code in routes

```<code>Route::controller('/orders/{from}/{to}', 'CartController');
</code>```

the link something like this

localhost/admin/orders/2020-01-01/2020-01-02

this will open all the records between 2 dates

But I have another link something like this

localhost/admin/orders/4212

to open specific row on a new tab

This 2 links falls for 1 function

called it

```<code> public function getIndex($from,$to){

 }
</code>```

can  I do this params optional? with 1 Route::controller('/orders/{from}/{to}', 'CartController'); in my route.php?

答:
Try this:</p>

```<code>Route::controller('/orders/{from?}/{to?}', 'CartController');
</code>```

```<code>public function getIndex($from = false,$to = false){

}

</code>```

Body:
I have this code in routes

Route::controller('/orders/{from}/{to}', 'CartController');

the link something like this

localhost/admin/orders/2020-01-01/2020-01-02

this will open all the records between 2 dates

But I have another link something like this

localhost/admin/orders/4212

to open specific row on a new tab

This 2 links falls for 1 function

called it

 public function getIndex($from,$to){

 }

can  I do this params optional? with 1 Route::controller('/orders/{from}/{to}', 'CartController'); in my route.php?

Body:
Try this:

Route::controller('/orders/{from?}/{to?}', 'CartController');

public function getIndex($from = false,$to = false){

}


问:
Cronjob Javascript, how to fire job limited times? ( set counter and max limit )
I'm new to Cronjob and looking for a way to fire it with interval but only 5 times.
Im firing an API call with cron and do not want to loop it.
Is it possible to set a counter and max limit of how many times cron has been executed?
or is there another better way of making delayed API calls with nodejs 5 times during 5 min ?</p>

答: please use https://www.npmjs.com/package/node-cron, using this will be much simpler and scalable</p>


问:
How to remove Blazor code block background color?
I am trying out blazor webassembly app and on Visual Studio 2019 Dark theme, code blocks are highlighted with dark gray color which makes it harder to read, is there a way to remove it without switching to lighter theme?

I tried to find "Razor" and "Blazor" Under Options > font & colors

答:
Oddly enough I had to google this yesterday, as I hated the lack of contrast!

It's set under Tools => Options menu, in Fonts and Colors:

I set my background to match the editor background (which is RGB 30,30,30) so the backgrounds match:


问:
Retrieve image orientation in PHP
How can I get the image orientation (landscape or portrait) of an image (JPEG or PNG) in PHP?

I created a php site where users can upload pictures. Before I scale them down to a smaller size, I want to know how the image is orientated in order to scale it properly.

Thanks for your answer!

答:
I am using this shorthand. Sharing just in case someone needs a one-line solution.

```<code>$orientation = ( $width != $height ? ( $width > $height ? 'landscape' : 'portrait' ) : 'square' );
</code>```

First it checks if image is not 1:1 (square). If it is not it determines the orientation (landscape / portrait).

I hope someone finds this helpful.

ContentLicense: CC BY-SA 3.0

Title: Retrieve image orientation in PHP

Body:
I am using this shorthand. Sharing just in case someone needs a one-line solution.

$orientation = ( $width != $height ? ( $width > $height ? 'landscape' : 'portrait' ) : 'square' );

First it checks if image is not 1:1 (square). If it is not it determines the orientation (landscape / portrait).

I hope someone finds this helpful.


问:
PayTM payment gateway integration with Angular Universal
Im trying to integrate Paytm payment gateway into my angular universal project.

Issue is, When I try to run payment gateway Url, I see Please wait! Do not refresh the page and instead of taking me the payment portal it is redirecting to callback url immediately

I add the /payment routes in server.ts

Below is the code,

```<code>  server.get('/payment', (req, res) => {
    let params = {}
    params['MID'] = 'xxx',
      params['WEBSITE'] = 'WEBSTAGING',
      params['CHANNEL_ID'] = 'WEB',
      params['INDUSTRY_TYPE_ID'] = 'Retail',
      params['ORDER_ID'] = 'ORD0001',
      params['CUST_ID'] = 'CUST0011',
      params['TXN_AMOUNT'] = '100',
      params['CALLBACK_URL'] = 'http://localhost:' + port + '/callback',
      params['EMAIL'] = 'xxx@gmail.com',
      params['MOBILE_NO'] = 'xxxx'

    checksum_lib.genchecksum(params, 'xxx', function (err, checksum) {
      let txn_url = "https://securegw-stage.paytm.in/order/process"

      let form_fields = ""
      for (let x in params) {
        form_fields += "<input type='hidden' name='" + x + "' value='" + params[x] + "'/>"

      }

      form_fields += "<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "' />"

      var html = '<html><body><center><h1>Please wait! Do not refresh the page</h1></center><form method="post" action="' + txn_url + '" name="f1">' + form_fields + '</form><script type="text/javascript">document.f1.submit()</script></body></html>'
      res.writeHead(200, { 'Content-Type': 'text/html' })
      res.write(html)
      res.end()
    })
  })
</code>```

答: It seems you are passing same order id in multiple requests. Orderid should be unique for every payment request.</p>

Body:
Im trying to integrate Paytm payment gateway into my angular universal project.

Issue is, When I try to run payment gateway Url, I see Please wait! Do not refresh the page and instead of taking me the payment portal it is redirecting to callback url immediately

I add the /payment routes in server.ts

Below is the code,

  server.get('/payment', (req, res) => {
    let params = {}
    params['MID'] = 'xxx',
      params['WEBSITE'] = 'WEBSTAGING',
      params['CHANNEL_ID'] = 'WEB',
      params['INDUSTRY_TYPE_ID'] = 'Retail',
      params['ORDER_ID'] = 'ORD0001',
      params['CUST_ID'] = 'CUST0011',
      params['TXN_AMOUNT'] = '100',
      params['CALLBACK_URL'] = 'http://localhost:' + port + '/callback',
      params['EMAIL'] = 'xxx@gmail.com',
      params['MOBILE_NO'] = 'xxxx'

    checksum_lib.genchecksum(params, 'xxx', function (err, checksum) {
      let txn_url = "https://securegw-stage.paytm.in/order/process"

      let form_fields = ""
      for (let x in params) {
        form_fields += "<input type='hidden' name='" + x + "' value='" + params[x] + "'/>"

      }

      form_fields += "<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "' />"

      var html = '
Please wait! Do not refresh the page
<form method="post" action="' + txn_url + '" name="f1">' + form_fields + '</form>'
      res.writeHead(200, { 'Content-Type': 'text/html' })
      res.write(html)
      res.end()
    })
  })


答:
You can use this like

```<code>Route::controller('/orders/{from}/{to?}', 'CartController');
</code>```

And in your controller

```<code>public function getIndex($from,$to=null){
    if($to==null){
        //to open specific row on a new tab
    }
    else{
        // Other task
    }

}
</code>```

Title: Laravel 5.1 Route::controller with optional url params?

Body:
You can use this like

Route::controller('/orders/{from}/{to?}', 'CartController');

And in your controller

public function getIndex($from,$to=null){
    if($to==null){
        //to open specific row on a new tab
    }
    else{
        // Other task
    }

}


问:
.click event doesn't seem to fire
I've got the following code inside of a

答: maybe you have more than one #toolbarReset, if this is the case it will not work until you remove other ids.</p>

Title: .click event doesn't seem to fire

Body: I've got the following code inside of a


问:
Comparing two arrays and put result in third array in php
Schedule

```<code>[
    {"Monday":"11:30"},
    {"Monday":"12:00"},
    {"Monday":"23:00"},
    {"Tuesday":"11:30"},
    {"Tuesday":"12:00"},
    {"Tuesday":"23:00"}
]
</code>```

Booked Slots

```<code>[
    {"Monday":"11:30"},
    {"Tuesday":"23:00"}
]
</code>```

The third Array should be of (available slots)

```<code>[
    {"Monday":"12:00"},
    {"Monday":"23:00"},
    {"Tuesday":"11:30"},
    {"Tuesday":"12:00"}
]
</code>```

How can I achieve this?

Body:
Schedule

[
    {"Monday":"11:30"},
    {"Monday":"12:00"},
    {"Monday":"23:00"},
    {"Tuesday":"11:30"},
    {"Tuesday":"12:00"},
    {"Tuesday":"23:00"}
]

Booked Slots

[
    {"Monday":"11:30"},
    {"Tuesday":"23:00"}
]

The third Array should be of (available slots)

[
    {"Monday":"12:00"},
    {"Monday":"23:00"},
    {"Tuesday":"11:30"},
    {"Tuesday":"12:00"}
]

How can I achieve this?

Body:
use array_diff

print_r(array_diff(['{"Monday":"11:30"}','{"Monday":"12:00"}','{"Monday":"23:00"}','{"Tuesday":"11:30"}','{"Tuesday":"12:00"}','{"Tuesday":"23:00"}'], ['{"Monday":"11:30"}','{"Tuesday":"23:00"}']));


答:
What you're after is an RGB image. You should create one from your img_14_10_2019 image and export it instead of img_14_10_2019.

Example code:

```<code>var imgRGB = img_14_10_2019.visualize({bands:['B3', 'B2', 'B1'], min:0, max:0.4, gamma:1.2})
Export.image.toDrive({
  image: imgRGB,
  description: 'img1_2019',
  scale: 30,
  maxPixels: 1e13
});
</code>```

The code just creates an RGB image imgRGB using the exact same parameters when you addLayer. Then just export it.

Regarding the bands you used to create RGB image, should it be B4, B3, and B2 for Landsat 8?

Title: Export each image of an image collection with visualisation parameters

Body:
I would like to export specific images as a geotiff to upload for analysis on QGIS (looking at change over time).

I want to be able to export each of the images in the l8_merge collection with true colour bands.

I've started with a single image from 2019.

// l8 collection

// L8 T1, 225:58
var l8_t1_225_58 = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")
        .filter(ee.Filter.eq('WRS_PATH', 225))
        .filter(ee.Filter.eq('WRS_ROW', 58))

        .select(['B4', 'B3', 'B2', ],['B3', 'B2','B1'])
        .filter(ee.Filter.inList('LANDSAT_PRODUCT_ID',ee.List(
          ['LC08_L1TP_225058_20130911_20170502_01_T1',
          'LC08_L1TP_225058_20140914_20170419_01_T1',
          'LC08_L1TP_225058_20150917_20170404_01_T1',
          'LC08_L1TP_225058_20170922_20171012_01_T1',
          'LC08_L1TP_225058_20181011_20181030_01_T1',
          'LC08_L1TP_225058_20191014_20191029_01_T1'
          ])));

// L8 T2, 225:58
var l8_t2_225_58 = ee.ImageCollection("LANDSAT/LC08/C01/T2_TOA")
        .filter(ee.Filter.eq('WRS_PATH', 225))
        .filter(ee.Filter.eq('WRS_ROW', 58))

        .select(['B4', 'B3', 'B2', ],['B3', 'B2','B1'])
        .filter(ee.Filter.inList('LANDSAT_PRODUCT_ID',ee.List(
          ['LC08_L1TP_225058_20130826_20170502_01_T2',
         'LC08_L1GT_225058_20130810_20170503_01_T2',
         'LC08_L1TP_225058_20140813_20170420_01_T2',
         'LC08_L1TP_225058_20140829_20170420_01_T2',
         'LC08_L1TP_225058_20151019_20170403_01_T2',
         'LC08_L1TP_225058_20150901_20170404_01_T2',
         'LC08_L1TP_225058_20161021_20170319_01_T2',
         'LC08_L1TP_225058_20161106_20170318_01_T2',
         'LC08_L1TP_225058_20160919_20180528_01_T2',
         'LC08_L1TP_225058_20171109_20171121_01_T2',
         'LC08_L1TP_225058_20171008_20171023_01_T2',
         'LC08_L1TP_225058_20180925_20180929_01_T2',
         'LC08_L1TP_225058_20181027_20181115_01_T2',
         'LC08_L1GT_225058_20191030_20191114_01_T2',
         'LC08_L1GT_225058_20190928_20191017_01_T2'
          ])));

// L8 T1, 225:59
var l8_t1_225_59 = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")
        .filter(ee.Filter.eq('WRS_PATH', 225))
        .filter(ee.Filter.eq('WRS_ROW', 59))

        .select(['B4', 'B3', 'B2', ],['B3', 'B2','B1'])
        .filter(ee.Filter.inList('LANDSAT_PRODUCT_ID',ee.List(
          ['LC08_L1TP_225059_20140813_20170420_01_T1',
          'LC08_L1TP_225059_20140829_20170420_01_T1',
          'LC08_L1TP_225059_20150901_20170404_01_T1',
          'LC08_L1TP_225059_20150917_20170404_01_T1',
          'LC08_L1TP_225059_20160818_20170322_01_T1',
          'LC08_L1TP_225059_20160903_20170321_01_T1',
          'LC08_L1TP_225059_20160919_20180528_01_T1',
          'LC08_L1TP_225059_20170821_20170911_01_T1',
          'LC08_L1TP_225059_20170922_20171012_01_T1',
          'LC08_L1TP_225059_20180925_20180929_01_T1',
          'LC08_L1TP_225059_20180824_20180829_01_T1',
          'LC08_L1TP_225059_20190912_20190917_01_T1',
          'LC08_L1TP_225059_20191014_20191029_01_T1'
          ])));

 // L8 T2, 225:59
var l8_t2_225_59 = ee.ImageCollection("LANDSAT/LC08/C01/T2_TOA")
        .filter(ee.Filter.eq('WRS_PATH', 225))
        .filter(ee.Filter.eq('WRS_ROW', 59))

        .select(['B4', 'B3', 'B2', ],['B3', 'B2','B1'])
        .filter(ee.Filter.inList('LANDSAT_PRODUCT_ID',ee.List(
          ['LC08_L1GT_225059_20130810_20170503_01_T2',
          'LC08_L1TP_225059_20131114_20170428_01_T2',
          'LC08_L1TP_225059_20131130_20170428_01_T2',
          'LC08_L1TP_225059_20150816_20170406_01_T2',
          'LC08_L1TP_225059_20170805_20170812_01_T2',
          'LC08_L1TP_225059_20181011_20181030_01_T2',
          'LC08_L1TP_225059_20190827_20190903_01_T2'
          ])));

// L8 T1, 226:57
var l8_t1_226_57 = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")
        .filter(ee.Filter.eq('WRS_PATH', 226))
        .filter(ee.Filter.eq('WRS_ROW', 57))

        .select(['B4', 'B3', 'B2', ],['B3', 'B2','B1'])
        .filter(ee.Filter.inList('LANDSAT_PRODUCT_ID',ee.List(
          ['LC08_L1TP_226057_20180916_20180928_01_T1',
          'LC08_L1TP_226057_20190903_20190916_01_T1'
          ])));

// L8 T2, 226:57
var l8_t2_226_57 = ee.ImageCollection("LANDSAT/LC08/C01/T2_TOA")
        .filter(ee.Filter.eq('WRS_PATH', 226))
        .filter(ee.Filter.eq('WRS_ROW', 57))

        .select(['B4', 'B3', 'B2', ],['B3', 'B2','B1'])
        .filter(ee.Filter.inList('LANDSAT_PRODUCT_ID',ee.List(
          ['LC08_L1GT_226057_20130801_20170503_01_T2',
          'LC08_L1TP_226057_20140804_20170420_01_T2',
          'LC08_L1GT_226057_20150807_20180528_01_T2',
          'LC08_L1GT_226057_20150823_20170405_01_T2',
          'LC08_L1GT_226057_20160910_20170321_01_T2',
          'LC08_L1GT_226057_20160809_20170322_01_T2',
          'LC08_L1GT_226057_20160825_20180528_01_T2',
          'LC08_L1GT_226057_20170812_20170824_01_T2',
          'LC08_L1GT_226057_20170828_20170914_01_T2',
          'LC08_L1GT_226057_20170913_20170928_01_T2',
          'LC08_L1GT_226057_20180831_20180912_01_T2',
          'LC08_L1GT_226057_20181002_20181010_01_T2',
          'LC08_L1TP_226057_20191005_20191018_01_T2',
          'LC08_L1GT_226057_20190919_20190926_01_T2',
          ])));

// L8 T2, 226:58
var l8_t2_226_58 = ee.ImageCollection("LANDSAT/LC08/C01/T2_TOA")
        .filter(ee.Filter.eq('WRS_PATH', 226))
        .filter(ee.Filter.eq('WRS_ROW', 58))

        .select(['B4', 'B3', 'B2', ],['B3', 'B2','B1'])
        .filter(ee.Filter.inList('LANDSAT_PRODUCT_ID',ee.List(
          ['LC08_L1TP_226058_20131020_20170429_01_T2',
            'LC08_L1GT_226058_20131105_20170428_01_T2',
            'LC08_L1TP_226058_20131121_20170428_01_T2',
            'LC08_L1TP_226058_20141108_20170417_01_T2',
            'LC08_L1TP_226058_20141124_20170417_01_T2',
            'LC08_L1TP_226058_20151127_20170401_01_T2',
            'LC08_L1TP_226058_20160809_20170322_01_T2',
            'LC08_L1TP_226058_20161129_20180528_01_T2',
            'LC08_L1GT_226058_20170812_20170824_01_T2',
            'LC08_L1TP_226058_20170828_20170914_01_T2',
            'LC08_L1GT_226058_20180815_20180828_01_T2',
            'LC08_L1TP_226058_20180831_20180912_01_T2',
            'LC08_L1TP_226058_20181002_20181010_01_T2',
            'LC08_L1TP_226058_20190818_20190902_01_T2',
            'LC08_L1GT_226058_20190919_20190926_01_T2',
            'LC08_L1TP_226058_20191005_20191018_01_T2'
          ])));

// Merge collection l8

var l8_merge = ee.ImageCollection(l8_t1_225_58.merge(l8_t2_225_58.merge(l8_t1_225_59.merge(l8_t2_225_59.merge(l8_t1_226_57.merge(l8_t2_226_57.merge(l8_t2_226_58 )))))));

Map.setCenter(-50.626565, 1.949439, 7);
Map.addLayer(l8_merge, {bands:['B3', 'B2', 'B1'], min:0, max:0.4, gamma:1.2}, 'l8');

//-------2019--------//

var img_2019 = ee.ImageCollection(l8_merge)
  .filterDate('2019-01-01', '2019-12-31');

Map.setCenter(-50.626565, 1.949439, 7);
Map.addLayer(img_2019, {bands:['B3', 'B2', 'B1'], min:0, max:0.4, gamma:1.2}, '2019');

// View ID list
var imageList = img_2019.toList(5000);
// print('imageList', imageList);
// Extract the ID of each image object.
var id_list = imageList.map(function(item) {
  return ee.Image(item).id();
});
print('img_2019 id', id_list);

// Get the number of images
var count = img_2019.size();
print('img_2019 Count:', count);

var listOfImages = img_2019.toList(img_2019.size());

print('list', listOfImages);

var img1 = ee.Image(listOfImages.get[0]);
var img2 = ee.Image(listOfImages.get[1]);
var img3 = ee.Image(listOfImages.get[2]);
var img4 = ee.Image(listOfImages.get[3]);
var img5 = ee.Image(listOfImages.get[4]);
var img6 = ee.Image(listOfImages.get[5]);
var img7 = ee.Image(listOfImages.get[6]);
var img8 = ee.Image(listOfImages.get[7]);
var img9 = ee.Image(listOfImages.get[8]);
var img10 = ee.Image(listOfImages.get[9]);
var img11 = ee.Image(listOfImages.get[10]);
var img12 = ee.Image(listOfImages.get[11]);

print('img1', img1);

var img_14_10_2019 = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_225058_20191014')
  .select(['B3', 'B2', 'B1']);

print('14_10_2019', img_14_10_2019);

Map.setCenter(-50.080, 2.893, 7);
Map.addLayer(img_14_10_2019, {bands:['B3', 'B2', 'B1'], min:0, max:0.4, gamma:1.2}, 'img_14_10_2019');

Export.image.toDrive({
  image: img_14_10_2019,
  description: 'img1_2019',
  scale: 30,
  maxPixels: 10000000000000
});

The images download as three seperate tifs, and I can't get them to show on QGIS. I would like to know if the code is correct, or if it needs to be adjusted in some way?

Body:
What you're after is an RGB image. You should create one from your img_14_10_2019 image and export it instead of img_14_10_2019.

Example code:

var imgRGB = img_14_10_2019.visualize({bands:['B3', 'B2', 'B1'], min:0, max:0.4, gamma:1.2})
Export.image.toDrive({
  image: imgRGB,
  description: 'img1_2019',
  scale: 30,
  maxPixels: 1e13
});

The code just creates an RGB image imgRGB using the exact same parameters when you addLayer. Then just export it.

Regarding the bands you used to create RGB image, should it be B4, B3, and B2 for Landsat 8?


问:
DataTable in Flutter, Sorting multiple columns?
This question is actually sort of simple, but: Is it possible to sort a DataTable on more than one column?
So that the user can decide if it should be sorted on for example Name or Year?

If possible how do you implement it?

答:
you can use onSort in every column like this</p>

```<code> DataColumn(
        label:  Text('name'),
        onSort: (columnIndex, sortAscending) {
          setState(() {
            if (columnIndex == _sortColumnIndex) {
              _sortAsc = _sortNameAsc = sortAscending;
            } else {
              _sortColumnIndex = columnIndex;
              _sortAsc = _sortNameAsc;
            }
            _persons.sort((a, b) => a.name.compareTo(b.name));
          });
        },
       ),
</code>```

Body:
you can use onSort in every column like this

 DataColumn(
        label:  Text('name'),
        onSort: (columnIndex, sortAscending) {
          setState(() {
            if (columnIndex == _sortColumnIndex) {
              _sortAsc = _sortNameAsc = sortAscending;
            } else {
              _sortColumnIndex = columnIndex;
              _sortAsc = _sortNameAsc;
            }
            _persons.sort((a, b) => a.name.compareTo(b.name));
          });
        },
       ),


问:
MongoDb find opeartion on nested array having multiiple json object in it
I'm having dataset in which json consists of array having multiple json in it.

The objects in the array have 4 keys, out of which 1 is missing in some of them.

I want to get the documents where all the objects in an array are missing the key.

e.g, From these following documents:

```<code>{"test":1,desc:[{"price":1,"abc":"def"},{"price":2,"ac":"def"}]}
{"test":1,desc:[{"price":1,"abc":"def"},{"ac":"def"}]}
{"test":1,desc:[{"abc":"def"},{"ac":"def"}]}
</code>```

I want to match only the last document.

Thanks in advance..

答:
You can just use $exists:

```<code>db.collection.find(
    {
        "desc.price": {$exists: false}
    }
)
</code>```

And if you want for other fields as well:

```<code>db.collection.find(
    {
        $or: [
            {
                "desc.price": {$exists: false}
            },
            {
                "desc.abc": {$exists: false}
            },
            {
                "desc.ac": {$exists: false}
            }
        ]
    }
)
</code>```

One thing to note is that an empty array, i.e desc = [] will always be matched by this query. if you want to ensure there's atleast one object use this query:

```<code>db.collection.find(
    {
       $and: [
           {
               "desc.price": {$exists: false}
           },
           {
               "desc.0": {$exists: true}
           }
       ]
    }
)
</code>```

Body:
I'm having dataset in which json consists of array having multiple json in it.

The objects in the array have 4 keys, out of which 1 is missing in some of them.

I want to get the documents where all the objects in an array are missing the key.

e.g, From these following documents:

{"test":1,desc:[{"price":1,"abc":"def"},{"price":2,"ac":"def"}]}
{"test":1,desc:[{"price":1,"abc":"def"},{"ac":"def"}]}
{"test":1,desc:[{"abc":"def"},{"ac":"def"}]}

I want to match only the last document.

Thanks in advance..

Body:
You can just use $exists:

db.collection.find(
    {
        "desc.price": {$exists: false}
    }
)

And if you want for other fields as well:

db.collection.find(
    {
        $or: [
            {
                "desc.price": {$exists: false}
            },
            {
                "desc.abc": {$exists: false}
            },
            {
                "desc.ac": {$exists: false}
            }
        ]
    }
)

One thing to note is that an empty array, i.e desc = [] will always be matched by this query. if you want to ensure there's atleast one object use this query:

db.collection.find(
    {
       $and: [
           {
               "desc.price": {$exists: false}
           },
           {
               "desc.0": {$exists: true}
           }
       ]
    }
)


问:
PHP Komodo getter/setter auto-generation
Does Komodo support getter/setter auto generation a la NetBeans or Eclipse? If so how do I use it? I can't seem to find it.</p>

答:
This is in no way perfect or finished, but here's a Komodo 6 compatible python macro script I wrote to auto-generate setters/getters for an entire PHP class.

```<code>    from xpcom import components
    import re

    viewSvc = components.classes["@activestate.com/koViewService;1"]\
        .getService(components.interfaces.koIViewService)
    view = viewSvc.currentView.queryInterface(components.interfaces.koIScintillaView)

    sm = view.scimoz
    sm.currentPos   # current position in the editor
    sm.text         # editor text
    sm.selText      # the selected text
    #sm.text = "Hello World!"

    output = u"\n"

    setterTemplate = """
        function set%s($value){
            $this->%s = $value;
        }
    """

    getterTemplate = """
        /**
        *@return string
        */
        function get%s(){
            return $this->%s;
        }
    """

    propertyTemplate = """
    %s

    %s
    """

    prefixSize = len(u"private $")

    def formalName(rawName):
        return u"%s" % "".join([part.title() for part in rawName.split("_")])

    #todo find a better way to split lines, what if its Mac or Windows format?
    for line in sm.text.split("\n"):
        if line.strip().startswith("private $"):
            #trim of the private $ and trailing semi-colon
            realName = line.strip()[prefixSize:-1]
            output += propertyTemplate % ( setterTemplate %(formalName(realName), realName), getterTemplate % (formalName(realName), realName))

    sm.insertText(sm.currentPos, output)
</code>```

give a file like foo.php with Class Bar as the only thing present

```<code>class Bar {
   private $id;
   private $name_first;
}
</code>```

It would inject

```<code>    function setId($value){
        $this->id = $value;
    }

    /**
    *@return string
    */
    function getId(){
        return $this->id;
    }

    function setNameFirst($value){
        $this->name_first = $value;
    }

    /**
    *@return string
    */
    function getNameFirst(){
        return $this->name_first;
    }
</code>```

That's good enough for my uses ( I can retab everything pretty quickly ) but I'll update this answer if I improve significantly on the script.

ContentLicense: CC BY-SA 2.5

Body:
This is in no way perfect or finished, but here's a Komodo 6 compatible python macro script I wrote to auto-generate setters/getters for an entire PHP class.

    from xpcom import components
    import re

    viewSvc = components.classes["@activestate.com/koViewService;1"]\
        .getService(components.interfaces.koIViewService)
    view = viewSvc.currentView.queryInterface(components.interfaces.koIScintillaView)

    sm = view.scimoz
    sm.currentPos   # current position in the editor
    sm.text         # editor text
    sm.selText      # the selected text
    #sm.text = "Hello World!"

    output = u"\n"

    setterTemplate = """
        function set%s($value){
            $this->%s = $value;
        }
    """

    getterTemplate = """
        /**
        *@return string
        */
        function get%s(){
            return $this->%s;
        }
    """

    propertyTemplate = """
    %s

    %s
    """

    prefixSize = len(u"private $")

    def formalName(rawName):
        return u"%s" % "".join([part.title() for part in rawName.split("_")])

    #todo find a better way to split lines, what if its Mac or Windows format?
    for line in sm.text.split("\n"):
        if line.strip().startswith("private $"):
            #trim of the private $ and trailing semi-colon
            realName = line.strip()[prefixSize:-1]
            output += propertyTemplate % ( setterTemplate %(formalName(realName), realName), getterTemplate % (formalName(realName), realName))

    sm.insertText(sm.currentPos, output)

give a file like foo.php with Class Bar as the only thing present

class Bar {
   private $id;
   private $name_first;
}

It would inject

    function setId($value){
        $this->id = $value;
    }

    /**
    *@return string
    */
    function getId(){
        return $this->id;
    }

    function setNameFirst($value){
        $this->name_first = $value;
    }

    /**
    *@return string
    */
    function getNameFirst(){
        return $this->name_first;
    }

That's good enough for my uses ( I can retab everything pretty quickly ) but I'll update this answer if I improve significantly on the script.


问:
Object of type decimal is not JSON serializable error in Django
I am following 'Django 2 by Example' book to create a ecommerce website in Django. But I am getting 'Object of type Decimal is not JSON serializable' when I am trying to save order id in the request.session in the following line.</p>

```<code>    request.session['order_id'] = order.id

    def order_create(request):
cart = Cart(request)
if request.method == 'POST':
    form = OrderCreateForm(request.POST)
    if form.is_valid():
        order = form.save()
        for item in cart:
            OrderItem.objects.create(
                order=order, product=item['product'], price=item['price'], quantity=item['quantity'])

        # cart.clear()
        order_created.delay(order.id)

        request.session['order_id'] = order.id

        return redirect(reverse('payment:process'))
else:
    form = OrderCreateForm()

return render(request, 'orders/order/create.html', {'cart': cart, 'form': form})
</code>```

答: I'm guessing that we followed along the same tutorial as your views look a lot like mine. If that's the case then the problem is likely to be in the cart.py file. Try to get rid of your decimal functions in it. This might not be the best solution but that's how I solved this issue.

Body:
I am following 'Django 2 by Example' book to create a ecommerce website in Django. But I am getting 'Object of type Decimal is not JSON serializable' when I am trying to save order id in the request.session in the following line.

    request.session['order_id'] = order.id

    def order_create(request):
cart = Cart(request)
if request.method == 'POST':
    form = OrderCreateForm(request.POST)
    if form.is_valid():
        order = form.save()
        for item in cart:
            OrderItem.objects.create(
                order=order, product=item['product'], price=item['price'], quantity=item['quantity'])

        # cart.clear()
        order_created.delay(order.id)

        request.session['order_id'] = order.id

        return redirect(reverse('payment:process'))
else:
    form = OrderCreateForm()

return render(request, 'orders/order/create.html', {'cart': cart, 'form': form})


问:
SpringDoc swagger documentation generation exception in nested complextype
We have a Person class. Person class has a property with type PersonDetail. And PersonDetail has a property with type Mail class.

When we start the application and navigate to swagger ui html page, Mail class is not generated in components section of openapi definition and we get "Could not resolve reference: Could not resolve pointer: /components/schemas/Mail does not exist in document" error on page. As we checked if there is a complex type in the third level that time springdoc can not resolve that type.
Person and PersonDetail works fine but Mail fails.

Person->PersonDetail->Mail

```<code>public class Person {
private String name;

private PersonDetail personDetail;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public PersonDetail getPersonDetail() {
    return personDetail;
}

public void setPersonDetail(PersonDetail personDetail) {
    this.personDetail = personDetail;
}
}

public class PersonDetail {
private String surname;

private List<Mail> mails;

public List<Mail> getMails() {
    return mails;
}

public void setMails(List<Mail> mails) {
    this.mails = mails;
}
}

public class Mail {
private String mailAddress;

public String getMailAddress() {
    return mailAddress;
}

public void setMailAddress(String mailAddress) {
    this.mailAddress = mailAddress;
}
}

@get(path = "/getPersonTest")
@operation(description = "Testttt")
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "successful operation",
content = @content(schema = @Schema(implementation = Person.class)))})
public ResponseEntity getPerson(@RequestParam String name){
Person person = new Person();
return ResponseEntity.status(HttpStatus.OK).body(person);
}
</code>```

答:
There is no issue.
It seems that you are not using the right configuration.

We already answered you here: https://github.com/springdoc/springdoc-openapi/issues/679

Body:
We have a Person class. Person class has a property with type PersonDetail. And PersonDetail has a property with type Mail class.

When we start the application and navigate to swagger ui html page, Mail class is not generated in components section of openapi definition and we get "Could not resolve reference: Could not resolve pointer: /components/schemas/Mail does not exist in document" error on page. As we checked if there is a complex type in the third level that time springdoc can not resolve that type.
Person and PersonDetail works fine but Mail fails.

Person->PersonDetail->Mail

public class Person {
private String name;

private PersonDetail personDetail;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public PersonDetail getPersonDetail() {
    return personDetail;
}

public void setPersonDetail(PersonDetail personDetail) {
    this.personDetail = personDetail;
}
}

public class PersonDetail {
private String surname;

private List<Mail> mails;

public List<Mail> getMails() {
    return mails;
}

public void setMails(List<Mail> mails) {
    this.mails = mails;
}
}

public class Mail {
private String mailAddress;

public String getMailAddress() {
    return mailAddress;
}

public void setMailAddress(String mailAddress) {
    this.mailAddress = mailAddress;
}
}

@get(path = "/getPersonTest")
@operation(description = "Testttt")
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "successful operation",
content = @content(schema = @Schema(implementation = Person.class)))})
public ResponseEntity getPerson(@RequestParam String name){
Person person = new Person();
return ResponseEntity.status(HttpStatus.OK).body(person);
}


问:
Is there a way to train a Tensorflow Keras' model manually without using the fit method or I'm freaking out?
I've just started to learn Tensorflow and Keras and I wondering if there is another option, more manually, to train the model without using fit method.

I want to do the optimisation pass manually: I want to update the parameters by myself using my own loss function and updating these parameters with the loss that I have compute.

Is there any way to do that or I'm freaking out?

I'm asking this because I want to understand more how Keras' model works and if there any way to train a network without using fit method, that looks like it does a lot of things.

答:
Have a look to this tutorial: Tensorflow - Custom training.
It is explained how to create your own loss function, your custom optimizer and how to define the training loop. You have full control of the training process.

I copy here the code that may interest you the most from the tutorial:

```<code># Custom loss
def loss(target_y, predicted_y):
  return tf.reduce_mean(tf.square(target_y - predicted_y))

# Define a training loop
def train(model, inputs, outputs, learning_rate):
  with tf.GradientTape() as t:
    current_loss = loss(outputs, model(inputs))
  dW, db = t.gradient(current_loss, [model.W, model.b])
  model.W.assign_sub(learning_rate * dW)
  model.b.assign_sub(learning_rate * db)

model = Model()

Ws, bs = [], []
epochs = range(10)
for epoch in epochs:
  Ws.append(model.W.numpy())
  bs.append(model.b.numpy())
  current_loss = loss(outputs, model(inputs))

  train(model, inputs, outputs, learning_rate=0.1)
  print('Epoch %2d: W=%1.2f b=%1.2f, loss=%2.5f' %
        (epoch, Ws[-1], bs[-1], current_loss))
</code>```

That tutorial uses a very simple linear model, but it is very useful to get the idea. However, if you are interested in something more complex, check this tutorial: Tensorflow - Custom training: walkthrough

```<code>#Create the model
model = tf.keras.Sequential([
  tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(4,)),  # input shape required
  tf.keras.layers.Dense(10, activation=tf.nn.relu),
  tf.keras.layers.Dense(3)
])

# You can define your own loss function here
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
def loss(model, x, y, training):
  # training=training is needed only if there are layers with different
  # behavior during training versus inference (e.g. Dropout).
  y_ = model(x, training=training)

  return loss_object(y_true=y, y_pred=y_)

# Create here your gradient and optimizor
def grad(model, inputs, targets):
  with tf.GradientTape() as tape:
    loss_value = loss(model, inputs, targets, training=True)
  return loss_value, tape.gradient(loss_value, model.trainable_variables)
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)

# Training loop
train_loss_results = []
train_accuracy_results = []

num_epochs = 201

for epoch in range(num_epochs):
  epoch_loss_avg = tf.keras.metrics.Mean()
  epoch_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()

  # Training loop - using batches of 32
  for x, y in train_dataset:
    # Optimize the model
    loss_value, grads = grad(model, x, y)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))

    # Track progress
    epoch_loss_avg.update_state(loss_value)  # Add current batch loss
    # Compare predicted label to actual label
    # training=True is needed only if there are layers with different
    # behavior during training versus inference (e.g. Dropout).
    epoch_accuracy.update_state(y, model(x, training=True))

  # End epoch
  train_loss_results.append(epoch_loss_avg.result())
  train_accuracy_results.append(epoch_accuracy.result())

  if epoch % 50 == 0:
    print("Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}".format(epoch,
                                                                epoch_loss_avg.result(),
                                                                epoch_accuracy.result()))
</code>```

Body:
Have a look to this tutorial: Tensorflow - Custom training.
It is explained how to create your own loss function, your custom optimizer and how to define the training loop. You have full control of the training process.

I copy here the code that may interest you the most from the tutorial:

# Custom loss
def loss(target_y, predicted_y):
  return tf.reduce_mean(tf.square(target_y - predicted_y))

# Define a training loop
def train(model, inputs, outputs, learning_rate):
  with tf.GradientTape() as t:
    current_loss = loss(outputs, model(inputs))
  dW, db = t.gradient(current_loss, [model.W, model.b])
  model.W.assign_sub(learning_rate * dW)
  model.b.assign_sub(learning_rate * db)

model = Model()

Ws, bs = [], []
epochs = range(10)
for epoch in epochs:
  Ws.append(model.W.numpy())
  bs.append(model.b.numpy())
  current_loss = loss(outputs, model(inputs))

  train(model, inputs, outputs, learning_rate=0.1)
  print('Epoch %2d: W=%1.2f b=%1.2f, loss=%2.5f' %
        (epoch, Ws[-1], bs[-1], current_loss))

That tutorial uses a very simple linear model, but it is very useful to get the idea. However, if you are interested in something more complex, check this tutorial: Tensorflow - Custom training: walkthrough

#Create the model
model = tf.keras.Sequential([
  tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(4,)),  # input shape required
  tf.keras.layers.Dense(10, activation=tf.nn.relu),
  tf.keras.layers.Dense(3)
])

# You can define your own loss function here
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
def loss(model, x, y, training):
  # training=training is needed only if there are layers with different
  # behavior during training versus inference (e.g. Dropout).
  y_ = model(x, training=training)

  return loss_object(y_true=y, y_pred=y_)

# Create here your gradient and optimizor
def grad(model, inputs, targets):
  with tf.GradientTape() as tape:
    loss_value = loss(model, inputs, targets, training=True)
  return loss_value, tape.gradient(loss_value, model.trainable_variables)
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)

# Training loop
train_loss_results = []
train_accuracy_results = []

num_epochs = 201

for epoch in range(num_epochs):
  epoch_loss_avg = tf.keras.metrics.Mean()
  epoch_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()

  # Training loop - using batches of 32
  for x, y in train_dataset:
    # Optimize the model
    loss_value, grads = grad(model, x, y)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))

    # Track progress
    epoch_loss_avg.update_state(loss_value)  # Add current batch loss
    # Compare predicted label to actual label
    # training=True is needed only if there are layers with different
    # behavior during training versus inference (e.g. Dropout).
    epoch_accuracy.update_state(y, model(x, training=True))

  # End epoch
  train_loss_results.append(epoch_loss_avg.result())
  train_accuracy_results.append(epoch_accuracy.result())

  if epoch % 50 == 0:
    print("Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}".format(epoch,
                                                                epoch_loss_avg.result(),
                                                                epoch_accuracy.result()))


问:
Is there a way to access attributes in the class of a property with said attribute?
In this scenario:

```<code>class MyClass
{
  [MyAttribute("flag")]
  public OtherClass Property {get; set;)

  // etc.
}
</code>```

Is there a way for code in OtherClass to access the "flag" without knowledge of MyClass?

答: Nope. Because OtherClass is totally independent and does not know where it is used. Well, in theory - yes. Load ALL classes, go through them, find all references, analyze for attribute via reflection. Depending on size and locality (in one assembly, in all assemblies) this may be slow or "oh damn, waht happened it is REALLLY slow", but yes, you can get access to all assemblies, all classes and use reflection on those.</p>

Body:
In this scenario:

class MyClass
{
  [MyAttribute("flag")]
  public OtherClass Property {get; set;)

  // etc.
}

Is there a way for code in OtherClass to access the "flag" without knowledge of MyClass?


问:
How do I style the "User login" text in Drupal 6?
I pointed to USER LOGIN word of the User Login block on the front page using Firebug. There is a blue square around the word (USER LOGIN) indicating that it is inside a file called HTML.js. Where is that file on the DRUPAL 6 structure. I want to change this word by changing this file and then I re upload it. Is this possible. I would appreciate any reply. </p>

答:
You can either go the whole way and modify the entire login form or you can modify the text specifically. The text you are probably looking for is in the user login block in [root]/modules/user.module (line 743):

```<code> $block['subject'] = t('User login');
</code>```

However, there are a few caveats:

If you're using a theme other than Garland, this text might not be the text you need to modify.

Modifying core is bad. If you have to upgrade (and you will), you'll have to reapply this change.

To do things the right way you would need to create a theme and style the login form. The easiest way would be to copy the Garland theme from [base]/themes to /sites/all/themes, change the .info file and modify it using the techniques in the links above.

Body:
You can either go the whole way and modify the entire login form or you can modify the text specifically. The text you are probably looking for is in the user login block in [root]/modules/user.module (line 743):

 $block['subject'] = t('User login');

However, there are a few caveats:

If you're using a theme other than Garland, this text might not be the text you need to modify.

Modifying core is bad. If you have to upgrade (and you will), you'll have to reapply this change.

To do things the right way you would need to create a theme and style the login form. The easiest way would be to copy the Garland theme from [base]/themes to /sites/all/themes, change the .info file and modify it using the techniques in the links above.


问:
Python function to return concatenated string from a list, where the length of the string is more than 2 characters
Newbie learning Python here, be nice!!

I have an assignment as part of my course to write simple programs, but there is one I am struggling with. For all elements in a list that have more than 2 characters, should be concatenated. The code itself is working, but it's returning the first string in the list as well as the other strings which are more than 2 characters. It's because of the way I have written the code I know, but I can't figure out a way to exclude the first string. Iteration should be utilised.

My code:

```<code>def concatenate(strings):
    start = strings[0]
    for string in strings:
        if len(string) > 2:
            start += string
    return start

print(concatenate(["a", "de", "fg", "hijk", "abc"]))
</code>```

It's correctly concatenating hijkabc, but it's also including the "a" at the beginning, so the result I'm actually getting is ahijkabc.

What do I need to do?

Thanks!

答:
This is a solution that you're looking for</p>

```<code>def concatenate(strings):
    return ''.join(filter(lambda x: len(x) >2, strings))
</code>```

Body:
Newbie learning Python here, be nice!!

I have an assignment as part of my course to write simple programs, but there is one I am struggling with. For all elements in a list that have more than 2 characters, should be concatenated. The code itself is working, but it's returning the first string in the list as well as the other strings which are more than 2 characters. It's because of the way I have written the code I know, but I can't figure out a way to exclude the first string. Iteration should be utilised.

My code:

def concatenate(strings):
    start = strings[0]
    for string in strings:
        if len(string) > 2:
            start += string
    return start

print(concatenate(["a", "de", "fg", "hijk", "abc"]))

It's correctly concatenating hijkabc, but it's also including the "a" at the beginning, so the result I'm actually getting is ahijkabc.

What do I need to do?

Thanks!

Body:
This is a solution that you're looking for

def concatenate(strings):
    return ''.join(filter(lambda x: len(x) >2, strings))


问:
How to read data from tensorflow 2 summary writer
I'm having trouble with reading data from a tensorflow summary writer.

I'm using the writer from the example on the tensorflow website: https://www.tensorflow.org/tensorboard/migrate

```<code>import tensorflow as tf
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator

writer = tf.summary.create_file_writer("/tmp/mylogs/eager")

# write to summary writer
with writer.as_default():
  for step in range(100):
    # other model code would go here
    tf.summary.scalar("my_metric", 0.5, step=step)
    writer.flush()

# read from summary writer
event_acc = EventAccumulator("/tmp/mylogs/eager")
event_acc.Reload()
event_acc.Tags()
</code>```

yields:

```<code> 'distributions': [],
 'graph': False,
 'histograms': [],
 'images': [],
 'meta_graph': False,
 'run_metadata': [],
 'scalars': [],
 'tensors': ['my_metric']}```

```

<p>If I try to grab the tensor data:</p>

```import pandas as pd
pd.DataFrame(event_acc.Tensors('my_metric'))
```

<p>I don't get the right values:</p>

```wall_time   step    tensor_proto
0   1.590743e+09    3   dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
1   1.590743e+09    20  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
2   1.590743e+09    24  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
3   1.590743e+09    32  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
...
```

How do I grab the actual summary data (which should be 0.5, for each of 100 steps)?

Here is a colab notebook with the code above: https://colab.research.google.com/drive/1RlgZrGD_vY-YcOBLF_sEPelmtVuygkqz?usp=sharing

答:
You need to convert the tensor values in the event accumulator, stored as TensorProto messages, into arrays, which you can do with tf.make_ndarray:

pd.DataFrame([(w, s, tf.make_ndarray(t)) for w, s, t in event_acc.Tensors('my_metric')],
             columns=['wall_time', 'step', 'tensor'])
```

Body:
I'm having trouble with reading data from a tensorflow summary writer.

I'm using the writer from the example on the tensorflow website: https://www.tensorflow.org/tensorboard/migrate

import tensorflow as tf
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator

writer = tf.summary.create_file_writer("/tmp/mylogs/eager")

# write to summary writer
with writer.as_default():
  for step in range(100):
    # other model code would go here
    tf.summary.scalar("my_metric", 0.5, step=step)
    writer.flush()

# read from summary writer
event_acc = EventAccumulator("/tmp/mylogs/eager")
event_acc.Reload()
event_acc.Tags()

yields:

 'distributions': [],
 'graph': False,
 'histograms': [],
 'images': [],
 'meta_graph': False,
 'run_metadata': [],
 'scalars': [],
 'tensors': ['my_metric']}```

If I try to grab the tensor data:

import pandas as pd
pd.DataFrame(event_acc.Tensors('my_metric'))

I don't get the right values:

wall_time   step    tensor_proto
0   1.590743e+09    3   dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
1   1.590743e+09    20  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
2   1.590743e+09    24  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
3   1.590743e+09    32  dtype: DT_FLOAT\ntensor_shape {\n}\ntensor_con...
...

How do I grab the actual summary data (which should be 0.5, for each of 100 steps)?

Here is a colab notebook with the code above: https://colab.research.google.com/drive/1RlgZrGD_vY-YcOBLF_sEPelmtVuygkqz?usp=sharing


问:
Training Computer Vision OCR
I setup the Azure Computer Vision Service and used in my app.  When I tried performing OCR on some images, it didn't recognize all the text (i.e. leaving out "S" in "cups").
Can it be trained/retrained in OCR when text isn't recognized correctly?</p>

答:
It is not always the case when OCR tools can detect everything. You can try preprocessing some images before sending them to the azure.
Preprocessig</p>

Title: Training Computer Vision OCR


问:
what does that mean? [Baseclass] [name] = new [Subclass]
I actually learn c# and i stuck at this theme:

what does this mean: [Baseclass] [name] = new [Subclass]

i only understand that i can use that as a parameter like

```<code>    public void DoSomething(Book _book)
    {
        if (_book is PokemonBook)
        {
            Console.WriteLine("It's a Pokemon-Book!");
        }
        else
        {
            Console.WriteLine("idk");
        }
    }
</code>```

but i dont understand this [Baseclass] [name] = new [Subclass], when do is use this and what does it do?

and yes, it's a stupid question

答:
You cannot do Subclass x = new BaseClass (even if you cast),
But can do BaseClass x = new SubClass

This is essentially treating an instance of subclass as baseclass.

Body:
I actually learn c# and i stuck at this theme:

what does this mean: [Baseclass] [name] = new [Subclass]

i only understand that i can use that as a parameter like

    public void DoSomething(Book _book)
    {
        if (_book is PokemonBook)
        {
            Console.WriteLine("It's a Pokemon-Book!");
        }
        else
        {
            Console.WriteLine("idk");
        }
    }

but i dont understand this [Baseclass] [name] = new [Subclass], when do is use this and what does it do?

and yes, it's a stupid question


问:
Add DropDown without refreshing page
Good Evening, </p>

<p>Could one of you suggest a way to add a dropdown box dynamically without refreshing the page? The dropdown box must not be visible at first, it must then become visible later based on a choice made by the user.  However one constraint is it can only be Javascript, Php, and/or html  </p>

答:
You can add display:none to your dropdown box style and add a link that have onclick=document.getElemetById('myDropDownBox').style.disply = 'block' to show the box.

BUUUT... it's best to Google it and learn more about this stuff. There is lots of cool stuff about this out there.

Title: Add DropDown without refreshing page

Body:
Good Evening,

Could one of you suggest a way to add a dropdown box dynamically without refreshing the page? The dropdown box must not be visible at first, it must then become visible later based on a choice made by the user.  However one constraint is it can only be Javascript, Php, and/or html


问:
Oneliner to create a dictionary from two lists in Python
I want to create this dictionary, but using one liner.

```<code>{'apple_last_6kg':'buy','mango_last_6kg':'buy','banana_last_6kg':'buy',
 'apple_last_4kg':'buy','mango_last_4kg':'buy','banana_last_4kg':'buy',
 'apple_last_3kg':'buy','mango_last_3kg':'buy','banana_last_3kg':'buy',
 'apple_last_kg':'buy','mango_last_kg':'buy','banana_last_kg':'buy'}
</code>```

This is what I initially tried and got the error, though {**{'a':1},**{'b':2}} works perfectly and gives {'a':1,'b':2}, but using this formulation in dictionary comprehension gives error.:

```<code>dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
print(dic2)
File "<ipython-input-238-9332e6a46412>", line 29
    dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
          ^
SyntaxError: dict unpacking cannot be used in dict comprehension
</code>```

I solved this like below, but I would like to have a one liner dictionay-comprehension like solution. Any suggestions?

```<code># This solution is unelegant, so I don't want to use this.
dic2 = [{i+'_last_'+j:'buy' for i in ['apple','mango','banana']} for j in ['kg','3kg','4kg','6kg']]

new_dic = {}
for d in dic2:
    new_dic.update(d)
print(new_dic)
{'apple_last_3kg': 'buy','apple_last_4kg': 'buy','apple_last_6kg': 'buy',
 'apple_last_kg': 'buy','banana_last_3kg': 'buy','banana_last_4kg': 'buy',
 'banana_last_6kg': 'buy','banana_last_kg': 'buy','mango_last_3kg': 'buy',
 'mango_last_4kg': 'buy','mango_last_6kg': 'buy','mango_last_kg': 'buy'}
</code>```

答:
This:

```<code>dic2 = [{i+'_last_'+j:'buy' for i in ['apple','mango','banana']} for j in ['kg','3kg','4kg','6kg']]
</code>```

can be reworked to produce desired dict following way:

```<code>newdic = {i+'_last_'+j:'buy' for i in ['apple','mango','banana'] for j in ['kg','3kg','4kg','6kg']}
print(newdic)
</code>```

Giving output:

```<code>{'apple_last_kg': 'buy', 'apple_last_3kg': 'buy', 'apple_last_4kg': 'buy', 'apple_last_6kg': 'buy', 'mango_last_kg': 'buy', 'mango_last_3kg': 'buy', 'mango_last_4kg': 'buy', 'mango_last_6kg': 'buy', 'banana_last_kg': 'buy', 'banana_last_3kg': 'buy', 'banana_last_4kg': 'buy', 'banana_last_6kg': 'buy'}
</code>```

Body:
I want to create this dictionary, but using one liner.

{'apple_last_6kg':'buy','mango_last_6kg':'buy','banana_last_6kg':'buy',
 'apple_last_4kg':'buy','mango_last_4kg':'buy','banana_last_4kg':'buy',
 'apple_last_3kg':'buy','mango_last_3kg':'buy','banana_last_3kg':'buy',
 'apple_last_kg':'buy','mango_last_kg':'buy','banana_last_kg':'buy'}

This is what I initially tried and got the error, though {**{'a':1},**{'b':2}} works perfectly and gives {'a':1,'b':2}, but using this formulation in dictionary comprehension gives error.:

dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
print(dic2)
File "<ipython-input-238-9332e6a46412>", line 29
    dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
          ^
SyntaxError: dict unpacking cannot be used in dict comprehension

I solved this like below, but I would like to have a one liner dictionay-comprehension like solution. Any suggestions?

# This solution is unelegant, so I don't want to use this.
dic2 = [{i+'_last_'+j:'buy' for i in ['apple','mango','banana']} for j in ['kg','3kg','4kg','6kg']]

new_dic = {}
for d in dic2:
    new_dic.update(d)
print(new_dic)
{'apple_last_3kg': 'buy','apple_last_4kg': 'buy','apple_last_6kg': 'buy',
 'apple_last_kg': 'buy','banana_last_3kg': 'buy','banana_last_4kg': 'buy',
 'banana_last_6kg': 'buy','banana_last_kg': 'buy','mango_last_3kg': 'buy',
 'mango_last_4kg': 'buy','mango_last_6kg': 'buy','mango_last_kg': 'buy'}

Body:
This:

dic2 = [{i+'_last_'+j:'buy' for i in ['apple','mango','banana']} for j in ['kg','3kg','4kg','6kg']]

can be reworked to produce desired dict following way:

newdic = {i+'_last_'+j:'buy' for i in ['apple','mango','banana'] for j in ['kg','3kg','4kg','6kg']}
print(newdic)

Giving output:

{'apple_last_kg': 'buy', 'apple_last_3kg': 'buy', 'apple_last_4kg': 'buy', 'apple_last_6kg': 'buy', 'mango_last_kg': 'buy', 'mango_last_3kg': 'buy', 'mango_last_4kg': 'buy', 'mango_last_6kg': 'buy', 'banana_last_kg': 'buy', 'banana_last_3kg': 'buy', 'banana_last_4kg': 'buy', 'banana_last_6kg': 'buy'}


问:
Type guard for Map in Typescript
consider Map like this in file CategoryMap.ts

```<code>export default new Map<number, SubCategory[]>([
   [11, [100, 101]],
   [12, [102, 103]],
   ...
])
</code>```

How to make type guard for that Map?

```<code>import categoryMap from 'CategoryMap'

type CategoryMapId = keyof typeof categoryMap

function isCategoryId(id: number): id is CategoryMapId {
   return categoryMap.has(id)
}
</code>```

This doesn't work because CategoryMapId is
"[Symbol.toStringTag]" | "clear" | "delete" | "forEach" | "get" | "has" | "set" | "size" | "[Symbol.iterator]" | "entries" | "keys" | ...

I expect that type CategoryMapId is 11 | 12 ...

Any solutions? Thanx.

答:
You can provide a type for the 'key' of the map like so:

const testMap = new Map<11 | 12, [number, number]>([
  [11, [100, 101]],
  [12, [102, 103]],
]);

const y = testMap.get(11); // works
const x = testMap.get(13); // type error
```

<p>However it seems that you want to have typescript infer this at runtime. Looking at this answer, it seems we can do something like:</p>

<pre class="lang-js prettyprint-override"><code>type KeyOfMap<M extends Map<unknown, unknown>> = M extends Map<infer K, unknown> ? K : never

const testMap = new Map<number, [number, number]>([
  [11, [100, 101]],
  [12, [102, 103]],
]);

type CategoryMapId = KeyOfMap<typeof testMap>;

const isCategoryId = (id: number): id is CategoryMapId =>
  testMap.has(id);
</code>```

But in that case, CategoryMapId still just has the type number, which isn't what we want.

Using an object instead of a Map, you have the option to get a proper type for the keys:

const testMap = {
  11: [100, 101],
  12: [102, 103],
}
type CategoryMapId = keyof typeof testMap;

const isCategoryId = (id: number): id is CategoryMapId =>
  Object.keys(testMap).map(Number).indexOf(id) > -1;

const x = isCategoryId(11); // true
const y = isCategoryId(13); // false

const getValue = (id: number) => {
  if (isCategoryId(id)) {
    return testMap[id];
  } else {
    return [];
  }
}
```

This may not fit your use case, but it seems impossible to do this with Maps currently

Title: Type guard for Map in Typescript

Body:
consider Map like this in file CategoryMap.ts

export default new Map<number, SubCategory[]>([
   [11, [100, 101]],
   [12, [102, 103]],
   ...
])

How to make type guard for that Map?

import categoryMap from 'CategoryMap'

type CategoryMapId = keyof typeof categoryMap

function isCategoryId(id: number): id is CategoryMapId {
   return categoryMap.has(id)
}

This doesn't work because CategoryMapId is
"[Symbol.toStringTag]" | "clear" | "delete" | "forEach" | "get" | "has" | "set" | "size" | "[Symbol.iterator]" | "entries" | "keys" | ...

I expect that type CategoryMapId is 11 | 12 ...

Any solutions? Thanx.

Body:
You can provide a type for the 'key' of the map like so:

const testMap = new Map<11 | 12, [number, number]>([
  [11, [100, 101]],
  [12, [102, 103]],
]);

const y = testMap.get(11); // works
const x = testMap.get(13); // type error

However it seems that you want to have typescript infer this at runtime. Looking at this answer, it seems we can do something like:

type KeyOfMap<M extends Map<unknown, unknown>> = M extends Map<infer K, unknown> ? K : never

const testMap = new Map<number, [number, number]>([
  [11, [100, 101]],
  [12, [102, 103]],
]);

type CategoryMapId = KeyOfMap<typeof testMap>;

const isCategoryId = (id: number): id is CategoryMapId =>
  testMap.has(id);

But in that case, CategoryMapId still just has the type number, which isn't what we want.

Using an object instead of a Map, you have the option to get a proper type for the keys:

const testMap = {
  11: [100, 101],
  12: [102, 103],
}
type CategoryMapId = keyof typeof testMap;

const isCategoryId = (id: number): id is CategoryMapId =>
  Object.keys(testMap).map(Number).indexOf(id) > -1;

const x = isCategoryId(11); // true
const y = isCategoryId(13); // false

const getValue = (id: number) => {
  if (isCategoryId(id)) {
    return testMap[id];
  } else {
    return [];
  }
}

This may not fit your use case, but it seems impossible to do this with Maps currently


问:
Branch Y from branch X - how to refresh only original branch X?
I have checked out a Git branch: git checkout branch_x. Than I made a branch from a branch: git checkout -b branch_y branch_x. I then work in new branch_y, make some changes, etc, than I want to pull changes that happened in original branch_x just to see what's going on. So while in branch_y I do:

git pull origin branch_x

But his fails with a message:

error: Your local changes to the following files would be overwritten by merge. Please commit your changes or stash them before you merge. Aborting.

I expected that git pull origin branch_x would have absolutely no effect on my own new branch_y.

Can I avoid this automatic merge and pull the changes only into branch_x?

答:
You can bring changes from origin/branch_x into branch_x without checkout using:

```<code>git fetch origin branch_x:branch_x
</code>```

as in this answer.

Body:
You can bring changes from origin/branch_x into branch_x without checkout using:

git fetch origin branch_x:branch_x

as in this answer.


问:
Process.Start(url) in a loop not launching every instance
I have a need to launch multiple browser instances / tabs in succession but using Process.Start(url) I am finding that not every URL is launched.

```<code>    for (int i = 0; i < n; i++)
    {
        var p = Process.Start("http://localhost/#" + i.ToString());
    }
</code>```

For any value n > 1 I find that only the last URL is opened in the browser (I'm testing with IE as the default browser). If I add a Thread.Sleep(1000) after Process.Start then I see a variety of behavior: sometimes all n are created; sometimes a subset.

The following does work as expected, but assumes IE (would rather use the default browser) and launches n browser instances rather than n tabs:

```<code>    for (int i = 0; i < n; i++)
    {
        var p = Process.Start("iexplore.exe", "http://localhost/#" + i.ToString());
    }
</code>```

I would prefer to get it working with the default browser behavior, but need it to be deterministic.

答: Seems to be a windows explorer bug. You could try to find to common browser executables and use them if present, if no match is found you can fall back to your default method.</p>

Body:
I have a need to launch multiple browser instances / tabs in succession but using Process.Start(url) I am finding that not every URL is launched.

    for (int i = 0; i < n; i++)
    {
        var p = Process.Start("http://localhost/#" + i.ToString());
    }

For any value n > 1 I find that only the last URL is opened in the browser (I'm testing with IE as the default browser). If I add a Thread.Sleep(1000) after Process.Start then I see a variety of behavior: sometimes all n are created; sometimes a subset.

The following does work as expected, but assumes IE (would rather use the default browser) and launches n browser instances rather than n tabs:

    for (int i = 0; i < n; i++)
    {
        var p = Process.Start("iexplore.exe", "http://localhost/#" + i.ToString());
    }

I would prefer to get it working with the default browser behavior, but need it to be deterministic.


问:
c# datatable groupby and sum column's values (without know the name)
I need to do a group by and sum the values for each columns. Actually I've been able to create a datatable as:

```<code>DataTable stats = dt.AsEnumerable().GroupBy(r => r["Data"]).OrderByDescending(r => r.Key).Select(g => g.OrderBy(r => r["Data"]).First()).CopyToDataTable();
</code>```

Basically I need also to sum each values for each columns in the original datatable (dt). Please consider that, apart a couple of columns, I might dunno how many they are and its name.
In a previous test I used:

```<code>var query = from stat in stats
            group stat by stat.Field<string>("Data") into data
            orderby data.Key
            select new
            {
                Data = data.Key,
                TotTWorked = data.Sum(stat => stat.Field<int>("Time_Work")),
                TotTHold = data.Sum(stat => stat.Field<int>("Time_Hold")),
                TotTAlarm = data.Sum(stat => stat.Field<int>("Time_Alarm")),
                Productivity = 0,
            };
</code>```

But now I need to be more flexible so I can't specify the column name as above. Any help?

答:
So assuming you have at least the list of column names, I'd go with the approach of creating a dictionary as part of the select and then transform it later to whatever form you need it. Here's an example:

```<code>var query = from stat in stats
                        group stat by stat.Field<string>("Data") into data
                        orderby data.Key
                        select new
                        {
                            Data = data.Key,
                            SumsDictionary = listOfColumnNames
                                             .Select(colName => new { ColName = colName, Sum = data.Sum(stat => stat.Field<int>(colName)) })
                                             .ToDictionary(d => d.ColName, d => d.Sum),
                            Productivity = 0,
                        };
</code>```

So that if you were to serialize the result object it would look something like this:

```<code>{
  "Data": {},
  "SumsDictionary": {
    "Time_Work": 10,
    "Time_Hold": 20,
    "Time_Alarm": 30
  },
  "Productivity": 0
}
</code>```

Hope it helps!

Body:
I need to do a group by and sum the values for each columns. Actually I've been able to create a datatable as:

DataTable stats = dt.AsEnumerable().GroupBy(r => r["Data"]).OrderByDescending(r => r.Key).Select(g => g.OrderBy(r => r["Data"]).First()).CopyToDataTable();

Basically I need also to sum each values for each columns in the original datatable (dt). Please consider that, apart a couple of columns, I might dunno how many they are and its name.
In a previous test I used:

var query = from stat in stats
            group stat by stat.Field<string>("Data") into data
            orderby data.Key
            select new
            {
                Data = data.Key,
                TotTWorked = data.Sum(stat => stat.Field<int>("Time_Work")),
                TotTHold = data.Sum(stat => stat.Field<int>("Time_Hold")),
                TotTAlarm = data.Sum(stat => stat.Field<int>("Time_Alarm")),
                Productivity = 0,
            };

But now I need to be more flexible so I can't specify the column name as above. Any help?

Body:
So assuming you have at least the list of column names, I'd go with the approach of creating a dictionary as part of the select and then transform it later to whatever form you need it. Here's an example:

var query = from stat in stats
                        group stat by stat.Field<string>("Data") into data
                        orderby data.Key
                        select new
                        {
                            Data = data.Key,
                            SumsDictionary = listOfColumnNames
                                             .Select(colName => new { ColName = colName, Sum = data.Sum(stat => stat.Field<int>(colName)) })
                                             .ToDictionary(d => d.ColName, d => d.Sum),
                            Productivity = 0,
                        };

So that if you were to serialize the result object it would look something like this:

{
  "Data": {},
  "SumsDictionary": {
    "Time_Work": 10,
    "Time_Hold": 20,
    "Time_Alarm": 30
  },
  "Productivity": 0
}

Hope it helps!


问:
How to use Promise.all() with Typescript
Here is what I want to do:

```<code>Promise.all([aurelia.start(), entityManagerProvider.initialize()])
    .then((results:Array<any>) => {
        let aurelia: any = results[0];
        aurelia.setRoot();
    });
</code>```

aurelia.start() returns an Aurelia type, while initialize() returns void.

The compiler gives an error message that the type cannot be inferred from the usage.

What I am trying to achieve is to get them to run at the same time, as they are both very long processes, then run Aurelia.setRoot();

答:
I somehow landed here when I was looking for return type of Promise.all() since straightforward [Promise<any>, Promise<any>] is obviously not working.

Eventually it turned out to be simplier than it seems:

```<code>const severalMongoDbOperations: Promise<[DeleteWriteOpResultObject, UpdateWriteOpResult]> =
  () => Promise.all([
    mongo.deleteOne({ ... }),
    mongo.updateOne({ ... })
  ]);
</code>```

Later it can be used with .then() or:

```<code>try {
  const ops: [DeleteWriteOpResultObject, UpdateWriteOpResult] = await severalMongoDbOperations();
} catch (e) {
  // Process rejection
}
</code>```

Body:
Here is what I want to do:

Promise.all([aurelia.start(), entityManagerProvider.initialize()])
    .then((results:Array<any>) => {
        let aurelia: any = results[0];
        aurelia.setRoot();
    });

aurelia.start() returns an Aurelia type, while initialize() returns void.

The compiler gives an error message that the type cannot be inferred from the usage.

What I am trying to achieve is to get them to run at the same time, as they are both very long processes, then run Aurelia.setRoot();

Body:
I somehow landed here when I was looking for return type of Promise.all() since straightforward [Promise<any>, Promise<any>] is obviously not working.

Eventually it turned out to be simplier than it seems:

const severalMongoDbOperations: Promise<[DeleteWriteOpResultObject, UpdateWriteOpResult]> =
  () => Promise.all([
    mongo.deleteOne({ ... }),
    mongo.updateOne({ ... })
  ]);

Later it can be used with .then() or:

try {
  const ops: [DeleteWriteOpResultObject, UpdateWriteOpResult] = await severalMongoDbOperations();
} catch (e) {
  // Process rejection
}


问:
Where is Location of Microsoft Edge Extension Folder that are installed from Microsoft Store?
Where is the location of Microsoft Edge extensions folder when they are installed from Microsoft Store, in Windows 10?</p>

答:
location is

```<code>C:\Users\%username%\AppData\Local\Microsoft\Edge\User Data\Default\Extensions
</code>```

Dir name is extension's id, you can find it at extension detail page's url.

Body:
location is

C:\Users\%username%\AppData\Local\Microsoft\Edge\User Data\Default\Extensions

Dir name is extension's id, you can find it at extension detail page's url.


问:
How to add a new column in the middle of the dataframe with values based on the previous column?
So, I am really new to python and pandas.
I have a dataframe which looks like the following:

So, after the Creation Date-Time column I want to add three more columns "Creation Time of Day", "Creation Day of Week", "Creation Month" which are based on the date and time values in the "Creation Date-Time" column.

For example, "Creation Time of Day" would contain values like "Morning", "Evening", etc, based on the time. "Creation Day of Week" would contain values like "Monday", "Tuesday", etc. and "Creation Month" would contain values like "January", "February", etc. How do I do this?

答:
Use:

```<code>df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'Creation Date-Time':pd.date_range('2015-01-02 15:07:01',periods=6,freq='231H')
                                 .strftime('%Y-%m-%dT%H:%M:%S'),
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})
print (df)
   A  B   Creation Date-Time  D  E  F
0  a  4  2015-01-02T15:07:01  1  5  a
1  b  5  2015-01-12T06:07:01  3  3  a
2  c  4  2015-01-21T21:07:01  5  6  a
3  d  5  2015-01-31T12:07:01  7  9  b
4  e  5  2015-02-10T03:07:01  1  2  b
5  f  4  2015-02-19T18:07:01  0  4  b
</code>```

First use to_datetime for datetimes, then get position of Creation Date-Time column by Index.get_loc, what is used for specify positions of new columns created by DataFrame.insert. For categoricals use cut, for names of days and months is used Series.dt.day_name and Series.dt.month_name:

```<code>df['Creation Date-Time'] = pd.to_datetime(df['Creation Date-Time'])

idx = df.columns.get_loc('Creation Date-Time')

#https://stackoverflow.com/a/55571425/2901002
b = [0,4,8,12,16,20,24]
l = ['Late Night', 'Early Morning','Morning','Noon','Eve','Night']
s = pd.cut(df['Creation Date-Time'].dt.hour, bins=b, labels=l)

df.insert(idx + 1, 'Creation Time of Day', s)
df.insert(idx + 2, 'Creation Time of Week', df['Creation Date-Time'].dt.day_name())
df.insert(idx + 3, 'Creation Month', df['Creation Date-Time'].dt.month_name())
print (df)

   A  B  Creation Date-Time Creation Time of Day Creation Time of Week  \
0  a  4 2015-01-02 15:07:01                 Noon                Friday
1  b  5 2015-01-12 06:07:01        Early Morning                Monday
2  c  4 2015-01-21 21:07:01                Night             Wednesday
3  d  5 2015-01-31 12:07:01              Morning              Saturday
4  e  5 2015-02-10 03:07:01           Late Night               Tuesday
5  f  4 2015-02-19 18:07:01                  Eve              Thursday

  Creation Month  D  E  F
0        January  1  5  a
1        January  3  3  a
2        January  5  6  a
3        January  7  9  b
4       February  1  2  b
5       February  0  4  b
</code>```

Body:
Use:

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'Creation Date-Time':pd.date_range('2015-01-02 15:07:01',periods=6,freq='231H')
                                 .strftime('%Y-%m-%dT%H:%M:%S'),
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})
print (df)
   A  B   Creation Date-Time  D  E  F
0  a  4  2015-01-02T15:07:01  1  5  a
1  b  5  2015-01-12T06:07:01  3  3  a
2  c  4  2015-01-21T21:07:01  5  6  a
3  d  5  2015-01-31T12:07:01  7  9  b
4  e  5  2015-02-10T03:07:01  1  2  b
5  f  4  2015-02-19T18:07:01  0  4  b

First use to_datetime for datetimes, then get position of Creation Date-Time column by Index.get_loc, what is used for specify positions of new columns created by DataFrame.insert. For categoricals use cut, for names of days and months is used Series.dt.day_name and Series.dt.month_name:

df['Creation Date-Time'] = pd.to_datetime(df['Creation Date-Time'])

idx = df.columns.get_loc('Creation Date-Time')

#https://stackoverflow.com/a/55571425/2901002
b = [0,4,8,12,16,20,24]
l = ['Late Night', 'Early Morning','Morning','Noon','Eve','Night']
s = pd.cut(df['Creation Date-Time'].dt.hour, bins=b, labels=l)

df.insert(idx + 1, 'Creation Time of Day', s)
df.insert(idx + 2, 'Creation Time of Week', df['Creation Date-Time'].dt.day_name())
df.insert(idx + 3, 'Creation Month', df['Creation Date-Time'].dt.month_name())
print (df)

   A  B  Creation Date-Time Creation Time of Day Creation Time of Week  \
0  a  4 2015-01-02 15:07:01                 Noon                Friday
1  b  5 2015-01-12 06:07:01        Early Morning                Monday
2  c  4 2015-01-21 21:07:01                Night             Wednesday
3  d  5 2015-01-31 12:07:01              Morning              Saturday
4  e  5 2015-02-10 03:07:01           Late Night               Tuesday
5  f  4 2015-02-19 18:07:01                  Eve              Thursday

  Creation Month  D  E  F
0        January  1  5  a
1        January  3  3  a
2        January  5  6  a
3        January  7  9  b
4       February  1  2  b
5       February  0  4  b


问:
What is the correct way to do an async action using redux observable and firebase?
so I have this epic

```<code>export const listenToCountryVisitsEpic = (action$, store) => {
    return action$.pipe(
        ofType('UPDATE_TRIP_DETAILS'),
        mergeMap((action) => {
            const userId = store.value.user.id
            const { country, newDetails } = action
            const { people, places } = details
            const scheme = {
                people,
                places,
            }

            firebase.database().ref(`users/${userId}/path`).update(scheme)

            return mergeMap((response) => {
                const payload = { ...JSON.parse(response.request.body), currentDetails: action.currentDetails }
                return [updatedCountrySuccess(payload)]
            })
        }),
    )
}
</code>```

what I want to do is make the request to firebase and then if successful update redux which in turn will update react. if not successful then catch it

this is correctly posting to firebase but I need to catch errors correctly. I don't want to fire this: updatedCountrySuccess until I know it's a success or failure in firebase

can I use async/await for this?

答:
You can use from() to turn Promise into Observable and then catchError to replace the error with whatever you want.

```<code>import { from } from 'rxjs';
import { catchError } from 'rxjs/operators';

...

return action$.pipe(
    ofType('UPDATE_TRIP_DETAILS'),
    mergeMap((action) => {
        const userId = store.value.user.id
        const { country, newDetails } = action
        const { people, places } = details
        const scheme = {
            people,
            places,
        }

        return from(firebase.database().ref(`users/${userId}/path`).update(scheme))
            .pipe(
                // `mergeMap` will handle only `next` notifications
                mergeMap((response) => {
                    const payload = ...
                    return [updatedCountrySuccess(payload)]
                }),
                catchError(error => of(errorAction)),
            );
    }),
)
</code>```

Body:
so I have this epic

export const listenToCountryVisitsEpic = (action$, store) => {
    return action$.pipe(
        ofType('UPDATE_TRIP_DETAILS'),
        mergeMap((action) => {
            const userId = store.value.user.id
            const { country, newDetails } = action
            const { people, places } = details
            const scheme = {
                people,
                places,
            }

            firebase.database().ref(`users/${userId}/path`).update(scheme)

            return mergeMap((response) => {
                const payload = { ...JSON.parse(response.request.body), currentDetails: action.currentDetails }
                return [updatedCountrySuccess(payload)]
            })
        }),
    )
}

what I want to do is make the request to firebase and then if successful update redux which in turn will update react. if not successful then catch it

this is correctly posting to firebase but I need to catch errors correctly. I don't want to fire this: updatedCountrySuccess until I know it's a success or failure in firebase

can I use async/await for this?

Body:
You can use from() to turn Promise into Observable and then catchError to replace the error with whatever you want.

import { from } from 'rxjs';
import { catchError } from 'rxjs/operators';

...

return action$.pipe(
    ofType('UPDATE_TRIP_DETAILS'),
    mergeMap((action) => {
        const userId = store.value.user.id
        const { country, newDetails } = action
        const { people, places } = details
        const scheme = {
            people,
            places,
        }

        return from(firebase.database().ref(`users/${userId}/path`).update(scheme))
            .pipe(
                // `mergeMap` will handle only `next` notifications
                mergeMap((response) => {
                    const payload = ...
                    return [updatedCountrySuccess(payload)]
                }),
                catchError(error => of(errorAction)),
            );
    }),
)