问:
IIS wont run C++ CGI program
I am having major issues running C++ CGI on IIS. I could have sworn I set it up the same as my last computer (Windows 10 32bit Nextbook 11 Flex) but this one (Windows 10 64bit HP LP1965) I went to Turn Windows Features on, enabled IIS, turned on CGI and filters, and web includes, enabled the handler, and added the application. But I cant seem to be able to run it. Here are the logs

```<code>#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2017-02-18 16:00:27
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2017-02-18 16:00:27 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 403 14 0 728
2017-02-18 16:00:27 ::1 GET /favicon.ico - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 404 0 2 3
2017-02-18 16:00:36 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 404 2 1260 7
2017-02-18 16:01:58 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 47
2017-02-18 16:05:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 12
2017-02-18 16:05:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 5
#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2017-02-18 16:25:25
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2017-02-18 16:25:25 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 14
2017-02-18 16:26:50 ::1 GET /chrisandarpitllc - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 301 0 0 1
2017-02-18 16:26:50 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 200 0 0 2
2017-02-18 16:26:53 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 11
2017-02-18 16:28:14 ::1 GET /favicon.ico - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://www.chrisandarpitllc.com/ 404 0 2 0
#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2017-02-18 16:31:07
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2017-02-18 16:31:07 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 200 0 0 9
2017-02-18 16:31:10 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 29
2017-02-18 16:32:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 27
2017-02-18 16:32:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 10
2017-02-18 16:32:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 5
2017-02-18 16:32:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 5
2017-02-18 16:32:13 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 13
2017-02-18 16:32:58 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 19
2017-02-18 16:32:58 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 5
2017-02-18 16:32:58 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 5
2017-02-18 16:32:58 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 13
#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2017-02-18 16:46:58
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2017-02-18 16:46:58 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 404 2 1260 663
2017-02-18 16:46:58 ::1 GET /favicon.ico - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/index.exe 404 0 2 5
2017-02-18 16:50:22 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 404 2 1260 20
2017-02-18 16:52:18 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 90
2017-02-18 16:52:18 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 7
2017-02-18 16:52:18 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 6
2017-02-18 16:58:14 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 29
</code>```

And here is a screenshot of the error

IIS Error given

And here is the code (Which was a simple test)

```<code>#include <iostream>

int main ()
{
    std::cout << "Content-Type:text/html\n" << std::endl;
    std::cout << "Hello world" << std::endl;
    return 0;
}
</code>```

Can anyone tell me why all this is happening? How can I fix this? If you need any information please let me know and I will provide it.

I also checked the website on another device this is what I got..

Mobile device error

答: Content-type header may be finished by "\r\n\r\n" symbols</p>

Title: IIS wont run C++ CGI program

Body:
I am having major issues running C++ CGI on IIS. I could have sworn I set it up the same as my last computer (Windows 10 32bit Nextbook 11 Flex) but this one (Windows 10 64bit HP LP1965) I went to Turn Windows Features on, enabled IIS, turned on CGI and filters, and web includes, enabled the handler, and added the application. But I cant seem to be able to run it. Here are the logs

#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2017-02-18 16:00:27
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2017-02-18 16:00:27 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 403 14 0 728
2017-02-18 16:00:27 ::1 GET /favicon.ico - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 404 0 2 3
2017-02-18 16:00:36 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 404 2 1260 7
2017-02-18 16:01:58 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 47
2017-02-18 16:05:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 12
2017-02-18 16:05:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 5
#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2017-02-18 16:25:25
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2017-02-18 16:25:25 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 14
2017-02-18 16:26:50 ::1 GET /chrisandarpitllc - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 301 0 0 1
2017-02-18 16:26:50 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 200 0 0 2
2017-02-18 16:26:53 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 11
2017-02-18 16:28:14 ::1 GET /favicon.ico - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://www.chrisandarpitllc.com/ 404 0 2 0
#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2017-02-18 16:31:07
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2017-02-18 16:31:07 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 200 0 0 9
2017-02-18 16:31:10 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 29
2017-02-18 16:32:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 27
2017-02-18 16:32:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 10
2017-02-18 16:32:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 5
2017-02-18 16:32:08 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/ 502 2 3221225781 5
2017-02-18 16:32:13 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 13
2017-02-18 16:32:58 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 19
2017-02-18 16:32:58 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 5
2017-02-18 16:32:58 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 5
2017-02-18 16:32:58 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 13
#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2017-02-18 16:46:58
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2017-02-18 16:46:58 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 404 2 1260 663
2017-02-18 16:46:58 ::1 GET /favicon.ico - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 http://localhost/chrisandarpitllc/index.exe 404 0 2 5
2017-02-18 16:50:22 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 404 2 1260 20
2017-02-18 16:52:18 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 90
2017-02-18 16:52:18 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 7
2017-02-18 16:52:18 ::1 GET /chrisandarpitllc/index.exe - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 6
2017-02-18 16:58:14 ::1 GET /chrisandarpitllc/ - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/56.0.2924.87+Safari/537.36 - 502 2 3221225781 29

And here is a screenshot of the error

IIS Error given

And here is the code (Which was a simple test)

#include <iostream>

int main ()
{
    std::cout << "Content-Type:text/html\n" << std::endl;
    std::cout << "Hello world" << std::endl;
    return 0;
}

Can anyone tell me why all this is happening? How can I fix this? If you need any information please let me know and I will provide it.

I also checked the website on another device this is what I got..

Mobile device error


来源: stackexchange

问:
R exact selection based on %in%
I am having some trouble doing a simple operation.

What I want is to simply select the rows, grouped by id, that have all of the values (-1, -2, -3, -4), and apply a tag based on this condition.

```<code>   id time
1   1   -4
2   1   -3
3   1   -2
4   1   -1
5   2   -1
6   2   -2
7   3   -1
8   3   -3
9   4   -1
10  4   -2
11  4   -3
12  4   -4
</code>```

Intuitively I was going for

```<code>rb[rb$time %in% c(-1, -2, -3, -4), ]
</code>```

However, when I do that, all id are selected. So, the %in% operator uses the OR | operator.

So, I thought I could do this then, to use the AND & operator

```<code>rb[rb$time == -1 &
 rb$time == -2 &
 rb$time == -3 &
 rb$time == -4, ]
</code>```

But it does not work.

Any clue how I could tag or subset these id, such that

```<code>   id time tag
1   1   -4   1
2   1   -3   1
3   1   -2   1
4   1   -1   1
5   2   -1   0
6   2   -2   0
7   3   -1   0
8   3   -3   0
9   4   -1   1
10  4   -2   1
11  4   -3   1
12  4   -4   1
</code>```

答:
One of many base R options is to use aggregate (we could also rename and convert to integer to get 0 or 1, but booleans seem better fit for the purpose):

```<code>tags <- aggregate(df$time, by = df["id"], FUN = function(el) all(-1:-4 %in% el))
df <- merge(df, tags)
</code>```

Result:

```<code>df
#    id time     x
# 1   1   -4  TRUE
# 2   1   -3  TRUE
# 3   1   -2  TRUE
# 4   1   -1  TRUE
# 5   2   -1 FALSE
# 6   2   -2 FALSE
# 7   2   -1 FALSE
# 8   2   -3 FALSE
# 9   3   -1  TRUE
# 10  3   -2  TRUE
# 11  3   -3  TRUE
# 12  3   -4  TRUE
</code>```

ContentLicense: CC BY-SA 4.0

Title: R exact selection based on %in%

Body:
I am having some trouble doing a simple operation.

What I want is to simply select the rows, grouped by id, that have all of the values (-1, -2, -3, -4), and apply a tag based on this condition.

   id time
1   1   -4
2   1   -3
3   1   -2
4   1   -1
5   2   -1
6   2   -2
7   3   -1
8   3   -3
9   4   -1
10  4   -2
11  4   -3
12  4   -4

Intuitively I was going for

rb[rb$time %in% c(-1, -2, -3, -4), ]

However, when I do that, all id are selected. So, the %in% operator uses the OR | operator.

So, I thought I could do this then, to use the AND & operator

rb[rb$time == -1 &
 rb$time == -2 &
 rb$time == -3 &
 rb$time == -4, ]

But it does not work.

Any clue how I could tag or subset these id, such that

   id time tag
1   1   -4   1
2   1   -3   1
3   1   -2   1
4   1   -1   1
5   2   -1   0
6   2   -2   0
7   3   -1   0
8   3   -3   0
9   4   -1   1
10  4   -2   1
11  4   -3   1
12  4   -4   1

Body:
One of many base R options is to use aggregate (we could also rename and convert to integer to get 0 or 1, but booleans seem better fit for the purpose):

tags <- aggregate(df$time, by = df["id"], FUN = function(el) all(-1:-4 %in% el))
df <- merge(df, tags)

Result:

df
#    id time     x
# 1   1   -4  TRUE
# 2   1   -3  TRUE
# 3   1   -2  TRUE
# 4   1   -1  TRUE
# 5   2   -1 FALSE
# 6   2   -2 FALSE
# 7   2   -1 FALSE
# 8   2   -3 FALSE
# 9   3   -1  TRUE
# 10  3   -2  TRUE
# 11  3   -3  TRUE
# 12  3   -4  TRUE


问:
What is the relationship between bind and join?
I got the impression that (>>=) (used by Haskell) and join (preferred by mathematicians) are "equal" since one can write one in terms of the other:

```<code>import Control.Monad (join)

join x = x >>= id
x >>= f = join (fmap f x)
</code>```

Additionally every monad is a functor since bind can be used to replace fmap:

```<code>fmap f x = x >>= (return . f)
</code>```

I have the following questions:

Is there a (non-recursive) definition of fmap in terms of join? (fmap f x = join $ fmap (return . f) x follows from the equations above but is recursive.)

Is "every monad is a functor" a conclusion when using bind (in the definition of a monad), but an assumption when using join?

Is bind more "powerful" than join? And what would "more powerful" mean?

答:
A monad can be either defined in terms of:

return :: a -> m a

bind :: m a -> (a -> m b) -> m b

or alternatively in terms of:

return :: a -> m a

fmap :: (a -> b) -> m a -> m b

join :: m (m a) -> m a

To your questions:

No, we cannot define fmap in terms of join, since otherwise we could remove fmap from the second list above.

No, "every monad is a functor" is a statement about monads in general, regardless whether you define your specific monad in terms of bind or in terms of join and fmap. It is easier to understand the statement if you see the second definition, but that's it.

Yes, bind is more "powerful" than join. It is exactly as "powerful" as join and fmap combined, if you mean with "powerful" that it has the capacity to define a monad (always in combination with return).

For an intuition, see e.g. this answer – bind allows you to combine or chain strategies/plans/computations (that are in a context) together. As an example, let's use the Maybe context (or Maybe monad):

```<code>λ: let plusOne x = Just (x + 1)
λ: Just 3 >>= plusOne
Just 4
</code>```

fmap also let's you chain computations in a context together, but at the cost of increasing the nesting with every step.[1]

```<code>λ: fmap plusOne (Just 3)
Just (Just 4)
</code>```

That's why you need join: to squash two levels of nesting into one. Remember:

```<code>join :: m (m a) -> m a
</code>```

Having only the squashing step doesn't get you very far. You need also fmap to have a monad – and return, which is Just in the example above.

[1]: fmap and (>>=) don't take their two arguments in the same order, but don't let that confuse you.

Body:
I got the impression that (>>=) (used by Haskell) and join (preferred by mathematicians) are "equal" since one can write one in terms of the other:

import Control.Monad (join)

join x = x >>= id
x >>= f = join (fmap f x)

Additionally every monad is a functor since bind can be used to replace fmap:

fmap f x = x >>= (return . f)

I have the following questions:

Is there a (non-recursive) definition of fmap in terms of join? (fmap f x = join $ fmap (return . f) x follows from the equations above but is recursive.)

Is "every monad is a functor" a conclusion when using bind (in the definition of a monad), but an assumption when using join?

Is bind more "powerful" than join? And what would "more powerful" mean?

Body:
A monad can be either defined in terms of:

return :: a -> m a

bind :: m a -> (a -> m b) -> m b

or alternatively in terms of:

return :: a -> m a

fmap :: (a -> b) -> m a -> m b

join :: m (m a) -> m a

To your questions:

No, we cannot define fmap in terms of join, since otherwise we could remove fmap from the second list above.

No, "every monad is a functor" is a statement about monads in general, regardless whether you define your specific monad in terms of bind or in terms of join and fmap. It is easier to understand the statement if you see the second definition, but that's it.

Yes, bind is more "powerful" than join. It is exactly as "powerful" as join and fmap combined, if you mean with "powerful" that it has the capacity to define a monad (always in combination with return).

For an intuition, see e.g. this answer – bind allows you to combine or chain strategies/plans/computations (that are in a context) together. As an example, let's use the Maybe context (or Maybe monad):

λ: let plusOne x = Just (x + 1)
λ: Just 3 >>= plusOne
Just 4

fmap also let's you chain computations in a context together, but at the cost of increasing the nesting with every step.[1]

λ: fmap plusOne (Just 3)
Just (Just 4)

That's why you need join: to squash two levels of nesting into one. Remember:

join :: m (m a) -> m a

Having only the squashing step doesn't get you very far. You need also fmap to have a monad – and return, which is Just in the example above.

[1]: fmap and (>>=) don't take their two arguments in the same order, but don't let that confuse you.


问:
Block Ciphers and Stream Ciphers
I understand that block ciphers are more popular in software as opposed to stream ciphers which are typically hardware based. However, why can't a key be reused in stream ciphers? Is it because of patterns that may form?</p>

答:
A stream cipher is an encryption system which works over a given sequence of input bits. Most stream ciphers work by generating from the key a long sequence of random-looking bits, which are then combined (by bitwise XOR) with the data to encrypt. This is a (crude) emulation of one-time pad.

A block cipher is a generic cryptographic element which works over "blocks" which are sequences of bits with a fixed length (e.g. 128 bits for AES). The block cipher is a permutation of the blocks; the key selects which permutation we are talking about. A block cipher alone cannot process an arbitrary long message; the block cipher and the data must be used within an elaborate construction called a mode of operation (also often called a "chaining mode").

There is a chaining mode for block ciphers called "CTR" as "counter mode": in this mode, the block cipher is used to encrypt successive values of a counter (the counter having the size of a block). The resulting encrypted blocks are then concatenated, resulting in an arbitrarily long sequence of bits which depend only on the key. It suffices then to XOR that sequence with the data to encrypt. In other words, CTR mode turns a block cipher into a stream cipher. Another popular chaining mode is CBC, which does not fit the model of a stream cipher.

With stream ciphers, what must be avoided at all costs is reusing the same key-dependent sequence of bits for two distinct messages; this would yield the infamous "two-times pad" which can be broken quite easily (by exploiting redundancies in the two encrypted messages). With a block cipher in CTR mode, this translates to reusing the same counter values. This is why CTR mode requires a random Initial Value (IV) which is the counter value you begin encryption with. By choosing a new random IV, with sufficiently large blocks, you avoid with very high probability any overlap in the sequences of counter values that you use.

The concept of IV is not specific to block ciphers; some stream ciphers also use an IV (e.g. the one in the eSTREAM portfolio). When a stream cipher has an IV, reusing the key is no problem -- provided that you use proper IV (i.e. IV generated with a cryptographically strong RNG in the complete space of possible IV, with uniform probability). However, some other stream ciphers do not have an IV, in particular the widely used RC4. Reusing the same key would mean reusing the exact same sequence of generated bits, and that's bad.

Note that some chaining modes other than CTR also need an IV, which should be unique for each message encrypted with a given key. Block ciphers do not alleviate the need for that.

ContentLicense: CC BY-SA 3.0

Title: Block Ciphers and Stream Ciphers


问:
Passing buffer as Uint8Array without null bytes
I'm trying to pass image data from Jimp image object to Tesserract (ocr lib) via buffer:

image.getBufferAsync('image/png').then((buffer) => {
  // Buffer here is <Buffer 12 34 56 ...
  const worker = new TesseractWorker();
  worker.recognize(buffer)
      .then((result) => { console.log('result', result.text); });

});
```

<p>Which throws an error from Teserract saying that it wants Uint8Array and not buffer</p>

```TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received <Buffer 89 50 4e 47...
```

<p>So I try to convert buffer to Uint8Array:</p>

```buffer = new Uint8Array(buffer);
```

<p>But I get another error:</p>

```TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received Uint8Array [
  137,
  80,
  ...
```

Where is a mistake?

If I save image file to disc and then read its path via Teserract - it works, so the problem shouldn't be the image.

答:
The below worked for me.  Think we might be on different versions of tesseract (v.3.05), but don't think it changes much.</p>

```<code>    var Jimp = require('jimp');
    var Tesseract = require('tesseract.js');
    var file = 'YourFile.png';  // Or .jpg etc...

    Jimp.read(file, async (err, image) => {
        if (err) throw err;

        //Do your Jimp stuff here to 'image' then...

        const buffer = await image.getBufferAsync(Jimp.AUTO);

        //Above line creates a buffer using Jimp.AUTO (the
        //original file format from your variable 'file')

        Tesseract.recognize(buffer,'eng')
            .then(data => {
             console.log(data)
            })
     })
</code>```

Body:
I'm trying to pass image data from Jimp image object to Tesserract (ocr lib) via buffer:

image.getBufferAsync('image/png').then((buffer) => {
  // Buffer here is <Buffer 12 34 56 ...
  const worker = new TesseractWorker();
  worker.recognize(buffer)
      .then((result) => { console.log('result', result.text); });

});

Which throws an error from Teserract saying that it wants Uint8Array and not buffer

TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received <Buffer 89 50 4e 47...

So I try to convert buffer to Uint8Array:

buffer = new Uint8Array(buffer);

But I get another error:

TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received Uint8Array [
  137,
  80,
  ...

Where is a mistake?

If I save image file to disc and then read its path via Teserract - it works, so the problem shouldn't be the image.

Body:
The below worked for me.  Think we might be on different versions of tesseract (v.3.05), but don't think it changes much.

    var Jimp = require('jimp');
    var Tesseract = require('tesseract.js');
    var file = 'YourFile.png';  // Or .jpg etc...

    Jimp.read(file, async (err, image) => {
        if (err) throw err;

        //Do your Jimp stuff here to 'image' then...

        const buffer = await image.getBufferAsync(Jimp.AUTO);

        //Above line creates a buffer using Jimp.AUTO (the
        //original file format from your variable 'file')

        Tesseract.recognize(buffer,'eng')
            .then(data => {
             console.log(data)
            })
     })


问:
Error when checking array element in Powershell script : unexpected token 'eq'
I wish to go through a sharepoint list and if a property (a choice field named Status) is a certain value then change the author of that item.

```<code>Add-PSSnapin Microsoft.SharePoint.Powershell
$web = Get-SPWeb "http://site"
$library = $web.Lists["UserInfo"]
$newUser = $web.EnsureUser("user1")
$oldUser = $web.EnsureUser("user2")

foreach ($item in $library.Items)
{
   #$userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["DocumentAuthorColumnInternalName"].ToString())
   $userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["Author"].ToString())
   $userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["Author"].ToString())
   $login = $userfield.User.LoginName
   #if ($login -eq $oldUser.LoginName)
   if ($login -eq $oldUser.LoginName)
   {

#if($item["Status"] eq 'Fully Implemented')
#{
    $item["Author"] = $newUser
        #if you are using default "Author" column, you need to set the following as well:
        $item.Properties["vti_author"] = $newUser.LoginName
        $item.UpdateOverwriteVersion() #this saves changes without incrementing the version
       #}
   }
   $login = $null
}

$web.Dispose();
</code>```

I can get it working but when I reach the line

```<code>if($item["Status"] eq 'Fully Implemented')
</code>```

It causes an error

unexpected token 'eq'

答:
Have you just missed the hyphen in eq? So it should be:</p>

```<code>if($item["Status"] -eq 'Fully Implemented')
{
}
</code>```

Body:
I wish to go through a sharepoint list and if a property (a choice field named Status) is a certain value then change the author of that item.

Add-PSSnapin Microsoft.SharePoint.Powershell
$web = Get-SPWeb "http://site"
$library = $web.Lists["UserInfo"]
$newUser = $web.EnsureUser("user1")
$oldUser = $web.EnsureUser("user2")

foreach ($item in $library.Items)
{
   #$userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["DocumentAuthorColumnInternalName"].ToString())
   $userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["Author"].ToString())
   $userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["Author"].ToString())
   $login = $userfield.User.LoginName
   #if ($login -eq $oldUser.LoginName)
   if ($login -eq $oldUser.LoginName)
   {

#if($item["Status"] eq 'Fully Implemented')
#{
    $item["Author"] = $newUser
        #if you are using default "Author" column, you need to set the following as well:
        $item.Properties["vti_author"] = $newUser.LoginName
        $item.UpdateOverwriteVersion() #this saves changes without incrementing the version
       #}
   }
   $login = $null
}

$web.Dispose();

I can get it working but when I reach the line

if($item["Status"] eq 'Fully Implemented')

It causes an error

unexpected token 'eq'

Body:
Have you just missed the hyphen in eq? So it should be:

if($item["Status"] -eq 'Fully Implemented')
{
}


问:
Redirect any non existing files/pages in a folder to a special page
I am using DNN as my website platform.
Here is the situation:

Our software has links to online documents stored on our website hosting space. It consists of multi-language. However, there are several languages are not available yet. Therefore when the user clicks some of our help items in the software, it will display "404 error" because the page does not exist.

Since there are over hundreds of pages not exist. It will spend too much time to match one by one (and they do not even exist on the site). Therefore we want to redirect them all to the default English one.

The limitation is we can not modify the software because it can be used offline. So we have to do something on the website hosting.

The solution I thought is redirect all non-existing files under a specific folder to a page. The folder will be empty.

Only non-existing pages under that specific folder will redirect to a page. Other non-existing pages on the website will still go to 404.

I have tried to modify the web.config file but it is not working

```<code><rewrite>
      <rules>
        <clear />
        <rule name="Online Document 404 Redirection" stopProcessing="true">
          <match url="/Help/sub/xe/nonexist/(.*)" />
          <action type="Redirect" url="/Help/sub/xe/en/index.htm" />
        </rule>
      </rules>
</rewrite>
</code>```

Still goes to 404 error page.

答:
I don't think the IIS url rewriter (not installed by default) could help here as it will redirect all urls in the folder.

The best option would be to redirect users from the 404 page under certain conditions.
You could add some logic for this to the theme/skin on the 404 page.
We also have (free) module the does the same if you want.

Body:
I am using DNN as my website platform.
Here is the situation:

Our software has links to online documents stored on our website hosting space. It consists of multi-language. However, there are several languages are not available yet. Therefore when the user clicks some of our help items in the software, it will display "404 error" because the page does not exist.

Since there are over hundreds of pages not exist. It will spend too much time to match one by one (and they do not even exist on the site). Therefore we want to redirect them all to the default English one.

The limitation is we can not modify the software because it can be used offline. So we have to do something on the website hosting.

The solution I thought is redirect all non-existing files under a specific folder to a page. The folder will be empty.

Only non-existing pages under that specific folder will redirect to a page. Other non-existing pages on the website will still go to 404.

I have tried to modify the web.config file but it is not working

<rewrite>
      <rules>
        <clear />
        <rule name="Online Document 404 Redirection" stopProcessing="true">
          <match url="/Help/sub/xe/nonexist/(.*)" />
          <action type="Redirect" url="/Help/sub/xe/en/index.htm" />
        </rule>
      </rules>
</rewrite>

Still goes to 404 error page.


问:
ESLint Unexpected dangling '_' in '__place' no-underscore-dangle
I have the below JSON response, to validate the __place, i used responseData.search[0].edges[0].node.__place

```<code>{
  "data": {
    "search": [
      {
        "__place": "SearchResultItemConnection",
        "edges": [
          {
            "cursor": "New",
            "node": {
              "__place": "Delhi",
              "name": "AIIMS"
            }
          }
        ]
      }
    ]
  }
}
</code>```

I'm getting the ESLint error stating "error    Unexpected dangling '_' in '__typename'                                      no-underscore-dangle"

I went through the link, http://eslint.org/docs/rules/no-underscore-dangle but i'm not able to resolve this.

Could anyone know how to resolve this, instead of changing the rules?

答:
In case you would like to disable a whole rule (for example "no-underscore-dangle"), just type in config : </p>

```<code>{
   rules: {
      "no-underscore-dangle": 'off'
   },
};
</code>```

Body:
I have the below JSON response, to validate the __place, i used responseData.search[0].edges[0].node.__place

{
  "data": {
    "search": [
      {
        "__place": "SearchResultItemConnection",
        "edges": [
          {
            "cursor": "New",
            "node": {
              "__place": "Delhi",
              "name": "AIIMS"
            }
          }
        ]
      }
    ]
  }
}

I'm getting the ESLint error stating "error    Unexpected dangling '_' in '__typename'                                      no-underscore-dangle"

I went through the link, http://eslint.org/docs/rules/no-underscore-dangle but i'm not able to resolve this.

Could anyone know how to resolve this, instead of changing the rules?

Body:
In case you would like to disable a whole rule (for example "no-underscore-dangle"), just type in config :

{
   rules: {
      "no-underscore-dangle": 'off'
   },
};


问:
Is it possible to replace Integer[] with int[]?
I'm trying to rewrite my code for a little bit. Is it possible to use int[] array instead of Integer[] in my code?

When I replacing all of Integer[] with int[], I'm stuck in part of replacing:

.toArray(Integer[]::new);
```

<p>with</p>

<pre class="lang-java prettyprint-override"><code>.toArray(int[]::new);
</code>```

public class Main {

    private static final int MODULO = (int) (Math.pow(10, 9) + 7);

    private static int modulate(final long result) {
        return (int) (result % MODULO);
    }

    //private static

    private static Integer[] steps(final int smaller, final int larger) {
        final int lcm = lowestCommonMultiple(smaller, larger);
        final int max = lcm / smaller;
        final int min = lcm / larger;
        final Integer[] result = new Integer[max * 2];

        int pos = 0;
        for (int i = 1; i <= max; i++) {
            result[pos++] = (i * smaller);
            if (i <= min) {
                result[pos++] = (i * larger);
            }
        }
        return Arrays.stream(result)
                .filter(Objects::nonNull)
                .sorted()
                .distinct()
                .toArray(Integer[]::new);
    }

    private static long nthNonZeroMagicalNumber(final int N, final int smaller, final int larger) {
        final Integer[] stepsInCycle = steps(smaller, larger);
        final long lcm = stepsInCycle[stepsInCycle.length - 1];
        final int inOneCycle = stepsInCycle.length;
        final int fullCycleCount = N / inOneCycle;
        int count = fullCycleCount * inOneCycle;
        final long evaluated = fullCycleCount * lcm;
        if (count == N) {
            return evaluated;
        }
        final int remainder = N - count - 1;
        return stepsInCycle[remainder] + evaluated;
    }

    private static int greatestCommonDenominator(int a, int b) {
        while (b > 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    public static int lowestCommonMultiple(final int a, final int b) {
        return a * (b / greatestCommonDenominator(a, b));
    }

    public static int nthMagicalNumber(final int N, final int A, final int B) {
        if (N == 0) {
            return 0;
        } else if (A == B) {
            final long result = (long) A * (long) N;
            return modulate(result);
        } else if (N == 1) {
            return modulate(Math.min(A, B));
        }
        return modulate(nthNonZeroMagicalNumber(N, Math.min(A, B), Math.max(A, B)));
    }

    public static void main(String[] args) {
        int result = nthMagicalNumber(53776, 22434, 31343);

    }
}
```

If someone can give me any advice I will really appreciate it. Thank you in advance!

答:
Assuming you start with an Integer[], you can unbox the Integers inside the stream, which will give an IntStream from your Stream<Integer>.

```<code>// if result is an Integer[]
return Arrays.stream(result)
        .filter(Objects::nonNull)
        .sorted()
        .distinct()
        .mapToInt(n -> n) // this gives an IntStream
        .toArray();       // this returns an int[]
</code>```

If you actually change your result array to type int[] then you won't need the unboxing, but you won't be able to filter out elements using nonNull any more: the unwritten elements in your array will be zero instead of null. So you would have:

```<code>// if result is an int[]
return Arrays.stream(result)
             .filter(n -> n!=0)
             .sorted()
             .distinct()
             .toArray();
</code>```

You might be better off using lists instead of arrays. A list can increase in size as required, so you don't have to track what position you have reached, or exclude elements you haven't written to.

Body:
I'm trying to rewrite my code for a little bit. Is it possible to use int[] array instead of Integer[] in my code?

When I replacing all of Integer[] with int[], I'm stuck in part of replacing:

.toArray(Integer[]::new);

with

.toArray(int[]::new);

public class Main {

    private static final int MODULO = (int) (Math.pow(10, 9) + 7);

    private static int modulate(final long result) {
        return (int) (result % MODULO);
    }

    //private static

    private static Integer[] steps(final int smaller, final int larger) {
        final int lcm = lowestCommonMultiple(smaller, larger);
        final int max = lcm / smaller;
        final int min = lcm / larger;
        final Integer[] result = new Integer[max * 2];

        int pos = 0;
        for (int i = 1; i <= max; i++) {
            result[pos++] = (i * smaller);
            if (i <= min) {
                result[pos++] = (i * larger);
            }
        }
        return Arrays.stream(result)
                .filter(Objects::nonNull)
                .sorted()
                .distinct()
                .toArray(Integer[]::new);
    }

    private static long nthNonZeroMagicalNumber(final int N, final int smaller, final int larger) {
        final Integer[] stepsInCycle = steps(smaller, larger);
        final long lcm = stepsInCycle[stepsInCycle.length - 1];
        final int inOneCycle = stepsInCycle.length;
        final int fullCycleCount = N / inOneCycle;
        int count = fullCycleCount * inOneCycle;
        final long evaluated = fullCycleCount * lcm;
        if (count == N) {
            return evaluated;
        }
        final int remainder = N - count - 1;
        return stepsInCycle[remainder] + evaluated;
    }

    private static int greatestCommonDenominator(int a, int b) {
        while (b > 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    public static int lowestCommonMultiple(final int a, final int b) {
        return a * (b / greatestCommonDenominator(a, b));
    }

    public static int nthMagicalNumber(final int N, final int A, final int B) {
        if (N == 0) {
            return 0;
        } else if (A == B) {
            final long result = (long) A * (long) N;
            return modulate(result);
        } else if (N == 1) {
            return modulate(Math.min(A, B));
        }
        return modulate(nthNonZeroMagicalNumber(N, Math.min(A, B), Math.max(A, B)));
    }

    public static void main(String[] args) {
        int result = nthMagicalNumber(53776, 22434, 31343);

    }
}

If someone can give me any advice I will really appreciate it. Thank you in advance!

Body:
Assuming you start with an Integer[], you can unbox the Integers inside the stream, which will give an IntStream from your Stream<Integer>.

// if result is an Integer[]
return Arrays.stream(result)
        .filter(Objects::nonNull)
        .sorted()
        .distinct()
        .mapToInt(n -> n) // this gives an IntStream
        .toArray();       // this returns an int[]

If you actually change your result array to type int[] then you won't need the unboxing, but you won't be able to filter out elements using nonNull any more: the unwritten elements in your array will be zero instead of null. So you would have:

// if result is an int[]
return Arrays.stream(result)
             .filter(n -> n!=0)
             .sorted()
             .distinct()
             .toArray();

You might be better off using lists instead of arrays. A list can increase in size as required, so you don't have to track what position you have reached, or exclude elements you haven't written to.


问:
From serial to omp: no speedup
I'm new to openMP. I'm working on All Pair Shortest Path Algorithm and here is the serial C++ routine i need to parallelize (complete code at the end of the post):

```<code>void mini(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    size_t i, j;

    for ( i=0; i<n; i++)
        for ( j=0; j<n; j++)
            M[i][j]=min(rowk[j]+colk[i], M[i][j]);

}
</code>```

At execution I get this :

```<code>$ time ./floyd

real    0m0,349s
user    0m0,349s
sys     0m0,000s
</code>```

Now, I try to insert some directives:

```<code>void mini(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{

    #pragma omp parallel
    {
        size_t i, j;

        #pragma omp parallel for
        for ( i=0; i<n; i++)
            for ( j=0; j<n; j++)
                M[i][j]=min(rowk[j]+colk[i], M[i][j]);
    }

}
</code>```

Unfortunately, there is no speedup:

```<code>$ grep -c ^processor /proc/cpuinfo
4
$ time ./floyd

real    0m0,547s
user    0m2,073s
sys     0m0,004s
</code>```

What am I doing wrong?

EDIT

Processor: Intel(R) Core(TM) i5-4590 CPU (4 hardware cores)

Complete code :

```<code>#include <cstdio>
#include <vector>
#include <limits>
#include <ctime>
#include <random>
#include <set>
#include <omp.h>

using namespace std;

typedef struct Wedge
{
    int a, b;
    double w;
} Wedge;

typedef pair<int, int> edge;

int randrange(int end, int start=0)
{
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(start, end-1);

    return dis(gen);
}

void relax_omp(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    #pragma omp parallel
    {
        size_t i, j;

        #pragma omp parallel for
        for (i=0; i<n; i++)
            for ( j=0; j<n; j++)
                M[i][j]=min(rowk[j]+colk[i], M[i][j]);

    }
}

void relax_serial(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    size_t i, j;

    for (i=0; i<n; i++)
        for ( j=0; j<n; j++)
            M[i][j]=min(rowk[j]+colk[i], M[i][j]);
}

void floyd(vector<vector<double>> &dist, bool serial)
{
    size_t i, k;

    size_t n {dist.size()};

    for (k=0; k<n; k++)
    {
        vector<double> rowk =dist[k];
        vector<double> colk(n);

        for (i=0; i<n; i++)
            colk[i]=dist[i][k];
        if (serial)
            relax_serial(dist, n, rowk, colk);
        else
            relax_omp(dist, n, rowk, colk);
    }

    for (i=0; i<n; i++)
        dist[i][i]=0;
}

vector<Wedge> random_edges(int n, double density, double max_weight)
{
    int M{n*(n-1)/2};
    double m{density*M};
    set<edge> edges;
    vector<Wedge> wedges;

    while (edges.size()<m)
    {
        pair<int,int> L;
        L.first=randrange(n);
        L.second=randrange(n);

        if (L.first!=L.second && edges.find(L) == edges.end())
        {
            double w=randrange(max_weight);
            Wedge wedge{L.first, L.second, w};
            wedges.push_back(wedge);
            edges.insert(L);
        }
    }
    return wedges;
}

vector<vector<double>> fill_distances(vector<Wedge> wedges, int n)
{
    double INF = std::numeric_limits<double>::infinity();
    size_t i, m=wedges.size();
    vector<vector<double>> dist(n, vector<double>(n, INF));
    int a, b;
    double w;
    for (i=0; i<m; i++)
    {   a=wedges[i].a;
        b=wedges[i].b;
        w=wedges[i].w;
        dist[a][b]=w;
    }
    return dist;
}

int main (void)
{
    double density{0.33};
    double max_weight{200};
    int n{800};
    bool serial;

    int ntest=10;
    double avge_serial=0, avge_omp=0;

    for (int i=0; i<ntest; i++)
    {
        vector<Wedge> wedges=random_edges(n, density, max_weight);
        vector<vector<double>> dist=fill_distances(wedges, n);
        double dtime;

        dtime = omp_get_wtime();
        serial=true;
        floyd(dist, serial);
        dtime = omp_get_wtime() - dtime;
        avge_serial+=dtime;

        dtime = omp_get_wtime();
        serial=false;
        floyd(dist, serial);
        dtime = omp_get_wtime() - dtime;
        avge_omp+=dtime;
    }
    printf("%d tests, n=%d\n", ntest, n);
    printf("Average serial : %.2lf\n", avge_serial/ntest);
    printf("Average openMP : %.2lf\n", avge_omp/ntest);
    return 0;
}
</code>```

output :

```<code>20 tests, n=800
Average serial : 0.31
Average openMP : 0.61
</code>```

command line:

```<code>g++ -std=c++11 -Wall -O2 -Wno-unused-result -Wno-unused-variable -Wno-unused-but-set-variable -Wno-unused-parameter floyd.cpp -o floyd -lm -fopenmp
</code>```

答:
Your main issue is that you accidentally use nested parallelism:

```<code>#pragma omp parallel
{
    size_t i, j;

    #pragma omp parallel for
</code>```

Since you already are in a parallel region, your second line should be

```<code>    #pragma omp for
</code>```

Otherwise, since a omp parallel for equals a omp parallel and a omp for, you have two nested parallel regions which is typically bad. Fixing this minor thing gets an ~2x speedup on a similar CPU.

There are several limitations why you are unlikely to get a full 4x speedup, such as but not limited to:

Memory bandwidth as a bottleneck

Relative overhead due to the small amount of work done within the parallel loop

Lower clock frequencies with multiple threads in turbo mode

Edit:
By the way, the much more idiomatic way to write your code is the following:

```<code>void relax_omp(...) {
  #pragma omp parallel for
  for (size_t i=0; i<n; i++) {
    for (size_t j=0; j<n; j++) {
      M[i][j]=min(rowk[j]+colk[i], M[i][j]);
    }
  }
}
</code>```

If you declare variables as locally as possible, OpenMP wil almost alaways do the right thing. Which, in this case, means that i and j are private. In general it is much easier to reason about code this way.

Title: From serial to omp: no speedup

Body:
I'm new to openMP. I'm working on All Pair Shortest Path Algorithm and here is the serial C++ routine i need to parallelize (complete code at the end of the post):

void mini(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    size_t i, j;

    for ( i=0; i<n; i++)
        for ( j=0; j<n; j++)
            M[i][j]=min(rowk[j]+colk[i], M[i][j]);

}

At execution I get this :

$ time ./floyd

real    0m0,349s
user    0m0,349s
sys     0m0,000s

Now, I try to insert some directives:

void mini(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{

    #pragma omp parallel
    {
        size_t i, j;

        #pragma omp parallel for
        for ( i=0; i<n; i++)
            for ( j=0; j<n; j++)
                M[i][j]=min(rowk[j]+colk[i], M[i][j]);
    }

}

Unfortunately, there is no speedup:

$ grep -c ^processor /proc/cpuinfo
4
$ time ./floyd

real    0m0,547s
user    0m2,073s
sys     0m0,004s

What am I doing wrong?

EDIT

Processor: Intel(R) Core(TM) i5-4590 CPU (4 hardware cores)

Complete code :

#include <cstdio>
#include <vector>
#include <limits>
#include <ctime>
#include <random>
#include <set>
#include <omp.h>

using namespace std;

typedef struct Wedge
{
    int a, b;
    double w;
} Wedge;

typedef pair<int, int> edge;

int randrange(int end, int start=0)
{
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(start, end-1);

    return dis(gen);
}

void relax_omp(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    #pragma omp parallel
    {
        size_t i, j;

        #pragma omp parallel for
        for (i=0; i<n; i++)
            for ( j=0; j<n; j++)
                M[i][j]=min(rowk[j]+colk[i], M[i][j]);

    }
}

void relax_serial(vector<vector<double>> &M, size_t n, vector<double> &rowk, vector<double> &colk)
{
    size_t i, j;

    for (i=0; i<n; i++)
        for ( j=0; j<n; j++)
            M[i][j]=min(rowk[j]+colk[i], M[i][j]);
}

void floyd(vector<vector<double>> &dist, bool serial)
{
    size_t i, k;

    size_t n {dist.size()};

    for (k=0; k<n; k++)
    {
        vector<double> rowk =dist[k];
        vector<double> colk(n);

        for (i=0; i<n; i++)
            colk[i]=dist[i][k];
        if (serial)
            relax_serial(dist, n, rowk, colk);
        else
            relax_omp(dist, n, rowk, colk);
    }

    for (i=0; i<n; i++)
        dist[i][i]=0;
}

vector<Wedge> random_edges(int n, double density, double max_weight)
{
    int M{n*(n-1)/2};
    double m{density*M};
    set<edge> edges;
    vector<Wedge> wedges;

    while (edges.size()<m)
    {
        pair<int,int> L;
        L.first=randrange(n);
        L.second=randrange(n);

        if (L.first!=L.second && edges.find(L) == edges.end())
        {
            double w=randrange(max_weight);
            Wedge wedge{L.first, L.second, w};
            wedges.push_back(wedge);
            edges.insert(L);
        }
    }
    return wedges;
}

vector<vector<double>> fill_distances(vector<Wedge> wedges, int n)
{
    double INF = std::numeric_limits<double>::infinity();
    size_t i, m=wedges.size();
    vector<vector<double>> dist(n, vector<double>(n, INF));
    int a, b;
    double w;
    for (i=0; i<m; i++)
    {   a=wedges[i].a;
        b=wedges[i].b;
        w=wedges[i].w;
        dist[a][b]=w;
    }
    return dist;
}

int main (void)
{
    double density{0.33};
    double max_weight{200};
    int n{800};
    bool serial;

    int ntest=10;
    double avge_serial=0, avge_omp=0;

    for (int i=0; i<ntest; i++)
    {
        vector<Wedge> wedges=random_edges(n, density, max_weight);
        vector<vector<double>> dist=fill_distances(wedges, n);
        double dtime;

        dtime = omp_get_wtime();
        serial=true;
        floyd(dist, serial);
        dtime = omp_get_wtime() - dtime;
        avge_serial+=dtime;

        dtime = omp_get_wtime();
        serial=false;
        floyd(dist, serial);
        dtime = omp_get_wtime() - dtime;
        avge_omp+=dtime;
    }
    printf("%d tests, n=%d\n", ntest, n);
    printf("Average serial : %.2lf\n", avge_serial/ntest);
    printf("Average openMP : %.2lf\n", avge_omp/ntest);
    return 0;
}

output :

20 tests, n=800
Average serial : 0.31
Average openMP : 0.61

command line:

g++ -std=c++11 -Wall -O2 -Wno-unused-result -Wno-unused-variable -Wno-unused-but-set-variable -Wno-unused-parameter floyd.cpp -o floyd -lm -fopenmp

Body:
Your main issue is that you accidentally use nested parallelism:

#pragma omp parallel
{
    size_t i, j;

    #pragma omp parallel for

Since you already are in a parallel region, your second line should be

    #pragma omp for

Otherwise, since a omp parallel for equals a omp parallel and a omp for, you have two nested parallel regions which is typically bad. Fixing this minor thing gets an ~2x speedup on a similar CPU.

There are several limitations why you are unlikely to get a full 4x speedup, such as but not limited to:

Memory bandwidth as a bottleneck

Relative overhead due to the small amount of work done within the parallel loop

Lower clock frequencies with multiple threads in turbo mode

Edit:
By the way, the much more idiomatic way to write your code is the following:

void relax_omp(...) {
  #pragma omp parallel for
  for (size_t i=0; i<n; i++) {
    for (size_t j=0; j<n; j++) {
      M[i][j]=min(rowk[j]+colk[i], M[i][j]);
    }
  }
}

If you declare variables as locally as possible, OpenMP wil almost alaways do the right thing. Which, in this case, means that i and j are private. In general it is much easier to reason about code this way.


问:
Remove canvas element on click with typescript
I am new to typescript and what i am trying is, to remove canvas element from the div. So here is my HTML code.

```<code><div class="chart">
    <canvas id="nav-chart"></canvas>
</div>
</code>```

on click removing the canvas element using id nav-chart. So here my JS code inside the onclick function

```<code>const elem: HTMLElement = document.getElementById('nav-chart')
if (elem) {
   elem.parentElement.removeChild(elem)
}
</code>```

While trying this it throws the error saying at the line
const elem: HTMLElement = document.getElementById('nav-chart')

```<code>TS2322: Type 'HTMLElement | null' is not assignable to type 'HTMLElement'.
  Type 'null' is not assignable to type 'HTMLElement'.
</code>```

and in this line elem.parentElement.removeChild(elem)

```<code>TS2531: Object is possibly 'null'.
</code>```

答:
I found the solution first we have to declare the element type with HTMLElement | null

```<code>const elem: HTMLElement | null = document.getElementById('nav-chart')
</code>```

and inside the condition.

```<code>if (elem) {
      elem.parentElement && elem.parentElement.removeChild(elem)
}
</code>```

Body:
I am new to typescript and what i am trying is, to remove canvas element from the div. So here is my HTML code.

    <canvas id="nav-chart"></canvas>

on click removing the canvas element using id nav-chart. So here my JS code inside the onclick function

const elem: HTMLElement = document.getElementById('nav-chart')
if (elem) {
   elem.parentElement.removeChild(elem)
}

While trying this it throws the error saying at the line
const elem: HTMLElement = document.getElementById('nav-chart')

TS2322: Type 'HTMLElement | null' is not assignable to type 'HTMLElement'.
  Type 'null' is not assignable to type 'HTMLElement'.

and in this line elem.parentElement.removeChild(elem)

TS2531: Object is possibly 'null'.

Body:
I found the solution first we have to declare the element type with HTMLElement | null

const elem: HTMLElement | null = document.getElementById('nav-chart')

and inside the condition.

if (elem) {
      elem.parentElement && elem.parentElement.removeChild(elem)
}


问:
react-native-navigation showModal Custom Size
I use wix react-native-navigation. Navigation.showModal open fullscreen size. Is it possible to open the custom size? where do I find all the properties list about navigation layouts? Documentation is too meager...</p>

答:
Modal is always full screen. You can control your view's dimensions in jsx.
Instead of flex: 1 - use a predefined width and height according to your needs.

```<code>render() {
  return (
    <View style={{width: '80%', height: 150}}>
    { /* render Modal content */ }
    </View.
  );
}
</code>```

Alternatively, if you need to interact with the UI behind the Modal you should use a Navigation.showOverlay

```<code>Navigation.showOverlay({
  component: {
    name: 'example.Overlay',
    options: {
      overlay: {
        interceptTouchOutside: false // this make touch events pass through the invisible parts of the overlay
      }
    }
  }
});
</code>```

For more examples on Overlay used you can see code examples in the playground app

Body:
Modal is always full screen. You can control your view's dimensions in jsx.
Instead of flex: 1 - use a predefined width and height according to your needs.

render() {
  return (
    <View style={{width: '80%', height: 150}}>
    { /* render Modal content */ }
    </View.
  );
}

Alternatively, if you need to interact with the UI behind the Modal you should use a Navigation.showOverlay

Navigation.showOverlay({
  component: {
    name: 'example.Overlay',
    options: {
      overlay: {
        interceptTouchOutside: false // this make touch events pass through the invisible parts of the overlay
      }
    }
  }
});

For more examples on Overlay used you can see code examples in the playground app


问:
How to Unit Test locale-specific local notifications
I have just added local notifications to my app. These notifications are supposed to fire only if the app Locale's regionCode (i.e. Locale.current.regionCode) is "US" or "CA". I am not interested in the locale's language.

I will also want to write the complementary test case, but once I know how to write one test case, the other will follow naturally.

Therefore, my question is: How can a Locale be injected into the test (see testSuccessfulNotificationDelivery())?

LocalNotificationTests.swift:

```<code>class LocalNotificationTests: XCTestCase {

    let notification1 = LocalNotification(toTriggerInSeconds: 5)
    let notification2 = LocalNotification(toTriggerInSeconds: 6)

    // This object manages LocalNotifications
    // by building them into UNUserNotifications
    // and then scheduling them using UNUserNotificationCenter.
    let notificationManager = NotificationManager()

    func testSuccessfulNotificationDelivery() {

        // setup locale and use it for testing, somehow
        let  = Locale(identifier: "en_CA")

        // The answer to my question would go here.
        // (Inject Locale into the test, somehow?)

        notificationManager.schedule(notifications: [notification1, notification2],
                                     withRegionCode: .regionCode)

        let expectation = self.expectation(description: "notification delivery")

        var deliveredNotifications: [UNNotification]?

        UNUserNotificationCenter.current().getDeliveredNotifications {
            deliveredNotifications = $0
            expectation.fulfill()
        }

        waitForExpectations(timeout: 10, handler: nil)

        XCTAssertEqual(deliveredNotifications?.count, 2)
    }
}
</code>```

Assume default setup() and tearDown().

答:
I am not sure if you can do that with "XCTest", but I am sure you can do this with "XCUITest". You can probably do it something like this?

```<code>class CALocalNotificationTests: LocalNotificationTests {
    override func setUp() {
        super.setUp()

        let app = XCUIApplication()
        app.launchArguments = ["-AppleLocale", "en_CA"]
        app.launch()
    }

    func testSuccessfulNotificationDelivery() {
        testSuccessfulNotificationDelivery(with: Locale(identifier: "en_CA"))
    }
}

class LocalNotificationTests: XCTestCase {

    let notification1 = LocalNotification(toTriggerInSeconds: 5)
    let notification2 = LocalNotification(toTriggerInSeconds: 6)
//
//    // This object manages LocalNotifications
//    // by building them into UNUserNotifications
//    // and then scheduling them using UNUserNotificationCenter.
    let notificationManager = NotificationManager()

    func testSuccessfulNotificationDelivery(with locale: Locale) {

        notificationManager.schedule(notifications: [notification1, notification2],
                                     withRegionCode: locale.regionCode)

        let expectation = self.expectation(description: "notification delivery")

        var deliveredNotifications: [UNNotification]?

        UNUserNotificationCenter.current().getDeliveredNotifications {
            deliveredNotifications = $0
            expectation.fulfill()
        }

        waitForExpectations(timeout: 10, handler: nil)

        XCTAssertEqual(deliveredNotifications?.count, 2)
    }
}

</code>```

I think it's quite trivial but app.launchArguments = ["-AppleLocale", "en_CA"] is the key.

You can create different test (sub)classes for different locales.

Body:
I have just added local notifications to my app. These notifications are supposed to fire only if the app Locale's regionCode (i.e. Locale.current.regionCode) is "US" or "CA". I am not interested in the locale's language.

I will also want to write the complementary test case, but once I know how to write one test case, the other will follow naturally.

Therefore, my question is: How can a Locale be injected into the test (see testSuccessfulNotificationDelivery())?

LocalNotificationTests.swift:

class LocalNotificationTests: XCTestCase {

    let notification1 = LocalNotification(toTriggerInSeconds: 5)
    let notification2 = LocalNotification(toTriggerInSeconds: 6)

    // This object manages LocalNotifications
    // by building them into UNUserNotifications
    // and then scheduling them using UNUserNotificationCenter.
    let notificationManager = NotificationManager()

    func testSuccessfulNotificationDelivery() {

        // setup locale and use it for testing, somehow
        let  = Locale(identifier: "en_CA")

        // The answer to my question would go here.
        // (Inject Locale into the test, somehow?)

        notificationManager.schedule(notifications: [notification1, notification2],
                                     withRegionCode: .regionCode)

        let expectation = self.expectation(description: "notification delivery")

        var deliveredNotifications: [UNNotification]?

        UNUserNotificationCenter.current().getDeliveredNotifications {
            deliveredNotifications = $0
            expectation.fulfill()
        }

        waitForExpectations(timeout: 10, handler: nil)

        XCTAssertEqual(deliveredNotifications?.count, 2)
    }
}

Assume default setup() and tearDown().

Body:
I am not sure if you can do that with "XCTest", but I am sure you can do this with "XCUITest". You can probably do it something like this?

class CALocalNotificationTests: LocalNotificationTests {
    override func setUp() {
        super.setUp()

        let app = XCUIApplication()
        app.launchArguments = ["-AppleLocale", "en_CA"]
        app.launch()
    }

    func testSuccessfulNotificationDelivery() {
        testSuccessfulNotificationDelivery(with: Locale(identifier: "en_CA"))
    }
}

class LocalNotificationTests: XCTestCase {

    let notification1 = LocalNotification(toTriggerInSeconds: 5)
    let notification2 = LocalNotification(toTriggerInSeconds: 6)
//
//    // This object manages LocalNotifications
//    // by building them into UNUserNotifications
//    // and then scheduling them using UNUserNotificationCenter.
    let notificationManager = NotificationManager()

    func testSuccessfulNotificationDelivery(with locale: Locale) {

        notificationManager.schedule(notifications: [notification1, notification2],
                                     withRegionCode: locale.regionCode)

        let expectation = self.expectation(description: "notification delivery")

        var deliveredNotifications: [UNNotification]?

        UNUserNotificationCenter.current().getDeliveredNotifications {
            deliveredNotifications = $0
            expectation.fulfill()
        }

        waitForExpectations(timeout: 10, handler: nil)

        XCTAssertEqual(deliveredNotifications?.count, 2)
    }
}

I think it's quite trivial but app.launchArguments = ["-AppleLocale", "en_CA"] is the key.

You can create different test (sub)classes for different locales.


问:
how to pass a match object from re.sub as an argument
I'm using re.sub to look for a pattern and replace the matches, with the replacement being conditional based on the match. How do I pass the match as an argument? python-3.7

I've successfully passed 'match' if I use the following:

```<code>string = re.sub(r"{(.*?)}", replaceVar, string)
</code>```

But this method doesn't allow me to pass additional arguments, which is what I need to do.

```<code>import re

def matchVar(match, another_argument):
    if match.group(1) == another_argument:
        return f'{{{another_argument}}}'
    else:
        return f'{{{another_argument}[{match.group(1)}]}}'

def replaceVar(string, another_argument):
    string = re.sub(r"{(.*?)}", matchVar(match, another_argument), string)
    return string

string = 'This is a {x} sentence. This is another {y} sentence.'
another_argument = 'x'
string = replaceVar(string, another_argument)
print(string)
</code>```

The string should result in

```<code>'This is a {x} sentence. This is another {x[y]} sentence.'
</code>```

But instead I'm receiving an error 'NameError: name 'match' is not defined'.

(I understand 'match' isn't defined. I'm not sure how to define 'match'.)

How do I pass 'match' as an argument? Thanks!

答:
You have to use lambda and pass the match

```<code>string = re.sub(r"{(.*?)}", lambda match :matchVar(match, another_argument), string)
</code>```

Or change the matchVar to def matchVar(match):
and pass the function like re.sub(r"{(.*?)}", matchVar, string)

Body:
I'm using re.sub to look for a pattern and replace the matches, with the replacement being conditional based on the match. How do I pass the match as an argument? python-3.7

I've successfully passed 'match' if I use the following:

string = re.sub(r"{(.*?)}", replaceVar, string)

But this method doesn't allow me to pass additional arguments, which is what I need to do.

import re

def matchVar(match, another_argument):
    if match.group(1) == another_argument:
        return f'{{{another_argument}}}'
    else:
        return f'{{{another_argument}[{match.group(1)}]}}'

def replaceVar(string, another_argument):
    string = re.sub(r"{(.*?)}", matchVar(match, another_argument), string)
    return string

string = 'This is a {x} sentence. This is another {y} sentence.'
another_argument = 'x'
string = replaceVar(string, another_argument)
print(string)

The string should result in

'This is a {x} sentence. This is another {x[y]} sentence.'

But instead I'm receiving an error 'NameError: name 'match' is not defined'.

(I understand 'match' isn't defined. I'm not sure how to define 'match'.)

How do I pass 'match' as an argument? Thanks!

Body:
You have to use lambda and pass the match

string = re.sub(r"{(.*?)}", lambda match :matchVar(match, another_argument), string)

Or change the matchVar to def matchVar(match):
and pass the function like re.sub(r"{(.*?)}", matchVar, string)


问:
Unable to delete some csv file conditionally
I've written a script in python to get some tabular content from a webpage and write the same in a csv file. What I wish to do now is let my script write the content in a csv file only if the table (visible as Top Mutual Fund Holders) is available in that page otherwise it will remove the csv file that has been created.

The table is avaible in this webpage.

The table I'm looking for is not available in this webpage.

This is my try:

```<code>import os
import csv
import requests
from bs4 import BeautifulSoup

url = "https://finance.yahoo.com/quote/UBER/holders?p=UBER"

def get_mutual_fund(soup):
    datalist = []
    for items in soup.select_one("h3:contains('Top Mutual Fund Holders')").find_next_sibling().select("table tr"):
        data = [item.text for item in items.select("th,td")]
        datalist.append(data)
    return datalist

def get_records(link):
    r = requests.get(link)
    soup_obj = BeautifulSoup(r.text,"lxml")
    try:
        item_one = get_mutual_fund(soup_obj)
    except AttributeError:
        item_one = ""

    if item_one:
        writer.writerows(item_one)
    else:
        os.remove("mutual_fund.csv")
    return item_one

if __name__ == '__main__':
    with open("mutual_fund.csv","w",newline="") as f:
        writer = csv.writer(f)
        for elem in get_records(url):
            print(elem)
</code>```

I've tried with the link that do not have that table. However, it throws the following error

```<code>while deleting the csv file:
Traceback (most recent call last):
  File "C:\Users\WCS\AppData\Local\Programs\Python\Python37-32\demo.py", line 33, in <module>
    for elem in get_records(url):
  File "C:\Users\WCS\AppData\Local\Programs\Python\Python37-32\demo.py", line 27, in get_records
    os.remove("mutual_fund.csv")
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'mutual_fund.csv'
</code>```

How can I delete the csv file when the tabular content is not present?

答:
If you keep your existing logic as it is and delete the file when the content within csv is nothing then the following should work:</p>

```<code>import os
import csv
import requests
from bs4 import BeautifulSoup

# url = "https://finance.yahoo.com/quote/fb/holders?p=FB"
url = "https://finance.yahoo.com/quote/UBER/holders?p=UBER"

def get_mutual_fund(soup):
    datalist = []
    for items in soup.select_one("h3:contains('Top Mutual Fund Holders')").find_next_sibling().select("table tr"):
        data = [item.text for item in items.select("th,td")]
        datalist.append(data)
    return datalist

def get_records(link):
    r = requests.get(link)
    soup_obj = BeautifulSoup(r.text,"lxml")
    try:
        item_one = get_mutual_fund(soup_obj)
    except AttributeError:
        item_one = ""

    if item_one:
        writer.writerows(item_one)
    else:
        f.close()
        os.remove('mutual_fund.csv')

if __name__ == '__main__':
    with open("mutual_fund.csv","w",newline="") as f:
        writer = csv.writer(f)
        get_records(url)
</code>```

Body:
I've written a script in python to get some tabular content from a webpage and write the same in a csv file. What I wish to do now is let my script write the content in a csv file only if the table (visible as Top Mutual Fund Holders) is available in that page otherwise it will remove the csv file that has been created.

The table is avaible in this webpage.

The table I'm looking for is not available in this webpage.

This is my try:

import os
import csv
import requests
from bs4 import BeautifulSoup

url = "https://finance.yahoo.com/quote/UBER/holders?p=UBER"

def get_mutual_fund(soup):
    datalist = []
    for items in soup.select_one("h3:contains('Top Mutual Fund Holders')").find_next_sibling().select("table tr"):
        data = [item.text for item in items.select("th,td")]
        datalist.append(data)
    return datalist

def get_records(link):
    r = requests.get(link)
    soup_obj = BeautifulSoup(r.text,"lxml")
    try:
        item_one = get_mutual_fund(soup_obj)
    except AttributeError:
        item_one = ""

    if item_one:
        writer.writerows(item_one)
    else:
        os.remove("mutual_fund.csv")
    return item_one

if __name__ == '__main__':
    with open("mutual_fund.csv","w",newline="") as f:
        writer = csv.writer(f)
        for elem in get_records(url):
            print(elem)

I've tried with the link that do not have that table. However, it throws the following error

while deleting the csv file:
Traceback (most recent call last):
  File "C:\Users\WCS\AppData\Local\Programs\Python\Python37-32\demo.py", line 33, in <module>
    for elem in get_records(url):
  File "C:\Users\WCS\AppData\Local\Programs\Python\Python37-32\demo.py", line 27, in get_records
    os.remove("mutual_fund.csv")
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'mutual_fund.csv'

How can I delete the csv file when the tabular content is not present?

Body:
If you keep your existing logic as it is and delete the file when the content within csv is nothing then the following should work:

import os
import csv
import requests
from bs4 import BeautifulSoup

# url = "https://finance.yahoo.com/quote/fb/holders?p=FB"
url = "https://finance.yahoo.com/quote/UBER/holders?p=UBER"

def get_mutual_fund(soup):
    datalist = []
    for items in soup.select_one("h3:contains('Top Mutual Fund Holders')").find_next_sibling().select("table tr"):
        data = [item.text for item in items.select("th,td")]
        datalist.append(data)
    return datalist

def get_records(link):
    r = requests.get(link)
    soup_obj = BeautifulSoup(r.text,"lxml")
    try:
        item_one = get_mutual_fund(soup_obj)
    except AttributeError:
        item_one = ""

    if item_one:
        writer.writerows(item_one)
    else:
        f.close()
        os.remove('mutual_fund.csv')

if __name__ == '__main__':
    with open("mutual_fund.csv","w",newline="") as f:
        writer = csv.writer(f)
        get_records(url)


问:
Reading intended recipient from Undeliverable emails via Interop for Outlook
I've created an application, which is used to loop through the emails in an inbox and find all the undeliverable, mailbox full or delayed emails and generate a report.

The usual routine is to loop through all the emails in the inbox (up to a specified date).

If an email is undeliverable use regex to find the email. This works 95% of the time as this information is contained in the body of the Undelivered message (ReportItem).

So, my problem is I have a few emails which are returning blank emails to the report making it nigh on impossible to clean them or easily report that we have a problem with someone's email.

I have found that the information in the Internet Headers has who the mail was intended for, but cannot find anything on if it is possible to use an interop or some other object to obtain this information.

If anyone else has come across this problem and knows of a work around I would be very grateful.

Cheers

答:
I was looking to automate an outlook mail box to move all undelivered emails and store the email address of the recipient of the undeliverable message in a list, so that I can later check if an entry of the list is present in an excel column and then remove it from the excel. I hope this helps !
I've found a Python solution for this problem. A python library that is used to connect to the outlook is win32com, so first we import all libraries that we will need:

```<code>import win32com.client
import re
import datetime as dt
from tqdm import tqdm
import time
import extract_msg
</code>```

This is a good way to connect to a specific outlook account, if you have :

```<code>outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
accounts= win32com.client.Dispatch("Outlook.Application").Session.Accounts
</code>```

Then create a loop that iterates through the whole outlook and gets to the specified mail account:

```<code>for account in accounts:
    inbox = outlook.Folders(account.DeliveryStore.DisplayName)
    if account.DeliveryStore.DisplayName == 'place_your_account_name_here':
            for folder in inbox.Folders:
</code>```

Find the folder in outlook you wish to check by folder name,
so if you would want to iterate through Inbox, type "Inbox" instead of "Folder_name"

```<code>if folder.__str__() == "Folder_name":
    messages = folder.Items
    messages.Sort('[ReceivedTime]', True)
    if folder.Folders.Item('Undeliverable'):
        undeliverable = folder.Folders.Item('Undeliverable')

    list_of_undelivered_email_addresses = my_super_function(messages,undeliverable)
</code>```

After we have reached the mail items and declared the undeliverable subfolder as "undeliverable", we specify the time period for which we want to do the below function:

```<code>def my_super_function(messages,undeliverable):

    list_of_undelivered_email_addresses = []

    last_n_days = dt.datetime.now() - dt.timedelta(days = 25)

    messages = messages.Restrict("[ReceivedTime] >= '" +last_n_days.strftime('%m/%d/%Y %H:%M %p')+"'")

    rl= list()
</code>```

I have found that the msot popular times of undeliverable email addresses present some sort of an error, and below the error is the original version of the email I have sent. Most of them (with very few exceptions, have a line that says:
To: "Some_email_address" ....
This is why I used this regular expression to get read the whole line after my pattern (which is "To: "")

```<code>    pattern = re.compile('To: ".*\n?',re.MULTILINE)

    for counter, message in enumerate(messages):
</code>```

It is very important that you save the email somewhere on your PC, because otherwise as soon as you read it's body, the email gets encrypted.

```<code> message.SaveAs("undeliverable_emails.msg")
            f = r'specify_the_absolute_path_where_you_want_it_saved'
            try:
                    msg = extract_msg.Message(f)
                    print(counter)
</code>```

Search the saved msg body for the keyword Undeliverable:

```<code>                    if msg.body.find("undeliverable")!= -1 or msg.body.find("Undeliverable")!= -1 or msg.subject.find("Undeliverable")!= -1 or msg.subject.find("undeliverable")!= -1 or msg.body.find("wasn't found at")!= -1:
</code>```

Save the actual email to a list, so you can move it to the undeliverables subfolder later

```<code>rl.append(message)

                            m = re.search(pattern, msg.body)
                            m = m[0]

                            mail_final = m.split('"')[1]

                            list_of_undelivered_email_addresses.append(mail_final)
                            list_of_undelivered_email_addresses=list(filter(None, list_of_undelivered_email_addresses))

                    else:
                            print('this email is not an undeliverable one')
            except:
                    pass
</code>```

Move all mails in the list to the undeliverables folder:

```<code>if len(rl) ==0:
            pass
    else:
            for m in tqdm(rl):
                    m.Move(undeliverable)

    return list_of_undelivered_email_addresses
</code>```

Here is the full code:

```<code>import win32com.client
import re
import datetime as dt
from tqdm import tqdm #tqdm gives you the progress bar
import time
import extract_msg

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
accounts= win32com.client.Dispatch("Outlook.Application").Session.Accounts

def my_super_function(messages,undeliverable):
        list_of_undelivered_email_addresses = []
        last_n_days = dt.datetime.now() - dt.timedelta(days = 25)
        messages = messages.Restrict("[ReceivedTime] >= '" +last_n_days.strftime('%m/%d/%Y %H:%M %p')+"'")
        rl= list()
        pattern = re.compile('To: ".*\n?',re.MULTILINE)
        for counter, message in enumerate(messages):
                message.SaveAs("undeliverable_emails.msg")
                f = r'some_absolute_path'
                try:
                        msg = extract_msg.Message(f)
                        print(counter)
                        if msg.body.find("undeliverable")!= -1 or msg.body.find("Undeliverable")!= -1 or msg.subject.find("Undeliverable")!= -1 or msg.subject.find("undeliverable")!= -1 or msg.body.find("wasn't found at")!= -1:
                                rl.append(message)
                                m = re.search(pattern, msg.body)
                                m = m[0]
                                mail_final = m.split('"')[1]
                                list_of_undelivered_email_addresses.append(mail_final)
                                list_of_undelivered_email_addresses=list(filter(None, list_of_undelivered_email_addresses))
                        else:
                                print('else')
                except:
                        pass
        if len(rl) ==0:
                pass
        else:
                for m in tqdm(rl):
                        m.Move(undeliverable)
        return list_of_undelivered_email_addresses

for account in accounts:
        inbox = outlook.Folders(account.DeliveryStore.DisplayName)
        if account.DeliveryStore.DisplayName == 'desired_email_address':
                for folder in inbox.Folders:
                        if folder.__str__() == "Inbox":
                                messages = folder.Items
                                messages.Sort('[ReceivedTime]', True)
                                if folder.Folders.Item('Undeliverable'):
                                        undeliverable = folder.Folders.Item('Undeliverable')
                                list_of_undelivered_email_addresses = my_super_function(messages,undeliverable)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I was looking to automate an outlook mail box to move all undelivered emails and store the email address of the recipient of the undeliverable message in a list, so that I can later check if an entry of the list is present in an excel column and then remove it from the excel. I hope this helps !
I've found a Python solution for this problem. A python library that is used to connect to the outlook is win32com, so first we import all libraries that we will need:

import win32com.client
import re
import datetime as dt
from tqdm import tqdm
import time
import extract_msg

This is a good way to connect to a specific outlook account, if you have :

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
accounts= win32com.client.Dispatch("Outlook.Application").Session.Accounts

Then create a loop that iterates through the whole outlook and gets to the specified mail account:

for account in accounts:
    inbox = outlook.Folders(account.DeliveryStore.DisplayName)
    if account.DeliveryStore.DisplayName == 'place_your_account_name_here':
            for folder in inbox.Folders:

Find the folder in outlook you wish to check by folder name,
so if you would want to iterate through Inbox, type "Inbox" instead of "Folder_name"

if folder.__str__() == "Folder_name":
    messages = folder.Items
    messages.Sort('[ReceivedTime]', True)
    if folder.Folders.Item('Undeliverable'):
        undeliverable = folder.Folders.Item('Undeliverable')

    list_of_undelivered_email_addresses = my_super_function(messages,undeliverable)

After we have reached the mail items and declared the undeliverable subfolder as "undeliverable", we specify the time period for which we want to do the below function:

def my_super_function(messages,undeliverable):

    list_of_undelivered_email_addresses = []

    last_n_days = dt.datetime.now() - dt.timedelta(days = 25)

    messages = messages.Restrict("[ReceivedTime] >= '" +last_n_days.strftime('%m/%d/%Y %H:%M %p')+"'")

    rl= list()

I have found that the msot popular times of undeliverable email addresses present some sort of an error, and below the error is the original version of the email I have sent. Most of them (with very few exceptions, have a line that says:
To: "Some_email_address" ....
This is why I used this regular expression to get read the whole line after my pattern (which is "To: "")

    pattern = re.compile('To: ".*\n?',re.MULTILINE)

    for counter, message in enumerate(messages):

It is very important that you save the email somewhere on your PC, because otherwise as soon as you read it's body, the email gets encrypted.

 message.SaveAs("undeliverable_emails.msg")
            f = r'specify_the_absolute_path_where_you_want_it_saved'
            try:
                    msg = extract_msg.Message(f)
                    print(counter)

Search the saved msg body for the keyword Undeliverable:

                    if msg.body.find("undeliverable")!= -1 or msg.body.find("Undeliverable")!= -1 or msg.subject.find("Undeliverable")!= -1 or msg.subject.find("undeliverable")!= -1 or msg.body.find("wasn't found at")!= -1:

Save the actual email to a list, so you can move it to the undeliverables subfolder later

rl.append(message)

                            m = re.search(pattern, msg.body)
                            m = m[0]

                            mail_final = m.split('"')[1]

                            list_of_undelivered_email_addresses.append(mail_final)
                            list_of_undelivered_email_addresses=list(filter(None, list_of_undelivered_email_addresses))

                    else:
                            print('this email is not an undeliverable one')
            except:
                    pass

Move all mails in the list to the undeliverables folder:

if len(rl) ==0:
            pass
    else:
            for m in tqdm(rl):
                    m.Move(undeliverable)

    return list_of_undelivered_email_addresses

Here is the full code:

import win32com.client
import re
import datetime as dt
from tqdm import tqdm #tqdm gives you the progress bar
import time
import extract_msg

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
accounts= win32com.client.Dispatch("Outlook.Application").Session.Accounts

def my_super_function(messages,undeliverable):
        list_of_undelivered_email_addresses = []
        last_n_days = dt.datetime.now() - dt.timedelta(days = 25)
        messages = messages.Restrict("[ReceivedTime] >= '" +last_n_days.strftime('%m/%d/%Y %H:%M %p')+"'")
        rl= list()
        pattern = re.compile('To: ".*\n?',re.MULTILINE)
        for counter, message in enumerate(messages):
                message.SaveAs("undeliverable_emails.msg")
                f = r'some_absolute_path'
                try:
                        msg = extract_msg.Message(f)
                        print(counter)
                        if msg.body.find("undeliverable")!= -1 or msg.body.find("Undeliverable")!= -1 or msg.subject.find("Undeliverable")!= -1 or msg.subject.find("undeliverable")!= -1 or msg.body.find("wasn't found at")!= -1:
                                rl.append(message)
                                m = re.search(pattern, msg.body)
                                m = m[0]
                                mail_final = m.split('"')[1]
                                list_of_undelivered_email_addresses.append(mail_final)
                                list_of_undelivered_email_addresses=list(filter(None, list_of_undelivered_email_addresses))
                        else:
                                print('else')
                except:
                        pass
        if len(rl) ==0:
                pass
        else:
                for m in tqdm(rl):
                        m.Move(undeliverable)
        return list_of_undelivered_email_addresses

for account in accounts:
        inbox = outlook.Folders(account.DeliveryStore.DisplayName)
        if account.DeliveryStore.DisplayName == 'desired_email_address':
                for folder in inbox.Folders:
                        if folder.__str__() == "Inbox":
                                messages = folder.Items
                                messages.Sort('[ReceivedTime]', True)
                                if folder.Folders.Item('Undeliverable'):
                                        undeliverable = folder.Folders.Item('Undeliverable')
                                list_of_undelivered_email_addresses = my_super_function(messages,undeliverable)


问:
max_by with multiple return columns
Presto's documentation says max_by(x, y) returns the value of x associated with the maximum value of y over all input values. (https://prestodb.github.io/docs/current/functions/aggregate.html#max_by)

How can I return multiple columns (not only x) associated with the maximum y? I found that max_by((x1, x2, x3), y) works (almost) but it returns a single column with x1, x2, x3 and I don't know how to convert it into multiple columns.

答:
Since Presto 314

As Martin Traverso pointed out, since Presto 314 there is a better option, the [] subscript operator. See Martin's answer.

For older versions, see below

(x1, x2, x3) creates a row with anonymous fields. Currently, to access individual row fields, you need to cast the value to a row with named fields:

```<code>CAST(row_value AS row(some_field field_type, other_field, field_type, ...))
</code>```

In a query this can be inside max_by or outside (doesn't matter).
Example:

```<code>presto> SELECT r.afield, r.bfield, r.cfield
     -> FROM (
     ->     SELECT max_by(CAST((x1, x2, x3) AS row(afield integer, bfield varchar, cfield double)), y) r
     ->     FROM (VALUES (1, 42, 'a', 13e0), (2, 40, 'b', 77e0)) t(y, x1, x2, x3)
     -> );
 afield | bfield | cfield
--------+--------+--------
     40 | b      |   77.0
(1 row)
</code>```

I understand this is quite verbose.
There is an issue to make this more convenient: https://github.com/prestosql/presto/issues/860.

Title: max_by with multiple return columns

Body:
Since Presto 314

As Martin Traverso pointed out, since Presto 314 there is a better option, the [] subscript operator. See Martin's answer.

For older versions, see below

(x1, x2, x3) creates a row with anonymous fields. Currently, to access individual row fields, you need to cast the value to a row with named fields:

CAST(row_value AS row(some_field field_type, other_field, field_type, ...))

In a query this can be inside max_by or outside (doesn't matter).
Example:

presto> SELECT r.afield, r.bfield, r.cfield
     -> FROM (
     ->     SELECT max_by(CAST((x1, x2, x3) AS row(afield integer, bfield varchar, cfield double)), y) r
     ->     FROM (VALUES (1, 42, 'a', 13e0), (2, 40, 'b', 77e0)) t(y, x1, x2, x3)
     -> );
 afield | bfield | cfield
--------+--------+--------
     40 | b      |   77.0
(1 row)

I understand this is quite verbose.
There is an issue to make this more convenient: https://github.com/prestosql/presto/issues/860.


问:
How to use OpenGL 2.0 rather than a later version?
The goal is to make a game which will be compatible with many Graphics cards, and cross-platform. I decided to go with OpenGL 2.0 and Glut.

I quickly came to realize however, that there are no specific DLL for version OpenGL version 1.0, 2.0, 2.1... This lead me to wonder, how exactly do you choose which OpenGL version you need?

Also, I am aware that Windows Visual Studio only comes with OpenGL version 1.1. That is why I decided to use Glut, so that I could use functions from a later version of OpenGL such as 2.0.

The question remains, how do I use a certain version of OpenGL?

答: You simply don't use any of the new features introduced since 2.0</p>


问:
Template Argument Binding
What I want is something like std::bind for functions but for templates.
Assume I have a template which needs a template template with a defined set of arguments.
Now I have another template which would work but which has more arguments, so I need to convert this complex template into a simpler one with bound arguments.

To do this I created a template which defines an alias template.

If I use this binding template with concrete types this works well. But if I instantiate the binding template with another template argument, gcc and clang assume that the alias is not a template template. I know it becomes a dependent name, but there is nothing like the typename disambiguator for templates.

With icc and msvc this works fine.

```<code>template<
    template<typename> typename Template
>
class ATypeWhichNeedsATemplateTemplate
{
};

template<typename A, typename B>
class AComplexTemplate
{
};

template<
    template<typename...> typename ATemplate
    ,typename... Args
>
class Binder {
public:
    template<typename T>
    using type = ATemplate<T, Args...>;
};

template<typename T>
class AClassWithBoundTemplate : public ATypeWhichNeedsATemplateTemplate<
    Binder<AComplexTemplate, T>::type
>
{
};
</code>```

see on godbolt

clang complains:

```<code><source>:30:5: error: template argument for template template parameter must be a class template or type alias template

    Binder<AComplexTemplate, T>::type

    ^
</code>```

gcc says something similar:

```<code><source>:31:1: error: type/value mismatch at argument 1 in template parameter list for 'template<template<class> class Template> class ATypeWhichNeedsATemplateTemplate'

 >

 ^
<source>:31:1: note:   expected a class template, got 'Binder<AComplexTemplate, T>::type'
</code>```

答:
type is a dependent template name. You need to spell it like Binder<AComplexTemplate, T>::template type, i. e.:

```<code>template<typename T>
class AClassWithBoundTemplate : public ATypeWhichNeedsATemplateTemplate<
    Binder<AComplexTemplate, T>::template type
>
{
};
</code>```

Fixed godbolt example: https://godbolt.org/z/7nJtAU

Title: Template Argument Binding

Body:
What I want is something like std::bind for functions but for templates.
Assume I have a template which needs a template template with a defined set of arguments.
Now I have another template which would work but which has more arguments, so I need to convert this complex template into a simpler one with bound arguments.

To do this I created a template which defines an alias template.

If I use this binding template with concrete types this works well. But if I instantiate the binding template with another template argument, gcc and clang assume that the alias is not a template template. I know it becomes a dependent name, but there is nothing like the typename disambiguator for templates.

With icc and msvc this works fine.

template<
    template<typename> typename Template
>
class ATypeWhichNeedsATemplateTemplate
{
};

template<typename A, typename B>
class AComplexTemplate
{
};

template<
    template<typename...> typename ATemplate
    ,typename... Args
>
class Binder {
public:
    template<typename T>
    using type = ATemplate<T, Args...>;
};

template<typename T>
class AClassWithBoundTemplate : public ATypeWhichNeedsATemplateTemplate<
    Binder<AComplexTemplate, T>::type
>
{
};

see on godbolt

clang complains:

<source>:30:5: error: template argument for template template parameter must be a class template or type alias template

    Binder<AComplexTemplate, T>::type

    ^

gcc says something similar:

<source>:31:1: error: type/value mismatch at argument 1 in template parameter list for 'template<template<class> class Template> class ATypeWhichNeedsATemplateTemplate'

 >

 ^
<source>:31:1: note:   expected a class template, got 'Binder<AComplexTemplate, T>::type'

Body:
type is a dependent template name. You need to spell it like Binder<AComplexTemplate, T>::template type, i. e.:

template<typename T>
class AClassWithBoundTemplate : public ATypeWhichNeedsATemplateTemplate<
    Binder<AComplexTemplate, T>::template type
>
{
};

Fixed godbolt example: https://godbolt.org/z/7nJtAU


问:
Border transition on click without javascript
My issue is I need to add a transition of 5sec on the border of a button when we click it without javascript.
Can anyone suggest me an idea</p>

答:
Use

:active

.btn{
  background-color: lightblue;
  padding:10px;
  border:0;
  border-radius:10px;
  cursor:pointer;
  transition: border 5s;
}

.btn:active{
  border:solid blue 5px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="btn">Button</button></code>```

Body:
Use

:active

.btn{
  background-color: lightblue;
  padding:10px;
  border:0;
  border-radius:10px;
  cursor:pointer;
  transition: border 5s;
}

.btn:active{
  border:solid blue 5px
}

<button class="btn">Button</button>