问:
Kafka Consumer diamond operator cannot infer arguments
I am creating a Kafka consumer. Mentioned piece of code is running fine on my sample POC project.

Somehow when I use this in my project application, it gives error, of not able to resolve Diamond Operator.

Project Code

```<code>private Consumer<Long, String> createConsumer(String topicName) {
    final Properties props = new Properties();
    // todo: use @Value instead of hardcodes
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "application");
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

    final Consumer<Long, String> consumer = new KafkaConsumer<>(props);
    consumer.subscribe(Collections.singletonList(topicName));
    return consumer;
}
</code>```

Error Snapshot

答:
You do not need a diamond operator in your code. Change the error line to this

```<code>KafkaConsumer consumer = new KafkaConsumer(props);
</code>```

The return type should change from Consumer<Long, String> to KafkaConsumer. Rest all code is fine and you can use the consumer as it is.

Body:
I am creating a Kafka consumer. Mentioned piece of code is running fine on my sample POC project.

Somehow when I use this in my project application, it gives error, of not able to resolve Diamond Operator.

Project Code

private Consumer<Long, String> createConsumer(String topicName) {
    final Properties props = new Properties();
    // todo: use @Value instead of hardcodes
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "application");
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

    final Consumer<Long, String> consumer = new KafkaConsumer<>(props);
    consumer.subscribe(Collections.singletonList(topicName));
    return consumer;
}

Error Snapshot

Body:
You do not need a diamond operator in your code. Change the error line to this

KafkaConsumer consumer = new KafkaConsumer(props);

The return type should change from Consumer<Long, String> to KafkaConsumer. Rest all code is fine and you can use the consumer as it is.


来源: stackexchange

问:
Unable to reach services via Azure Traffic Manager and Nginx Ingress on AKS
I have two AKS clusters as primary and secondary in two different regions.
I want to use Azure traffic manager for the the Priority based endpoint monitoring and fail-over mechanism on the primary and secondary clusters.
I got two services: A and B that routes at the relative path /service-a and /service-b respectively. I have nginx ingress controller on each cluster with PIP mapped to the custom host aks-primary.xyz.com and aks-secondary.xyz.com respectively.

The services are reachable on the below paths:

On Primary Custer:

https://aks-primary.xyz.com/service-a

https://aks-primary.xyz.com/service-b

On secondary cluster:

https://aks-secondary.xyz.com/service-a

https://aks-secondary.xyz.com/service-b

I added the primary and secondary host aks-primary.xyz.com and aks-secondary.xyz.com as the endpoint in the Azure Traffic Manager for priority based routing. I added the probe path /healthz and port 443.
My endpoints are online.

I added the custom domain for the ATM FQDN my-atm.trafficmanager.net to aks.xyz.com
I am unable to reach to my services on below paths

https://aks.xyz.com/service-a

https://aks.xyz.com/service-b

Please suggest.

答:
I got this resolved.

I added the ingress with two hosts on each cluster.

hosts: aks-primary.xyz.com and aks.xyz.com on cluster aks primary.

hosts: aks-secondary.xyz.com and aks.xyz.com on cluster aks secondary.

A sample ingress on cluster aks primary:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-with-atm
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: aks-primary.xyz.com
    http:
      paths:
      - backend:
          serviceName: service-a
          servicePort: 80
        path: /service-a
      - backend:
          serviceName: service-b
          servicePort: 80
        path: /service-b
  - host: aks.xyz.com
    http:
      paths:
      - backend:
          serviceName: service-a
          servicePort: 80
        path: /service-a
      - backend:
          serviceName: service-b
          servicePort: 80
        path: /service-b
  tls:
  - hosts:
    - aks-primary.xyz.com
    secretName: tls-secret-wildcard-for-xyz-com
  - hosts:
    - aks.xyz.com
    secretName: tls-secret-wildcard-for-xyz-com`
```

Cheers!

ContentLicense: CC BY-SA 4.0

Body:
I got this resolved.

I added the ingress with two hosts on each cluster.

hosts: aks-primary.xyz.com and aks.xyz.com on cluster aks primary.

hosts: aks-secondary.xyz.com and aks.xyz.com on cluster aks secondary.

A sample ingress on cluster aks primary:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-with-atm
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: aks-primary.xyz.com
    http:
      paths:
      - backend:
          serviceName: service-a
          servicePort: 80
        path: /service-a
      - backend:
          serviceName: service-b
          servicePort: 80
        path: /service-b
  - host: aks.xyz.com
    http:
      paths:
      - backend:
          serviceName: service-a
          servicePort: 80
        path: /service-a
      - backend:
          serviceName: service-b
          servicePort: 80
        path: /service-b
  tls:
  - hosts:
    - aks-primary.xyz.com
    secretName: tls-secret-wildcard-for-xyz-com
  - hosts:
    - aks.xyz.com
    secretName: tls-secret-wildcard-for-xyz-com`

Cheers!


问:
Load Url in Web View
I have a small problem that I want to load a url in web view but it doesn't displayed in webview, it displayed in default Android browser. How can we resist this to open in webview and one thing more that if I will use any other web url then it simply displayed in web view. This problem with only my particular url. What is the solution for that.

My url: http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1

my code:

```<code>@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.storesite);

    //Bundle bundle = getIntent().getExtras();
    WebView web = (WebView)findViewById(R.id.web_store);
    //MyWebViewClient web1 = new MyWebViewClient();
    //web1.shouldOverrideUrlLoading(web, "http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1");
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1");

}
</code>```

答:
use like this</p>

```<code> web.loadUrl("http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1");

    public class HelloWebViewClient extends WebViewClient {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

        }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Load Url in Web View

Body:
I have a small problem that I want to load a url in web view but it doesn't displayed in webview, it displayed in default Android browser. How can we resist this to open in webview and one thing more that if I will use any other web url then it simply displayed in web view. This problem with only my particular url. What is the solution for that.

My url: http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1

my code:

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.storesite);

    //Bundle bundle = getIntent().getExtras();
    WebView web = (WebView)findViewById(R.id.web_store);
    //MyWebViewClient web1 = new MyWebViewClient();
    //web1.shouldOverrideUrlLoading(web, "http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1");
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1");

}

Body:
use like this

 web.loadUrl("http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1");

    public class HelloWebViewClient extends WebViewClient {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

        }


问:
Google reCaptcha response "Uncaught (in promise) null"
I'm use reCaptcha v2 but in dev console response Uncaught (in promise) null in in any case (and moving the .reset() function)

console:

my code for recaptcha:

```<code><div class="text-xs-center" style="text-align: center; height:150px;">
    <p style="color: black;"> Complete the verification: </p>
    <div style="display: inline-block;" class="g-recaptcha" data-sitekey="xxxxxxxxxxx" data-callback="callback"></div>
</div>
</code>```

my callback function:

```<code>function callback() {
    if (grecaptcha === undefined) {
        alert('Recaptcha non definito');
        return;
    }

    var response = grecaptcha.getResponse();
    console.log(response);

    if (!response) {
        alert('Coud not get recaptcha response');
        return;
    }

    $.ajax({
    'url' : 'validate-recaptcha.php',
    'type' : 'POST',
    'data' : {
        'response' : response
    },
    'success' : function(data) {
        alert('Data: '+data);
    },
    'error' : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
    });
    grecaptcha.reset();
}
</code>```

and my validate-recaptcha.php:

```<code><?php
//debug
$fp = fopen('debug.txt', 'a');
fwrite($fp, print_r($_POST, TRUE));
fclose($fp);
//enddebug

if (empty($_POST['recaptcha'])) {
    exit('Please set recaptcha variable');
}
// validate recaptcha
$response = $_POST['recaptcha'];
$post = http_build_query(
    array (
        'response' => $response,
        'secret' => 'yoursecretkey',
        'remoteip' => $_SERVER['REMOTE_ADDR']
    )
);
$opts = array('http' =>
    array (
        'method' => 'POST',
        'header' => 'application/x-www-form-urlencoded',
        'content' => $post
    )
);
$context = stream_context_create($opts);
$serverResponse = @file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
if (!$serverResponse) {
    exit('Failed to validate Recaptcha');
}
$result = json_decode($serverResponse);
if (!$result -> success) {
    exit('Invalid Recaptcha');
}
exit('Recaptcha Validated');
</code>```

Searching on the internet, probably the problem is the .reset() function, but I do not understand the solution.

答: I was using ASP.NET Core 3.1 Identity, I had this issue and solved it by updating jquery.validate.min.js and jquery.validate.unobtrusive.min.js to the latest version in _ValidationScriptsPartial.cshtml.

Body:
I'm use reCaptcha v2 but in dev console response Uncaught (in promise) null in in any case (and moving the .reset() function)

console:

my code for recaptcha:

 Complete the verification:

my callback function:

function callback() {
    if (grecaptcha === undefined) {
        alert('Recaptcha non definito');
        return;
    }

    var response = grecaptcha.getResponse();
    console.log(response);

    if (!response) {
        alert('Coud not get recaptcha response');
        return;
    }

    $.ajax({
    'url' : 'validate-recaptcha.php',
    'type' : 'POST',
    'data' : {
        'response' : response
    },
    'success' : function(data) {
        alert('Data: '+data);
    },
    'error' : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
    });
    grecaptcha.reset();
}

and my validate-recaptcha.php:

<?php
//debug
$fp = fopen('debug.txt', 'a');
fwrite($fp, print_r($_POST, TRUE));
fclose($fp);
//enddebug

if (empty($_POST['recaptcha'])) {
    exit('Please set recaptcha variable');
}
// validate recaptcha
$response = $_POST['recaptcha'];
$post = http_build_query(
    array (
        'response' => $response,
        'secret' => 'yoursecretkey',
        'remoteip' => $_SERVER['REMOTE_ADDR']
    )
);
$opts = array('http' =>
    array (
        'method' => 'POST',
        'header' => 'application/x-www-form-urlencoded',
        'content' => $post
    )
);
$context = stream_context_create($opts);
$serverResponse = @file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
if (!$serverResponse) {
    exit('Failed to validate Recaptcha');
}
$result = json_decode($serverResponse);
if (!$result -> success) {
    exit('Invalid Recaptcha');
}
exit('Recaptcha Validated');

Searching on the internet, probably the problem is the .reset() function, but I do not understand the solution.


问:
Select the value of an element by name
How to access the value of this input field that is checked by its name attribute using Javascript :

```<code><input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">
</code>```

I write this :

```<code>document.querySelector('input[name="rate"]:checked').value;
</code>```

but there is an error:

```<code>TypeError: document.querySelector(...) is null
</code>```

And I do not want to be checked any inputs by default

答:
Run a function every time the input change status changes using onchange this function, in turn, logs the value of the clicked input

var rate = document.querySelectorAll(('input[name="rate"]'))

rate.forEach( each => (each.onchange = () => (console.log(each.value))))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4"></code>```

Title: Select the value of an element by name

Body:
How to access the value of this input field that is checked by its name attribute using Javascript :

<input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">

I write this :

document.querySelector('input[name="rate"]:checked').value;

but there is an error:

TypeError: document.querySelector(...) is null

And I do not want to be checked any inputs by default

Body:
Run a function every time the input change status changes using onchange this function, in turn, logs the value of the clicked input

var rate = document.querySelectorAll(('input[name="rate"]'))

rate.forEach( each => (each.onchange = () => (console.log(each.value))))

<input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">


问:
Creating a big paragraph with clickable Text in SwiftUI
I received an assignment to fetch text from the cloud database and convert it into a Text view

the rules are as follows:
each word that starts with $ and ends with $ needs to be bold:

```<code>let str = "$random$"
let extractStr = "random"
Text(extractStr).bold()
</code>```

each word that starts with ~ and ends with ~ needs to be clickable

```<code>let str = "~random~"
let extractStr = "random"
Text(extractStr).onTapGesture { print("tapping")}
</code>```

each word that starts with % and ends with % needs to be red

```<code>let str = "%random%"
let extractStr = "random"
Text(extractStr).foregroundColor(Color.red)
</code>```

and so on. different kinds of rules.

the overall target is to combine all the text into one paragraph.

It is possible when summing the Texts views without any gestures, But when I try to sum a Textview with a tap gesture, everything falls apart

for example, I created a long text

```<code>let text1 = "$Hello$ my dear fellows. I want to provide #you# this
             %awesome% long Text. I shall $talk$ a bit more to show
             @you@ that when the text is $very very long$ , $it
             doesn’t behave as I wanted to$. \n\n Lets #investigate a
             bit more# and see how this text can behave. \n\n ~you can
             click me~ and ~you can click me also~ and if you need
             to, you have ~another clickable text~"
</code>```

and my desired outcome is this:

So this is what I tried

I converted it into an array:

```<code>let array1 = [$Hello$, my, dear, fellows., I, want, to, provide,
              #you#, this, %awesome, long, text. ......]
</code>```

after that, I did some checking and created an array of Texts:

```<code>var arrayOfText: [Text] = []
</code>```

I did some logic and ended up with this:

```<code>arrayOfText = [Text("Hello").bold(), Text("my"),
       Text("dear").underline(),
       Text("fellows."), Text("I"), Text("want"), Text("to")
       Text("provide"), Text("you").foregroundColor(.blue),
       Text("this"), Text("awesome").foregroundColor(.red),
       Text("long"), Text("text"), ... ... ...
       Text("another clickable text").onTapGesture{print("tap")}] // <-- Text with tap gesture, this is not valid...
</code>```

Now I can loop through the texts and sum them all:

```<code>var newText: Text = Text("")
for text in arrayOfText {
    newText = newText + text
}
</code>```

but It fails... I cant assign Text with tap gesture into an array of Text

I got this error:

```<code>Could not cast value of type 'SwiftUI.ModifiedContent<SwiftUI.Text, SwiftUI.AddGestureModifier<SwiftUI._EndedGesture<SwiftUI.TapGesture>>>' (0x7fc8c08e9758) to 'SwiftUI.Text' (0x7fff8166cd30).
</code>```

So I tried to do some workaround and set the array to be an array of AnyView

```<code>var arrayOfText: [AnyView] = []
</code>```

but then when I cast Text into AnyView

I receive this error:

```<code>let str = "~random~"
let extractStr = "random"
Text(extractStr).onTapGesture { print("tapping")}
</code>```0

any ideas how can I pull this off?

UPDATE

I tried using Asperi method:

```<code>let str = "~random~"
let extractStr = "random"
Text(extractStr).onTapGesture { print("tapping")}
</code>```1

}

But it doesn't work with long text. the whole views collapse on each other

This is how it looks Like:

答:
You are pushing this version of SwiftUI beyond its current capabilities!

Something like this would more easily be done using the advanced text handling in UIKit, or by thinking outside the box and converting the text to something Like HTML.

If you MUST use SwiftUI, your best bet would probably be to layout the formatted text first onto a tappable paragraph/block, and then use gesture recognition at the block level to detect where in the block the tap took place - indirectly determining if the tap position coincided with the “tappable” text.

Update #1:

Example: To use a UITextView (which supports attributed text), you could use the UIViewRepresentable protocol to wrap the UIKit view and make it accessible from within SwiftUI. e.g. Using Paul Hudson's UIViewRepresentable example for the code...

```<code>struct TextView: UIViewRepresentable {
    @Binding var text: String

    func makeUIView(context: Context) -> UITextView {
        return UITextView()
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
    }
}
</code>```

The TextView can then be used directly within SwiftUI.

Now, while Textview gives you formatting, it does not give you the clickability you need without a lot of extra work, but a WKWebView used to render an HTML version of your text would allow you to convert the clickable text into HTML links that could be handled internal to your new SwiftUI view.

Note: The reason I say that you are pushing SwiftUI to its limits is that the current version of SwiftUI hides a lot of the configurability that is exposed in UIKit and forces you to do cartwheels to get to a solution that is often already present in UIKit.

Update #2:

Here's a clickable version that uses UITextField and a NSAttributedString:

```<code>class MyTextView: UITextView, UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print(URL)

        return false
    }
}

struct SwiftUIView: UIViewRepresentable {
    @Binding var text: NSAttributedString

    func makeUIView(context: Context) -> MyTextView {
        let view = MyTextView()

        view.dataDetectorTypes = .link
        view.isEditable        = false
        view.isSelectable      = true
        view.delegate          = view

        return view
    }

    func updateUIView(_ uiView: MyTextView, context: Context) {
        uiView.attributedText = text
    }
}
</code>```

All you need to do now is convert the downloaded text into a suitable attributed string format and you have attributed formatting and clickability

Body:
I received an assignment to fetch text from the cloud database and convert it into a Text view

the rules are as follows:
each word that starts with $ and ends with $ needs to be bold:

let str = "$random$"
let extractStr = "random"
Text(extractStr).bold()

each word that starts with ~ and ends with ~ needs to be clickable

let str = "~random~"
let extractStr = "random"
Text(extractStr).onTapGesture { print("tapping")}

each word that starts with % and ends with % needs to be red

let str = "%random%"
let extractStr = "random"
Text(extractStr).foregroundColor(Color.red)

and so on. different kinds of rules.

the overall target is to combine all the text into one paragraph.

It is possible when summing the Texts views without any gestures, But when I try to sum a Textview with a tap gesture, everything falls apart

for example, I created a long text

let text1 = "$Hello$ my dear fellows. I want to provide #you# this
             %awesome% long Text. I shall $talk$ a bit more to show
             @you@ that when the text is $very very long$ , $it
             doesn’t behave as I wanted to$. \n\n Lets #investigate a
             bit more# and see how this text can behave. \n\n ~you can
             click me~ and ~you can click me also~ and if you need
             to, you have ~another clickable text~"

and my desired outcome is this:

So this is what I tried

I converted it into an array:

let array1 = [$Hello$, my, dear, fellows., I, want, to, provide,
              #you#, this, %awesome, long, text. ......]

after that, I did some checking and created an array of Texts:

var arrayOfText: [Text] = []

I did some logic and ended up with this:

arrayOfText = [Text("Hello").bold(), Text("my"),
       Text("dear").underline(),
       Text("fellows."), Text("I"), Text("want"), Text("to")
       Text("provide"), Text("you").foregroundColor(.blue),
       Text("this"), Text("awesome").foregroundColor(.red),
       Text("long"), Text("text"), ... ... ...
       Text("another clickable text").onTapGesture{print("tap")}] // <-- Text with tap gesture, this is not valid...

Now I can loop through the texts and sum them all:

var newText: Text = Text("")
for text in arrayOfText {
    newText = newText + text
}

but It fails... I cant assign Text with tap gesture into an array of Text

I got this error:

Could not cast value of type 'SwiftUI.ModifiedContent<SwiftUI.Text, SwiftUI.AddGestureModifier<SwiftUI._EndedGesture<SwiftUI.TapGesture>>>' (0x7fc8c08e9758) to 'SwiftUI.Text' (0x7fff8166cd30).

So I tried to do some workaround and set the array to be an array of AnyView

var arrayOfText: [AnyView] = []

but then when I cast Text into AnyView

I receive this error:

Cast from 'AnyView' to unrelated type 'Text' always fails

any ideas how can I pull this off?

UPDATE

I tried using Asperi method:

struct StringPresenter: View {
   let text1 = "hello $world$ I am %a% &new&\n\n~robot~"
   var body: some View {
       ForEach(text1.split(separator: "\n"), id: \.self) { line in
           HStack(spacing: 4) {
               ForEach(line.split(separator: " "), id: \.self) { part in
                  self.generateBlock(for: part)
               }
           }
       }
   }

   private func generateBlock(for str: Substring) -> some View {
       Group {
           if str.starts(with: "$") {
               Text(str.dropFirst().dropLast(1))
                   .bold()
           } else
           if str.starts(with: "&") {
               Text(str.dropFirst().dropLast(1))
                   .font(Font.body.smallCaps())
           } else
           if str.starts(with: "%") {
               Text(str.dropFirst().dropLast(1))
                   .italic().foregroundColor(.red)
           } else
           if str.starts(with: "~") {
               Text(str.dropFirst().dropLast(1))
                   .underline().foregroundColor(.blue).onTapGesture { print("tapping ")}
           }
           else {
               Text(str)
           }
       }
   }

}

But it doesn't work with long text. the whole views collapse on each other

This is how it looks Like:

Body:
You are pushing this version of SwiftUI beyond its current capabilities!

Something like this would more easily be done using the advanced text handling in UIKit, or by thinking outside the box and converting the text to something Like HTML.

If you MUST use SwiftUI, your best bet would probably be to layout the formatted text first onto a tappable paragraph/block, and then use gesture recognition at the block level to detect where in the block the tap took place - indirectly determining if the tap position coincided with the “tappable” text.

Update #1:

Example: To use a UITextView (which supports attributed text), you could use the UIViewRepresentable protocol to wrap the UIKit view and make it accessible from within SwiftUI. e.g. Using Paul Hudson's UIViewRepresentable example for the code...

struct TextView: UIViewRepresentable {
    @Binding var text: String

    func makeUIView(context: Context) -> UITextView {
        return UITextView()
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
    }
}

The TextView can then be used directly within SwiftUI.

Now, while Textview gives you formatting, it does not give you the clickability you need without a lot of extra work, but a WKWebView used to render an HTML version of your text would allow you to convert the clickable text into HTML links that could be handled internal to your new SwiftUI view.

Note: The reason I say that you are pushing SwiftUI to its limits is that the current version of SwiftUI hides a lot of the configurability that is exposed in UIKit and forces you to do cartwheels to get to a solution that is often already present in UIKit.

Update #2:

Here's a clickable version that uses UITextField and a NSAttributedString:

class MyTextView: UITextView, UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print(URL)

        return false
    }
}

struct SwiftUIView: UIViewRepresentable {
    @Binding var text: NSAttributedString

    func makeUIView(context: Context) -> MyTextView {
        let view = MyTextView()

        view.dataDetectorTypes = .link
        view.isEditable        = false
        view.isSelectable      = true
        view.delegate          = view

        return view
    }

    func updateUIView(_ uiView: MyTextView, context: Context) {
        uiView.attributedText = text
    }
}

All you need to do now is convert the downloaded text into a suitable attributed string format and you have attributed formatting and clickability


问:
Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
I am getting below stack trace when I am deploying my application in a multi-server Apache Tomcat 8 environment. I am getting this error frequently, and it seems it is blocking the tomcat thread:

```<code>INFO [http-nio-80-exec-4461] org.apache.coyote.http11.AbstractHttp11Processor.process Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
 java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
 at org.apache.coyote.http11.AbstractNioInputBuffer.parseRequestLine(AbstractNioInputBuffer.java:233)
 at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1017)
 at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1524)
 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1480)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
 at java.lang.Thread.run(Unknown Source)
</code>```

Can any one direct me how to troubleshoot or narrow down such an exeption? I am not getting any reference to any of my application source files. I tried to google around, and in of the links it said, you are trying to access http url through https, which seems unlikely. I am not getting this error, when the application runs on a single Tomcat 8 instance. I get this only in a multi-server environment.

I am also sharing the meta tags I have embedded on each page, if that helps to identify the cause.

<%
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");
%>

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1">
```
<p>I am also using the following in a few pages, which basically is same as above:</p>
<pre class="lang-xml prettyprint-override"><code><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Cache-Control" content="private" />
<meta http-equiv="Cache-Control" content="no-store" />
<meta http-equiv="Pragma" content="no-cache" />
</code>```

Even if anyone helps in giving a direction to my troubleshooting attempt, that will be useful, as currently I have no idea where to look into.

答: In my case I had to clear browser history/cookies to get rid of this error.</p>

Body:
I am getting below stack trace when I am deploying my application in a multi-server Apache Tomcat 8 environment. I am getting this error frequently, and it seems it is blocking the tomcat thread:

INFO [http-nio-80-exec-4461] org.apache.coyote.http11.AbstractHttp11Processor.process Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
 java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
 at org.apache.coyote.http11.AbstractNioInputBuffer.parseRequestLine(AbstractNioInputBuffer.java:233)
 at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1017)
 at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1524)
 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1480)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
 at java.lang.Thread.run(Unknown Source)

Can any one direct me how to troubleshoot or narrow down such an exeption? I am not getting any reference to any of my application source files. I tried to google around, and in of the links it said, you are trying to access http url through https, which seems unlikely. I am not getting this error, when the application runs on a single Tomcat 8 instance. I get this only in a multi-server environment.

I am also sharing the meta tags I have embedded on each page, if that helps to identify the cause.

<%
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");
%>

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1">

I am also using the following in a few pages, which basically is same as above:

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Cache-Control" content="private" />
<meta http-equiv="Cache-Control" content="no-store" />
<meta http-equiv="Pragma" content="no-cache" />

Even if anyone helps in giving a direction to my troubleshooting attempt, that will be useful, as currently I have no idea where to look into.


问:
How to add multiple rows with decreasing values into a series
I have a series of number:

```
5138
22498
42955
```

I would like add 3 numbers (decrease 1 each) to each number above:

```
5135
5136
5137
5138
22495
22496
22497
22498
42952
42953
42954
42955
```

How to do that? Thanks.

答:
I did this on python:

```<code>numbers = [5138, 22498, 42955]
for number in numbers:
    for i in reversed(range(number, number-4, -1)):
        print(i)
</code>```

Hope this helps :)

Body:
I have a series of number:

5138
22498
42955

I would like add 3 numbers (decrease 1 each) to each number above:

5135
5136
5137
5138
22495
22496
22497
22498
42952
42953
42954
42955

How to do that? Thanks.

Body:
I did this on python:

numbers = [5138, 22498, 42955]
for number in numbers:
    for i in reversed(range(number, number-4, -1)):
        print(i)

Hope this helps :)


问:
Why different local size in OpenCL gives different result?
I'm trying to perform a basic matrix multiplication algorithm using OpenCL. Both matrices are supposed to have equal dimensions (SIZE x SIZE), so I defined the problem as a bidimensional one, with global size SIZE x SIZE, and I'm testing what happens with different local sizes.

The kernel is writen as follows:

```<code>__kernel void matmul(
    __global unsigned int *a,
    __global unsigned int *b,
    __global unsigned int *c
) {
    int row, col, i, size;
    unsigned int dot;

    row = get_global_id(0);
    col = get_global_id(1);
    size = get_global_size(0);

    dot = 0;
    for (i = 0; i < size; i++) {
        dot += a[row * size + i] * b[i * size + col];
    }

    c[row * size + col] = dot;
}
</code>```

It works nice if global and local sizes are set to 1024 x 1024 and 1 x 1, respectively. However, it turns out that if the local size is 2 x 2 or 4 x 4, I get wrong results in the multiplication. Now, for local size using multiples of 8, like 8 x 8, 16 x 16, ... There is no error in the multiplication. Why is that happening?

I don't know if the problem is in the programming of the kernel, or it is that I have a bad understanding on what can be done with a work-group or work-item.

The complete host code is the following:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include <CL/opencl.h>

#define SIZE (1024)
#define WORKITEMS (4096)
#define LOG_SIZE (2048)

int main(int argc, char *argv[]) {
    int i, j, k, size, errors;

    // Host memory
    cl_uint *a_host = NULL;
    cl_uint *b_host = NULL;
    cl_uint *c_host = NULL;
    cl_uint ref_dot;

    // Device memory
    cl_mem a_device;
    cl_mem b_device;
    cl_mem c_device;

    // Performance measurements
    struct timeval t0, tf;
    float ts, tp, tb;

    // OpenCL variables
    FILE *f;
    size_t f_size;
    size_t global[3] = {0}, local[3] = {0};
    char *buffer = NULL;
    cl_int ret;
    cl_platform_id platform;
    cl_device_id device;
    cl_context context;
    cl_command_queue queue;
    cl_program program;
    cl_kernel kernel;

    // [1] Initialize application

    // Read command line arguments to configure run
    size = (argc > 1) ? atoi(argv[1]) : SIZE;
    printf("Matrix multiplication with OpenCL (Size = %d)\n", size);

    // Allocate memory for host variables
    a_host = malloc(size * size * sizeof *a_host);
    b_host = malloc(size * size * sizeof *b_host);
    c_host = malloc(size * size * sizeof *c_host);

    // Initialize input arrays
    for (i = 0; i < size; i++) {
        for (j = 0; j < size; j++) {
            a_host[i * size + j] = rand();
            b_host[i * size + j] = rand();
        }
    }

    // [2] Initialize OpenCL environment

    // Get platform
    ret = clGetPlatformIDs(1, &platform, NULL);
    // Get device
    ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_CPU, 1, &device, NULL);

    // Create context
    context = clCreateContext(0, 1, &device, NULL, NULL, &ret);

    // Create command queue
    queue = clCreateCommandQueueWithProperties(context, device, 0, &ret);

    // [3] Compile OpenCL kernel
    f = fopen("kernel.cl", "rb");
    fseek(f, 0, SEEK_END);
    f_size = ftell(f);
    rewind(f);

    // Read file into memory
    buffer = malloc(f_size + 1);
    buffer[f_size] = '\0';
    fread(buffer, sizeof(char), f_size, f);
    fclose(f);

    // Create program
    printf("<OpenCL> Kernel source:\n%s", buffer);
    program = clCreateProgramWithSource(context, 1, (const char **) &buffer, &f_size, &ret);

    // Build program
    printf("<OpenCL> Building kernel...\n");
    gettimeofday(&t0, NULL);
    ret = clBuildProgram(program, 0, NULL, "-cl-std=CL2.0", NULL, NULL);
    gettimeofday(&tf, NULL);
    tb = ((tf.tv_sec - t0.tv_sec) * 1000.0) + ((tf.tv_usec - t0.tv_usec) / 1000.0);
    printf("Build time: %.3f ms\n", tb);

    // Print build log (optional)
    char log[LOG_SIZE];
    ret = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, LOG_SIZE, log, NULL);
    printf("<OpenCL> Kernel build log:\n%s\n", log);

    // [4] Configure OpenCL kernel

    // Create kernel
    kernel = clCreateKernel(program, "matmul", &ret);

    // Create device buffers
    a_device = clCreateBuffer(context, CL_MEM_READ_ONLY, size * size * sizeof *a_host, NULL, &ret);
    b_device = clCreateBuffer(context, CL_MEM_READ_ONLY, size * size * sizeof *b_host, NULL, &ret);
    c_device = clCreateBuffer(context, CL_MEM_WRITE_ONLY, size * size * sizeof *c_host, NULL, &ret);

    // Set kernel parameters
    ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), &a_device);
    ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_device);
    ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &c_device);

    // [5] Execute kernel
    printf("<OpenCL> Executing kernel...\n");
    gettimeofday(&t0, NULL);

    // Write data from host to device
    ret = clEnqueueWriteBuffer(queue, a_device, CL_TRUE, 0, size * size * sizeof *a_host, a_host, 0, NULL, NULL);
    ret |= clEnqueueWriteBuffer(queue, b_device, CL_TRUE, 0, size * size * sizeof *b_host, b_host, 0, NULL, NULL);

    // Enqueue kernel for execution
    global[0] = size;
    global[1] = size;
    local[0] = 2;
    local[1] = 2;
    ret = clEnqueueNDRangeKernel(queue, kernel, 2, NULL, global, local, 0, NULL, NULL);

    // Wait for kernel to finish
    ret = clFinish(queue);

    // Read data from device to host
    ret = clEnqueueReadBuffer(queue, c_device, CL_TRUE, 0, size * size * sizeof *c_host, c_host, 0, NULL, NULL);

    gettimeofday(&tf, NULL);
    tp = ((tf.tv_sec - t0.tv_sec) * 1000.0) + ((tf.tv_usec - t0.tv_usec) / 1000.0);
    printf("[PAR] Execution time: %.3f ms\n", tp);

    // [6] Print results, perform checks

    // Compute golden reference and check errors

    gettimeofday(&t0, NULL);
    errors = 0;

    for (i = 0; i < size; i++) {
        for (j = 0; j < size; j++) {
            ref_dot = 0;
            for (k = 0; k < size; k++) {
                ref_dot += a_host[i * size + k] * b_host[k * size + j];
            }

            if (ref_dot != c_host[i * size + j]) {
                errors++;
            }
        }
    }

    gettimeofday(&tf, NULL);
    ts = ((tf.tv_sec - t0.tv_sec) * 1000.0) + ((tf.tv_usec - t0.tv_usec) / 1000.0);
    printf("[SEQ] Execution time : %.3f ms\n", ts);
    printf("Found %d error%s\n", errors, (errors == 1) ? "" : "s");

    // [7] Cleanup system

    // Cleanup host variables
    free(a_host);
    free(b_host);
    free(c_host);
    free(buffer);

    // Cleanup OpenCL
    clReleaseMemObject(a_device);
    clReleaseMemObject(b_device);
    clReleaseMemObject(c_device);
    clReleaseKernel(kernel);
    clReleaseProgram(program);
    clReleaseCommandQueue(queue);
    clReleaseContext(context);

    return 0;
}
</code>```

答:
The global range has to be an exact multiple of the local range. If this is not the case, the GPU may read from or write to an undefined memory region (if not explicitly caught in the kernel with an if(rwo>=SIZE||col>SIZE) return;* in the beginning of the kernel before any memory loads/stores).

* This is branching should be avoided for performance reasons.

GPU threads operate in groups of 32 (warps), so the local range should be at least 32 or a multiple thereof. If the local range is for example only 16, then half of each warp will idle, halving the available processing power. The minimum size that works for you is 8x8=64 > 32.

Example in 1D:

global range 64, local range 32: thread block 1 does items 0-31, thread block 2 does items 32-63. Everything works properly.

global range 64, local range 40: thread block 1 does items 0-39, thread block 2 does items 40-79. Thread block 2 operates in an undefined memory region with items 64-79. The compiler will not warn you, but you will eventually see incorrect results.

Similarly to the second example, I suspect some of the remaining threads of a warp operate in an undefined memory region when your local range is smaller than 32, for example with the local range 4x4=16 < 32.

Body:
I'm trying to perform a basic matrix multiplication algorithm using OpenCL. Both matrices are supposed to have equal dimensions (SIZE x SIZE), so I defined the problem as a bidimensional one, with global size SIZE x SIZE, and I'm testing what happens with different local sizes.

The kernel is writen as follows:

__kernel void matmul(
    __global unsigned int *a,
    __global unsigned int *b,
    __global unsigned int *c
) {
    int row, col, i, size;
    unsigned int dot;

    row = get_global_id(0);
    col = get_global_id(1);
    size = get_global_size(0);

    dot = 0;
    for (i = 0; i < size; i++) {
        dot += a[row * size + i] * b[i * size + col];
    }

    c[row * size + col] = dot;
}

It works nice if global and local sizes are set to 1024 x 1024 and 1 x 1, respectively. However, it turns out that if the local size is 2 x 2 or 4 x 4, I get wrong results in the multiplication. Now, for local size using multiples of 8, like 8 x 8, 16 x 16, ... There is no error in the multiplication. Why is that happening?

I don't know if the problem is in the programming of the kernel, or it is that I have a bad understanding on what can be done with a work-group or work-item.

The complete host code is the following:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include <CL/opencl.h>

#define SIZE (1024)
#define WORKITEMS (4096)
#define LOG_SIZE (2048)

int main(int argc, char *argv[]) {
    int i, j, k, size, errors;

    // Host memory
    cl_uint *a_host = NULL;
    cl_uint *b_host = NULL;
    cl_uint *c_host = NULL;
    cl_uint ref_dot;

    // Device memory
    cl_mem a_device;
    cl_mem b_device;
    cl_mem c_device;

    // Performance measurements
    struct timeval t0, tf;
    float ts, tp, tb;

    // OpenCL variables
    FILE *f;
    size_t f_size;
    size_t global[3] = {0}, local[3] = {0};
    char *buffer = NULL;
    cl_int ret;
    cl_platform_id platform;
    cl_device_id device;
    cl_context context;
    cl_command_queue queue;
    cl_program program;
    cl_kernel kernel;

    // [1] Initialize application

    // Read command line arguments to configure run
    size = (argc > 1) ? atoi(argv[1]) : SIZE;
    printf("Matrix multiplication with OpenCL (Size = %d)\n", size);

    // Allocate memory for host variables
    a_host = malloc(size * size * sizeof *a_host);
    b_host = malloc(size * size * sizeof *b_host);
    c_host = malloc(size * size * sizeof *c_host);

    // Initialize input arrays
    for (i = 0; i < size; i++) {
        for (j = 0; j < size; j++) {
            a_host[i * size + j] = rand();
            b_host[i * size + j] = rand();
        }
    }

    // [2] Initialize OpenCL environment

    // Get platform
    ret = clGetPlatformIDs(1, &platform, NULL);
    // Get device
    ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_CPU, 1, &device, NULL);

    // Create context
    context = clCreateContext(0, 1, &device, NULL, NULL, &ret);

    // Create command queue
    queue = clCreateCommandQueueWithProperties(context, device, 0, &ret);

    // [3] Compile OpenCL kernel
    f = fopen("kernel.cl", "rb");
    fseek(f, 0, SEEK_END);
    f_size = ftell(f);
    rewind(f);

    // Read file into memory
    buffer = malloc(f_size + 1);
    buffer[f_size] = '\0';
    fread(buffer, sizeof(char), f_size, f);
    fclose(f);

    // Create program
    printf("<OpenCL> Kernel source:\n%s", buffer);
    program = clCreateProgramWithSource(context, 1, (const char **) &buffer, &f_size, &ret);

    // Build program
    printf("<OpenCL> Building kernel...\n");
    gettimeofday(&t0, NULL);
    ret = clBuildProgram(program, 0, NULL, "-cl-std=CL2.0", NULL, NULL);
    gettimeofday(&tf, NULL);
    tb = ((tf.tv_sec - t0.tv_sec) * 1000.0) + ((tf.tv_usec - t0.tv_usec) / 1000.0);
    printf("Build time: %.3f ms\n", tb);

    // Print build log (optional)
    char log[LOG_SIZE];
    ret = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, LOG_SIZE, log, NULL);
    printf("<OpenCL> Kernel build log:\n%s\n", log);

    // [4] Configure OpenCL kernel

    // Create kernel
    kernel = clCreateKernel(program, "matmul", &ret);

    // Create device buffers
    a_device = clCreateBuffer(context, CL_MEM_READ_ONLY, size * size * sizeof *a_host, NULL, &ret);
    b_device = clCreateBuffer(context, CL_MEM_READ_ONLY, size * size * sizeof *b_host, NULL, &ret);
    c_device = clCreateBuffer(context, CL_MEM_WRITE_ONLY, size * size * sizeof *c_host, NULL, &ret);

    // Set kernel parameters
    ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), &a_device);
    ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_device);
    ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &c_device);

    // [5] Execute kernel
    printf("<OpenCL> Executing kernel...\n");
    gettimeofday(&t0, NULL);

    // Write data from host to device
    ret = clEnqueueWriteBuffer(queue, a_device, CL_TRUE, 0, size * size * sizeof *a_host, a_host, 0, NULL, NULL);
    ret |= clEnqueueWriteBuffer(queue, b_device, CL_TRUE, 0, size * size * sizeof *b_host, b_host, 0, NULL, NULL);

    // Enqueue kernel for execution
    global[0] = size;
    global[1] = size;
    local[0] = 2;
    local[1] = 2;
    ret = clEnqueueNDRangeKernel(queue, kernel, 2, NULL, global, local, 0, NULL, NULL);

    // Wait for kernel to finish
    ret = clFinish(queue);

    // Read data from device to host
    ret = clEnqueueReadBuffer(queue, c_device, CL_TRUE, 0, size * size * sizeof *c_host, c_host, 0, NULL, NULL);

    gettimeofday(&tf, NULL);
    tp = ((tf.tv_sec - t0.tv_sec) * 1000.0) + ((tf.tv_usec - t0.tv_usec) / 1000.0);
    printf("[PAR] Execution time: %.3f ms\n", tp);

    // [6] Print results, perform checks

    // Compute golden reference and check errors

    gettimeofday(&t0, NULL);
    errors = 0;

    for (i = 0; i < size; i++) {
        for (j = 0; j < size; j++) {
            ref_dot = 0;
            for (k = 0; k < size; k++) {
                ref_dot += a_host[i * size + k] * b_host[k * size + j];
            }

            if (ref_dot != c_host[i * size + j]) {
                errors++;
            }
        }
    }

    gettimeofday(&tf, NULL);
    ts = ((tf.tv_sec - t0.tv_sec) * 1000.0) + ((tf.tv_usec - t0.tv_usec) / 1000.0);
    printf("[SEQ] Execution time : %.3f ms\n", ts);
    printf("Found %d error%s\n", errors, (errors == 1) ? "" : "s");

    // [7] Cleanup system

    // Cleanup host variables
    free(a_host);
    free(b_host);
    free(c_host);
    free(buffer);

    // Cleanup OpenCL
    clReleaseMemObject(a_device);
    clReleaseMemObject(b_device);
    clReleaseMemObject(c_device);
    clReleaseKernel(kernel);
    clReleaseProgram(program);
    clReleaseCommandQueue(queue);
    clReleaseContext(context);

    return 0;
}


问:
How to make a discord bot that gives a role on a command
I already know the basics like commands but I couldn't figure this out. I was looking at other answers and they didn't make sense. Here's my code (without the bot token in the const token):

const Discord = require('discord.js');
const bot = new Discord.Client();

const token = 'token';
const PREFIX = '!';

bot.on('ready', () => {
  console.log('This bot is online!')
})

bot.on('message', message => {
  let args = message.content.substring(PREFIX.length).split(" ");

  switch (args[0]) {
    case 'ping':
      message.channel.send('pong!')
      break;
  }
})

bot.login(token);
```

答:
You can try doing this :

switch (args[0]) {
  case 'role':
    var role = message.guild.roles.cache.find(role => role.name === "rolename");
    message.member.roles.add(role);
    break;
}
```

This example adds a role to the message author.

Body:
You can try doing this :

switch (args[0]) {
  case 'role':
    var role = message.guild.roles.cache.find(role => role.name === "rolename");
    message.member.roles.add(role);
    break;
}

This example adds a role to the message author.


问:
How can I perform a insertion sort based on the lvalue of a dictionary
```<code>item_data = {1:[11,21,31,41],
             3:[13,23,33,43],
             5:[15,25,35,45],
             2:[12,22,32,42],
             4:[14,24,34,44],
             14:[14,14,14,14]}

def insertion_sort():
    #insertion sort
</code>```

I am trying to perform a insertion sort base on the value: item_data[key][1]

but i have no idea how to do it

A complete newbie here asking for some help

答:
Make a function to do this comparison key[i-1]  > key[i].

Then:

```<code>...
while firstArrayIsgreater(key[i], key[i-1]) and i > 0:
                key[i-1],key[i] = key[i],key[i-1]
                i-=1
...
</code>```

Body:
item_data = {1:[11,21,31,41],
             3:[13,23,33,43],
             5:[15,25,35,45],
             2:[12,22,32,42],
             4:[14,24,34,44],
             14:[14,14,14,14]}

def insertion_sort():
    #insertion sort

I am trying to perform a insertion sort base on the value: item_data[key][1]

but i have no idea how to do it

A complete newbie here asking for some help

Body:
Make a function to do this comparison key[i-1]  > key[i].

Then:

...
while firstArrayIsgreater(key[i], key[i-1]) and i > 0:
                key[i-1],key[i] = key[i],key[i-1]
                i-=1
...


问:
Keystore file does not exist
I'm trying to use the Google Maps API in one of my projects and in the directions to set up the API credentials it wants me to add my application's SHA-1 signing-certificate fingerprint to the API.

In the instructions, it says to use the following command to get the fingerprint:

```<code>keytool -list -v -keystore mystore.keystore
</code>```

When I try to use it, both in the Android Studio terminal as well as cmd prompt in my application's directory I get the following error:

```<code>keytool error: java.lang.Exception: Keystore file does not exist: C:\Users\Name\.keystore
</code>```

Note, my application is in D:\Projects\Android\AppName.

How do I get my SHA-1 signing-certificate to use with the Google Maps API?

答:
Following will give you SHA1, SHA256, MD5 for default debug key.
And it can be used for developing and debugging with google play services.

Linux & Mac command

```<code>keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
</code>```

Windows

```<code>keytool -exportcert -keystore C:\Users\<USERNAME>\.android\debug.keystore -list -v
</code>```

Replace  with your windows account name example:

```<code>keytool -exportcert -keystore C:\Users\Aakash\.android\debug.keystore -list -v
</code>```

Title: Keystore file does not exist

Body:
I'm trying to use the Google Maps API in one of my projects and in the directions to set up the API credentials it wants me to add my application's SHA-1 signing-certificate fingerprint to the API.

In the instructions, it says to use the following command to get the fingerprint:

keytool -list -v -keystore mystore.keystore

When I try to use it, both in the Android Studio terminal as well as cmd prompt in my application's directory I get the following error:

keytool error: java.lang.Exception: Keystore file does not exist: C:\Users\Name\.keystore

Note, my application is in D:\Projects\Android\AppName.

How do I get my SHA-1 signing-certificate to use with the Google Maps API?

Body:
Following will give you SHA1, SHA256, MD5 for default debug key.
And it can be used for developing and debugging with google play services.

Linux & Mac command

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

Windows

keytool -exportcert -keystore C:\Users\<USERNAME>\.android\debug.keystore -list -v

Replace  with your windows account name example:

keytool -exportcert -keystore C:\Users\Aakash\.android\debug.keystore -list -v


问:
i try a multiple regression
I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variables (x1, x2, x3, etc.).

Can't find the error in my code:

       #data['PROFIT','HI','LO'] = data.target
        #ycenter=pd.DataFrame(np.c_[data['PROFIT'],data['HI'],data['LO']], columns=['PROFIT','HI','LO'])
        #Xcenter=pd.DataFrame(np.c_[data['ROLL'],data['DICE'],data['FREE'],data['STAKE'],data['MULT']],        columns=['ROLL','DICE','FREE','STAKE','MULT'])
       Xcenter=data['ROLL','DICE','FREE','STAKE','MULT']
       Ycenter=data['PROFIT','HI','LO']
   # split into 70:30 ration
       X_traincenter, X_testcenter, y_traincenter, y_testcenter = train_test_split(Xcenter, ycenter, test_size = 0.3, random_state = 0)
# describes info about traincenter and testcenter set
print("Number transactions X_traincenter dataset: ", X_traincenter.shape)
print("Number transactions y_traincenter dataset: ", y_traincenter.shape)
print("Number transactions X_testcenter dataset: ", X_testcenter.shape)
print("Number transactions y_testcenter dataset: ", y_testcenter.shape)

print("Before OverSampling, counts of positive profitcenter: {}".format(sum(y_traincenter > 0)))
print("Before OverSampling, counts of negative profitcenter: {} \n".format(sum(y_traincenter < 0)))
 #Initialize the linear model center
regcenter = LinearRegression()

 #Train the model with our training datacenter
regcenter.fit(X_traincenter,y_traincenter)

 #Print the coeffiscients/weights for each feature/column of our model
print(regcenter.coef_) #f(x,a) = mx + da + b =y

 #Print the predictions on our test datacenter
y_predcenter = regcenter.predict(X_testcenter)
print(y_predcenter)

 #Print the actual values center
print(y_testcenter)

 #Check the model performance/accuracy using Mean Squared Error (MSE)
print(np.mean((y_predcenter - y_testcenter)**2))

 #Check the model performance/accuracy using Mean Squared Error (MSE) and sklearn.metrics
print(mean_squared_error(y_testcenter,y_predcenter))
 #check the predictions against the actual values by using the RMSE and R-2 metrics
test_setcenter_rmse = (np.sqrt(mean_squared_error(y_testcenter, y_predcenter)))
print('test_setcenter_rmse = ',test_setcenter_rmse)
test_setcenter_r2 = r2_score(y_testcenter, y_predcenter)
print('test_setcenter_r2 = ',test_setcenter_r2)
```

<p>How would I regress these in python, to get the linear regression formula:</p>

```Y(x3,x5) = a1x1 + a2x2 + a3x4 + a4x6 + a5x7 + a6x8 + +a7x9 + c
```

答:
Well, Python can perform multiple regression as well as polynomial regression.

But if you want you can perform gradient descent-

Gradient Descent:  here

And also you can use normal equation method to perform multiple regression-

Normal Equation:  here

But if you don't want to write code for normal equation or gradient descent just use python's sklearn library for it and it works for both single feature and multiple features.

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LinearRegression

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1)

reg = linear_model.LinearRegression()

reg.fit(X_train, y_train)

reg.predict(X_test)

Title: i try a multiple regression

Body:
I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variables (x1, x2, x3, etc.).

Can't find the error in my code:

       #data['PROFIT','HI','LO'] = data.target
        #ycenter=pd.DataFrame(np.c_[data['PROFIT'],data['HI'],data['LO']], columns=['PROFIT','HI','LO'])
        #Xcenter=pd.DataFrame(np.c_[data['ROLL'],data['DICE'],data['FREE'],data['STAKE'],data['MULT']],        columns=['ROLL','DICE','FREE','STAKE','MULT'])
       Xcenter=data['ROLL','DICE','FREE','STAKE','MULT']
       Ycenter=data['PROFIT','HI','LO']
   # split into 70:30 ration
       X_traincenter, X_testcenter, y_traincenter, y_testcenter = train_test_split(Xcenter, ycenter, test_size = 0.3, random_state = 0)
# describes info about traincenter and testcenter set
print("Number transactions X_traincenter dataset: ", X_traincenter.shape)
print("Number transactions y_traincenter dataset: ", y_traincenter.shape)
print("Number transactions X_testcenter dataset: ", X_testcenter.shape)
print("Number transactions y_testcenter dataset: ", y_testcenter.shape)

print("Before OverSampling, counts of positive profitcenter: {}".format(sum(y_traincenter > 0)))
print("Before OverSampling, counts of negative profitcenter: {} \n".format(sum(y_traincenter < 0)))
 #Initialize the linear model center
regcenter = LinearRegression()

 #Train the model with our training datacenter
regcenter.fit(X_traincenter,y_traincenter)

 #Print the coeffiscients/weights for each feature/column of our model
print(regcenter.coef_) #f(x,a) = mx + da + b =y

 #Print the predictions on our test datacenter
y_predcenter = regcenter.predict(X_testcenter)
print(y_predcenter)

 #Print the actual values center
print(y_testcenter)

 #Check the model performance/accuracy using Mean Squared Error (MSE)
print(np.mean((y_predcenter - y_testcenter)**2))

 #Check the model performance/accuracy using Mean Squared Error (MSE) and sklearn.metrics
print(mean_squared_error(y_testcenter,y_predcenter))
 #check the predictions against the actual values by using the RMSE and R-2 metrics
test_setcenter_rmse = (np.sqrt(mean_squared_error(y_testcenter, y_predcenter)))
print('test_setcenter_rmse = ',test_setcenter_rmse)
test_setcenter_r2 = r2_score(y_testcenter, y_predcenter)
print('test_setcenter_r2 = ',test_setcenter_r2)

How would I regress these in python, to get the linear regression formula:

Y(x3,x5) = a1x1 + a2x2 + a3x4 + a4x6 + a5x7 + a6x8 + +a7x9 + c


问:
create progresbar percentage in angular 9
i want to create a progressbar in angular 9 when the image selected for upload .

i waite this code for find upload file and show me percent of uload .

```<code> let elemnt = document.getElementById('progress');

 this.managersService.UpdateWithFile(editModel, this.personalInfo.id, '/Manager/PersonalInfo').subscribe(
      (upload: HttpEvent<any>) => {
        switch (upload.type) {
          case HttpEventType.UploadProgress:
            if (upload.total) {
              this.queueProgress = Math.round(upload.loaded / upload.total * 100);
              if (this.queueProgress <= 100 && this.queueProgress > 0) {
                elemnt.style.strokeDashoffset = 440 + 45 + 'px'
                this.cdRef.detectChanges();
              }
            }
            break;
          case HttpEventType.Response:
            if (upload.body['isSuccess']) {
              this.queueProgress = null;
              this.alertService.success('', upload.body['message']);
              this.router.navigate(['/managers']);
            } else {
              this.cdRef.detectChanges();
            }
            this.loading = false;
            this.queueProgress = null;
            break;
        }
      },
      error => {
        this.loading = false;
        this.queueProgress = null;
      });
  }
</code>```

in this line i get a percent and need the change HTML px size .

```<code>if (this.queueProgress <= 100 && this.queueProgress > 0) {
                elemnt.style.strokeDashoffset = 440 + 45 + 'px'
                this.cdRef.detectChanges();
              }
</code>```

but my problem is here ,this code just once time exceuted elemnt.style.strokeDashoffset = 440 + 45 + 'px' but i need to every time the queueProgress changed value , this line going to excecute .

i using this this.cdRef.detectChanges(); but it not worked . whats the problem ? how can i solve this ????

答:
You are setting on each HttpEvent the offset to 485px (440 + 45) and forgot to use your variable this.queueProgress instead. This is why you don't see any change. As its percentage you could calculate this by multiplying with your required max offset

```<code>const maxOffset = 100;
elemnt.style.strokeDashoffset = 440 + (maxOffset * this.queueProgress / 100) + 'px'
</code>```

Body:
i want to create a progressbar in angular 9 when the image selected for upload .

i waite this code for find upload file and show me percent of uload .

 let elemnt = document.getElementById('progress');

 this.managersService.UpdateWithFile(editModel, this.personalInfo.id, '/Manager/PersonalInfo').subscribe(
      (upload: HttpEvent<any>) => {
        switch (upload.type) {
          case HttpEventType.UploadProgress:
            if (upload.total) {
              this.queueProgress = Math.round(upload.loaded / upload.total * 100);
              if (this.queueProgress <= 100 && this.queueProgress > 0) {
                elemnt.style.strokeDashoffset = 440 + 45 + 'px'
                this.cdRef.detectChanges();
              }
            }
            break;
          case HttpEventType.Response:
            if (upload.body['isSuccess']) {
              this.queueProgress = null;
              this.alertService.success('', upload.body['message']);
              this.router.navigate(['/managers']);
            } else {
              this.cdRef.detectChanges();
            }
            this.loading = false;
            this.queueProgress = null;
            break;
        }
      },
      error => {
        this.loading = false;
        this.queueProgress = null;
      });
  }

in this line i get a percent and need the change HTML px size .

if (this.queueProgress <= 100 && this.queueProgress > 0) {
                elemnt.style.strokeDashoffset = 440 + 45 + 'px'
                this.cdRef.detectChanges();
              }

but my problem is here ,this code just once time exceuted elemnt.style.strokeDashoffset = 440 + 45 + 'px' but i need to every time the queueProgress changed value , this line going to excecute .

i using this this.cdRef.detectChanges(); but it not worked . whats the problem ? how can i solve this ????

Body:
You are setting on each HttpEvent the offset to 485px (440 + 45) and forgot to use your variable this.queueProgress instead. This is why you don't see any change. As its percentage you could calculate this by multiplying with your required max offset

const maxOffset = 100;
elemnt.style.strokeDashoffset = 440 + (maxOffset * this.queueProgress / 100) + 'px'


问:
Memory Limit Exceed in Vector C++
I'm getting memory limit exceeded error for this code. I can't find the way to resolve it. If I'm taking  a long long int it gives the same error.

Why this error happening?

```<code>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
    ///1000000000000 500000000001 getting memory limit exceed for this test case.

    ll n,k;
    cin>>n>>k;
    vector<ll> v;
    vector<ll> arrange;

    for(ll i=0;i<n;i++)
    {
        v.push_back(i+1);
    }

    //Arranging vector like 1,3,5,...2,4,6,....
    for(ll i=0;i<v.size();i++)
    {
        if(v[i]%2!=0)
        {
            arrange.push_back(v[i]);
        }
    }
    for(ll i=0;i<v.size();i++)
    {
        if(v[i]%2==0)
        {
            arrange.push_back(v[i]);
        }
    }
    cout<<arrange[k-1]<<endl; // Found the kth number.

    return 0;
}
</code>```

答:
The provided code solves a coding problem for small values of n and k. However as you noticed it does fail for large values of n. This is because you are trying to allocate a couple of vectors of 1000000000000 elements, which exceeds the amount of memory available in today's computers.

Hence I'd suggest to return to the original problem you're solving, and try an approach that doesn't need to store all the intermediary values in memory. Since the given code works for small values of n and k, you can use the given code to check whether the approach without using vectors works.

I would suggest the following steps to redesign the approach to the coding problem:

Write down the contents of arrange for a small value of n

Write down the matching values of k for each element of arrange

Derive the (mathematical) function that maps k to the matching element in arrange

For this problem this can be done in constant time, so there is no need for loops

Note that this function should work both for even and odd values of k.

Test whether your code works by comparing it with your current results.

I would suggest trying the preceding steps first to come up with your own approach. If you can not find a working solution, please have a look at this approach on Wandbox.

Title: Memory Limit Exceed in Vector C++

Body:
I'm getting memory limit exceeded error for this code. I can't find the way to resolve it. If I'm taking  a long long int it gives the same error.

Why this error happening?

#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
    ///1000000000000 500000000001 getting memory limit exceed for this test case.

    ll n,k;
    cin>>n>>k;
    vector<ll> v;
    vector<ll> arrange;

    for(ll i=0;i<n;i++)
    {
        v.push_back(i+1);
    }

    //Arranging vector like 1,3,5,...2,4,6,....
    for(ll i=0;i<v.size();i++)
    {
        if(v[i]%2!=0)
        {
            arrange.push_back(v[i]);
        }
    }
    for(ll i=0;i<v.size();i++)
    {
        if(v[i]%2==0)
        {
            arrange.push_back(v[i]);
        }
    }
    cout<<arrange[k-1]<<endl; // Found the kth number.

    return 0;
}


问:
Set cpu requests in K8s for fluctuating load
I have a service deployed in Kubernetes and I am trying to optimize the requested cpu resources.

For now, I have deployed 10 instances and set spec.containers[].resources.limits.cpu to 0.1, based on the "average" use. However, it became obvious that this average is rather useless in practice because under constant load, the load increases significantly (to 0.3-0.4 as far as I can tell).

What happens consequently, when multiple instances are deployed on the same node, is that this node is heavily overloaded; pods are no longer responsive, are killed and restarted etc.

What is the best practice to find a good value? My current best guess is to increase the requested cpu to 0.3 or 0.4; I'm looking at Grafana visualizations and see that the pods on the heavily loaded node(s) converge there under continuous load.
However, how can I know if they would use more load if they could before becoming unresponsive as the node is overloaded?

I'm actually trying to understand how to approach this in general. I would expect an "ideal" service (presuming it is CPU-focused) to use close to 0.0 when there is no load, and close to 1.0 when requests are constantly coming in. With that assumption, should I set the cpu.requests to 1.0, taking a perspective where actual constant usage is assumed?

I have read some Kubernetes best practice guides, but none of them seem to address how to set the actual value for cpu requests in practice in more depth than "find an average".

答:
Basically come up with a number that is your lower acceptable bound for how much the process runs. Setting a request of 100m means that you are okay with a lower limit of your process running 0.1 seconds for every 1 second of wall time (roughly). Normally that should be some kind of average utilization, usually something like a P99 or P95 value over several days or weeks. Personally I usually look at a chart of P99, P80, and P50 (median) over 30 days and use that to decide on a value.

Limits are a different beast, they are setting your CPU timeslice quota. This subsystem in Linux has some persistent bugs so unless you've specifically vetted your kernel as correct, I don't recommend using it for anything but the most hostile of programs.


问:
How to give break line in data label
how to give break line in data label , Till what i have done below is link and i have pasted code here also.

And i am using custom datalabel and i want to add break line

https://jsfiddle.net/0x3ct8aq/4/

```<code>

<script>

    onComplete () {

       const chartInstance = this.chart;
      const ctx = chartInstance.ctx;
      const dataset = this.data.datasets[0];
      const meta = chartInstance.controller.getDatasetMeta(0);

      Chart.helpers.each(meta.data.forEach((bar, index) => {

        const label = this.data.customlabels[index];
        const labelPositionX = 20;
        const labelWidth = ctx.measureText(label).width + labelPositionX;

        ctx.textBaseline = 'bottom';
        ctx.textAlign = 'center';
        ctx.fillStyle = '#fff';
        console.log(label.x);
        ctx.fillText(label, bar._model.x, bar._model.y);

      }));

    }
  }
    },

});
</script>

</code>```

答:
Inside the animation.onComplete() function, you can reverse() the labels array, then draw individual tokens using forEach() as follows:

```<code>label.reverse().forEach((l, i) => ctx.fillText(l, bar._model.x, bar._model.y - (i * 16)))
</code>```

Please have a look at your amended JSFiddle

Title: How to give break line in data label

Body:
Inside the animation.onComplete() function, you can reverse() the labels array, then draw individual tokens using forEach() as follows:

label.reverse().forEach((l, i) => ctx.fillText(l, bar._model.x, bar._model.y - (i * 16)))

Please have a look at your amended JSFiddle


问:
Getting error while adding legend in leaflet object in R
I am trying to create a map in ggplot using leaflet library in R, I am pretty new to R programing. My dataset is per capita carbon emission of different countries in the world. For this, I first merge the shp file with my dataset, then created lables, bins and palette and then added polygons. But when I am trying to add legend using addlegend(), its throwing the following error:
Error in as.character(x) :
  cannot coerce type 'closure' to vector of type 'character'.
I have checked code in stages and codes works until I add legend, so suspecting either some issue in pal or value in addlegend().

```<code>library(leaflet)
library(ggplot2)
library(dplyr)
library(rgeos)
library(maptools)
library(ggmap)
library(broom)
library(readr)
library(lubridate)
library(dplyr)
library(tidyr)
library(scales)
library(RColorBrewer)
theme_set(theme_minimal())

# Read data into per_capita_emission object
per_capita_emission <- read.csv('co-emissions-per-capita.csv')

# Filter dataframe for year 2017
per_capita_emission_2017 <- per_capita_emission  %>% filter(Year == "2017")

# read shape file into R
Countries_shp<-readShapeSpatial("World_Countries/World_Countries.shp",delete_null_obj=TRUE)

# leaflet
p1 <- leaflet(Countries_shp) %>%
  setView(lng = 145.5, lat = -36.5, zoom = 2)
p1 %>% addPolygons()
per_capita_emission_2017$COUNTRY <- per_capita_emission_2017$Entity
per_capita_emission_2017<-select (per_capita_emission_2017,-c(Entity))
merge.per_capita_emission_2017_shp<-sp::merge(Countries_shp, per_capita_emission_2017,
                                               by="COUNTRY", duplicateGeoms = TRUE)

bins <- quantile(
  merge.per_capita_emission_2017_shp$Per_capita_emissions_in_tonnes,
  probs = seq(0,1,.2), names = FALSE, na.rm = TRUE)

pal <- colorBin(
  "YlOrRd",
  domain = merge.per_capita_emission_2017_shp$Per_capita_emissions_in_tonnes,
  bins = 4,
  pretty = FALSE
)

p1 <- leaflet(merge.per_capita_emission_2017_shp) %>%
  setView(lng = 147, lat = -36.5, zoom = 2)
p1 %>% addPolygons(
  fillColor = ~pal(Per_capita_emissions_in_tonnes),
  weight = 2,
  opacity = 1,
  color = "white",
  dashArray = "3",
  fillOpacity = 0.7,
  highlight = highlightOptions(
    weight = 3,
    color = "#666",
    dashArray = "",
    fillOpacity = 0.7,
    bringToFront = TRUE))

labels <- sprintf(
  "<strong>%s</strong><br/>%g Per_capita_emissions_in_tonnes",
  merge.per_capita_emission_2017_shp$COUNTRY,
  merge.per_capita_emission_2017_shp$Per_capita_emissions_in_tonnes
) %>% lapply(htmltools::HTML)

p1 %>% addPolygons(
  data = merge.per_capita_emission_2017_shp,
  fillColor = ~pal(merge.per_capita_emission_2017_shp$Per_capita_emissions_in_tonnes),
  weight = 2,
  opacity = 1,
  color = "white",
  dashArray = "3",
  fillOpacity = 0.7,
  highlight = highlightOptions(
    weight = 5,
    color = "#666",
    dashArray = "3",
    fillOpacity = 0.7,
    bringToFront = TRUE),
  label = labels,
  labelOptions = labelOptions(
    style = list("font-weight" = "normal", padding = "3px 8px"),
    textsize = "15px",
    direction = "auto"))%>%
  addLegend(pal = pal,
            values = merge.per_capita_emission_2017_shp$Per_capita_emissions_in_tonnes,
            opacity = 0.7,
            title = "Per_capita_emissions_in_tonnes",
            position = "bottomright"
  ) %>%
  addControl(title, position = "topright")

</code>```

Following is the link to get the dataset, please include blob: to download data:
blob:https://ourworldindata.org/27f19210-ac40-4909-9826-c7a72dc64a23

Following is the link to get the shp file for country's cordinates:
https://tapiquen-sig.jimdofree.com/app/download/5496966159/World_Countries.rar?t=1589254856

答:
Sorry this is going to be more of a clarification, but I cant comment (not enough reputation).

I think what may be happening is the addLegend is seeing your values as a character or its not recognizing it because it could be seeing it as a shapefile database, so maybe something like merge.per_capita_emission_2017_shp@data$Per_capita_emissions_in_tonnes.

When you merge that data to the shapefile you produce both the shapes and data together in a list like vector, so be sure to call the data portion of that from where you merged it.

For example in my leaflet if have (values =  dataM@data[,6]) with data being the sub-spreadsheet i want to call from within the shapefile list.

I dont know the structure of the dataset (the link is 404ing), so this is purely guesswork.

Sorry I cant be more specific

Body:
I am trying to create a map in ggplot using leaflet library in R, I am pretty new to R programing. My dataset is per capita carbon emission of different countries in the world. For this, I first merge the shp file with my dataset, then created lables, bins and palette and then added polygons. But when I am trying to add legend using addlegend(), its throwing the following error:
Error in as.character(x) :
  cannot coerce type 'closure' to vector of type 'character'.
I have checked code in stages and codes works until I add legend, so suspecting either some issue in pal or value in addlegend().

library(leaflet)
library(ggplot2)
library(dplyr)
library(rgeos)
library(maptools)
library(ggmap)
library(broom)
library(readr)
library(lubridate)
library(dplyr)
library(tidyr)
library(scales)
library(RColorBrewer)
theme_set(theme_minimal())

# Read data into per_capita_emission object
per_capita_emission <- read.csv('co-emissions-per-capita.csv')

# Filter dataframe for year 2017
per_capita_emission_2017 <- per_capita_emission  %>% filter(Year == "2017")

# read shape file into R
Countries_shp<-readShapeSpatial("World_Countries/World_Countries.shp",delete_null_obj=TRUE)

# leaflet
p1 <- leaflet(Countries_shp) %>%
  setView(lng = 145.5, lat = -36.5, zoom = 2)
p1 %>% addPolygons()
per_capita_emission_2017$COUNTRY <- per_capita_emission_2017$Entity
per_capita_emission_2017<-select (per_capita_emission_2017,-c(Entity))
merge.per_capita_emission_2017_shp<-sp::merge(Countries_shp, per_capita_emission_2017,
                                               by="COUNTRY", duplicateGeoms = TRUE)

bins <- quantile(
  merge.per_capita_emission_2017_shp$Per_capita_emissions_in_tonnes,
  probs = seq(0,1,.2), names = FALSE, na.rm = TRUE)

pal <- colorBin(
  "YlOrRd",
  domain = merge.per_capita_emission_2017_shp$Per_capita_emissions_in_tonnes,
  bins = 4,
  pretty = FALSE
)

p1 <- leaflet(merge.per_capita_emission_2017_shp) %>%
  setView(lng = 147, lat = -36.5, zoom = 2)
p1 %>% addPolygons(
  fillColor = ~pal(Per_capita_emissions_in_tonnes),
  weight = 2,
  opacity = 1,
  color = "white",
  dashArray = "3",
  fillOpacity = 0.7,
  highlight = highlightOptions(
    weight = 3,
    color = "#666",
    dashArray = "",
    fillOpacity = 0.7,
    bringToFront = TRUE))

labels <- sprintf(
  "%s
%g Per_capita_emissions_in_tonnes",
  merge.per_capita_emission_2017_shp$COUNTRY,
  merge.per_capita_emission_2017_shp$Per_capita_emissions_in_tonnes
) %>% lapply(htmltools::HTML)

p1 %>% addPolygons(
  data = merge.per_capita_emission_2017_shp,
  fillColor = ~pal(merge.per_capita_emission_2017_shp$Per_capita_emissions_in_tonnes),
  weight = 2,
  opacity = 1,
  color = "white",
  dashArray = "3",
  fillOpacity = 0.7,
  highlight = highlightOptions(
    weight = 5,
    color = "#666",
    dashArray = "3",
    fillOpacity = 0.7,
    bringToFront = TRUE),
  label = labels,
  labelOptions = labelOptions(
    style = list("font-weight" = "normal", padding = "3px 8px"),
    textsize = "15px",
    direction = "auto"))%>%
  addLegend(pal = pal,
            values = merge.per_capita_emission_2017_shp$Per_capita_emissions_in_tonnes,
            opacity = 0.7,
            title = "Per_capita_emissions_in_tonnes",
            position = "bottomright"
  ) %>%
  addControl(title, position = "topright")

Following is the link to get the dataset, please include blob: to download data:
blob:https://ourworldindata.org/27f19210-ac40-4909-9826-c7a72dc64a23

Following is the link to get the shp file for country's cordinates:
https://tapiquen-sig.jimdofree.com/app/download/5496966159/World_Countries.rar?t=1589254856


问:
I used database ID as object key, but I'm getting an error to get the value of that key
my objects are saved like this {"5ec801f6c7efb501a06b167f":"hi"} in DB, with userID as key.

```<code> return <div>{b.5ec801f6c7efb501a06b167f}</div>;
</code>```

In this line it's showing an error, because the key starts with an integer.
How to solve this?

答:
Any java script object property should not start with digits. That's why you are facing issue.

if you need value with that id in b use
{b['5ec801f6c7efb501a06b167f']}
.

Body:
my objects are saved like this {"5ec801f6c7efb501a06b167f":"hi"} in DB, with userID as key.

 return
{b.5ec801f6c7efb501a06b167f}
;

In this line it's showing an error, because the key starts with an integer.
How to solve this?

Body:
Any java script object property should not start with digits. That's why you are facing issue.

if you need value with that id in b use <div>{b['5ec801f6c7efb501a06b167f']}</div>.


问:
Base of Global Call Stack in C/C++
I have read that each function invocation leads to pushing of a stack frame in the global call stack and once the function call is completed the call stack is popped off and the control passes to the address that we get from the popped of stack frame. If a called function calls on to yet another function, it will push another return address onto the top of the same call stack, and so on, with the information stacking up and unstacking as the program dictates.

I was wondering what's at the base of global call stack in a C or C++ program?

I did some searching on the internet but none of the sources explicitly mention about it. Is the call stack empty when our program starts and only once a function is called, the call stack usage starts? OR Is the address where main() function has to return, gets implicitly pushed as the base of our call stack and is a stack frame in our call stack? I expect the main() would also have a stack frame in our call stack since we are always returning something at end of our main() function and there needs to be some address to return to. OR is this dependent on compiler/OS and differs according to implementation?

It would be helpful if someone has some informative links about this or could provide details on the process that goes into it.

答:
I'm not sure if there is a universal answer, as stack is something that may be implemented differently per architecture. For example a stack may grow up (i.e. stack position pointer value increases when pushing onto the stack) or grow downwards.

Exiting main() is usually done by calling an operating function to indicate the program wishes to to terminate (with the specified return code), so I don't expect a return address for main() to be present on the stack, but this may differ per operating system and even compiler.

I'm not sure why you need to know this, as this is typically something you leave up to the system.

Title: Base of Global Call Stack in C/C++


问:
idxmax() not working on a pandas DataFrame
I have a pandas data frame which I created after reading a csv file.

```<code>df = pd.DataFrame(ITC)
print(df.tail(5))
</code>```

This prints

```<code>            date            open  ...             low           close
488  22-May-2020          188.00  ...          184.60          186.35
489  26-May-2020          190.00  ...          187.80          191.70
490  27-May-2020          192.50  ...          186.90          192.15
491  28-May-2020          192.30  ...          189.00          190.65
492  29-May-2020          190.45  ...          189.00          197.35
</code>```

I wanted to find max from the 'close' column and df.tail(5).close.max() works fine.
At last I wanted to print the index of the max value which is 492 so I tried the following

```<code>print(df.tail(5).close.idxmax())
</code>```

but it gives me the following error

TypeError: reduction operation 'argmax' not allowed for this dtype

Any idea on how to go about this ?

答:
I think close column is not numeric, but filled by strings repr od numbers.

So use:

```<code>df.close = df.close.astype(float)
</code>```

Or:

```<code>df.close = pd.to_numeric(df.close, errors='coerce')
</code>```

Body:
I have a pandas data frame which I created after reading a csv file.

df = pd.DataFrame(ITC)
print(df.tail(5))

This prints

            date            open  ...             low           close
488  22-May-2020          188.00  ...          184.60          186.35
489  26-May-2020          190.00  ...          187.80          191.70
490  27-May-2020          192.50  ...          186.90          192.15
491  28-May-2020          192.30  ...          189.00          190.65
492  29-May-2020          190.45  ...          189.00          197.35

I wanted to find max from the 'close' column and df.tail(5).close.max() works fine.
At last I wanted to print the index of the max value which is 492 so I tried the following

print(df.tail(5).close.idxmax())

but it gives me the following error

TypeError: reduction operation 'argmax' not allowed for this dtype

Any idea on how to go about this ?

Body:
I think close column is not numeric, but filled by strings repr od numbers.

So use:

df.close = df.close.astype(float)

Or:

df.close = pd.to_numeric(df.close, errors='coerce')


问:
Windows 10: "The ampersand () character is not allowed"
I am learning C language. I installed and configurated everything to start coding

But when I try to use ampersand (&) in scanf my program doesn't compile:

```<code>scanf("%f", &x);
</code>```

I am getting this error:

The ampersand () character is not allowed. The & operator is reserved
  for future use; wrap an ampersand in double quotation marks ("&") to
  pass it as part of a string.

答: Sorry my bad, I had to change my file extension from .cpp to .c to make it work correctly.</p>

Body:
I am learning C language. I installed and configurated everything to start coding

But when I try to use ampersand (&) in scanf my program doesn't compile:

scanf("%f", &x);

I am getting this error:

The ampersand () character is not allowed. The & operator is reserved
  for future use; wrap an ampersand in double quotation marks ("&") to
  pass it as part of a string.


答: main() is invoked by the libc code that handles setting up the environment for the executable etc. So by the time main() is called, the stack already has at least one frame created by the caller. </p>

Title: Base of Global Call Stack in C/C++

Body:
I have read that each function invocation leads to pushing of a stack frame in the global call stack and once the function call is completed the call stack is popped off and the control passes to the address that we get from the popped of stack frame. If a called function calls on to yet another function, it will push another return address onto the top of the same call stack, and so on, with the information stacking up and unstacking as the program dictates.

I was wondering what's at the base of global call stack in a C or C++ program?

I did some searching on the internet but none of the sources explicitly mention about it. Is the call stack empty when our program starts and only once a function is called, the call stack usage starts? OR Is the address where main() function has to return, gets implicitly pushed as the base of our call stack and is a stack frame in our call stack? I expect the main() would also have a stack frame in our call stack since we are always returning something at end of our main() function and there needs to be some address to return to. OR is this dependent on compiler/OS and differs according to implementation?

It would be helpful if someone has some informative links about this or could provide details on the process that goes into it.


问:
Save files on Azure App Services and make them accesible from the outside
I am new to Web-Development and have therefor maybe a beginner question.
So I am having a Web-App with an Angular Frontend und .Net backend, deployed on Azure.

Now users should be able to upload files (pdf, etc.) to the server which sould be stored permanetly. I would prefer to store them on a normal filesystem, so I don't want to use a database. Futhermore the files should be accessible for external services for futher processing.

I am not sure if that is possible with Azure App Services or if I need some other components. The only way I found to store files on the server is in the "wwwroot" folder. But I found no way to download them from the outside. Should I create a Web-API for that or do I think to complicated? Should I deploy my App somewhere else? What could be a way to implement this?

Thanks for any help.

答:
You should use Azure Storage.

In Azure storage you can find mainly two options in your case. Blob and File Storage.

Blob is "more advanced" in a sense that it serves files on the browser, streaming video and audio etc.

File storage is a replacement of an on-premises file server.

Both options support file access by external services, and in addition to authorization, both are supported with Azure AD and shared access token.


问:
SSD anchor box scale relative to input image size or feature map
I have done a lot of reading on SSD paper, but i couldn't figure out when they mention a scale of Smin 0.2 to Smax 0.9, do they mean in relation to the input image size or in relation to the feature map size at that layer. Can someone help clarify this fact?

答:
Apparently this is with respect to each layer, quoting (page 6, equation 4):

The scale of the default boxes for each feature map is computed as:

where smin is 0.2 and smax is 0.9, meaning the lowest layer has a scale of 0.2 and the
  highest layer has a scale of 0.9, and all layers in between are
  regularly spaced.