问:
How can I draw a line in my form from another class?
I have 3 classes in my program:

Arrow (it contains the logic for drawing arrow, and all required information about it, like: starting point, ending point, etc.)

Form1 (that contains the drawing area(basically panel), where this arrow will be located in the future)

UserControl, is located in Form1 (I did Form1.Controls.Add(UserControl)). It has a Form1 as a parent. In this UserControl, I have a button, when I click it, an arrow should be drawn on the Form1's drawing area.

And I'm so confused with the logic that this program should have. I tried to create Arrow class object in the UserControl.Button_Click(), and call all the Arrow's methods from there, but I can't access to Form1's controls. I also thought maybe I can create object of Arrow in the Form1. So I tried to subscribe event UserControl.Button_Click() with some Form1's delegate, but I don't know how to do it. In this case, does delegate and the method that this delegate have as a reference should be Static?

So this is how my code looks like.
(I little bit simplified and shortened my classes)
Arrow:

```<code>public class Arrow
{
    public Point PointBeginning { get => pointBeginning; set => pointBeginning = value; }
    public Point PointEnding { get => pointEnding; set => pointEnding = value; }
    public int ArrowClickCounter { get => arrowClickCounter; set => arrowClickCounter = value; }

    public void Draw(object sender, MouseEventArgs e)
    {
        //code for drawing
    }
}
</code>```

Form1:

```<code>public class Form1
{
    public delegate void DrawArrowDelegate(object sender, MouseEventArgs e);
    DrawArrowDelegate drawArrowDelegate = DrawArrow;
    /* .. */

    private void DrawArrow(object sender, MouseEventArgs e)
    {
        Arrow arrow = new Arrow();
        arrow.PointBegining = //some point
        arrow.PointEnding = //some another point
        arrow.Draw(sender, e);
    }
}
</code>```

UserControl:

```<code>public class UserControl
{
    /*...*/

    private void button_MouseClick(object sender, MouseEventArgs e)
    {
        //And here i somehow want to call delegate. But don't know how :(
    }
}
</code>```

Sorry for such confused code :(

Can you please recommend me something?

答:
It sounds like you're having trouble accessing Form1's Controls, so try this:

```<code>Form1 f1 = new Form1();

foreach(Button b in f1.Controls)
{
  //Your code..
}
</code>```

There's also:

```<code>this.Controls
</code>```

And, with calling the events of another control,

```<code>button1_Click(sender, e);
</code>```

As for adding an event to the click of, say, a button,

```<code>button1.Click += button1_Click;
</code>```

Those should work to access the controls.

I can provide more information if needed :)

Body:
I have 3 classes in my program:

Arrow (it contains the logic for drawing arrow, and all required information about it, like: starting point, ending point, etc.)

Form1 (that contains the drawing area(basically panel), where this arrow will be located in the future)

UserControl, is located in Form1 (I did Form1.Controls.Add(UserControl)). It has a Form1 as a parent. In this UserControl, I have a button, when I click it, an arrow should be drawn on the Form1's drawing area.

And I'm so confused with the logic that this program should have. I tried to create Arrow class object in the UserControl.Button_Click(), and call all the Arrow's methods from there, but I can't access to Form1's controls. I also thought maybe I can create object of Arrow in the Form1. So I tried to subscribe event UserControl.Button_Click() with some Form1's delegate, but I don't know how to do it. In this case, does delegate and the method that this delegate have as a reference should be Static?

So this is how my code looks like.
(I little bit simplified and shortened my classes)
Arrow:

public class Arrow
{
    public Point PointBeginning { get => pointBeginning; set => pointBeginning = value; }
    public Point PointEnding { get => pointEnding; set => pointEnding = value; }
    public int ArrowClickCounter { get => arrowClickCounter; set => arrowClickCounter = value; }

    public void Draw(object sender, MouseEventArgs e)
    {
        //code for drawing
    }
}

Form1:

public class Form1
{
    public delegate void DrawArrowDelegate(object sender, MouseEventArgs e);
    DrawArrowDelegate drawArrowDelegate = DrawArrow;
    /* .. */

    private void DrawArrow(object sender, MouseEventArgs e)
    {
        Arrow arrow = new Arrow();
        arrow.PointBegining = //some point
        arrow.PointEnding = //some another point
        arrow.Draw(sender, e);
    }
}

UserControl:

public class UserControl
{
    /*...*/

    private void button_MouseClick(object sender, MouseEventArgs e)
    {
        //And here i somehow want to call delegate. But don't know how :(
    }
}

Sorry for such confused code :(

Can you please recommend me something?

Body:
It sounds like you're having trouble accessing Form1's Controls, so try this:

Form1 f1 = new Form1();

foreach(Button b in f1.Controls)
{
  //Your code..
}

There's also:

this.Controls

And, with calling the events of another control,

button1_Click(sender, e);

As for adding an event to the click of, say, a button,

button1.Click += button1_Click;

Those should work to access the controls.

I can provide more information if needed :)


来源: stackexchange

问:
How to convert CSV to JSON-Python
I am having trouble converting a url from a csv file to json, change whatever changes anything always shows me the following error:

Traceback (most recent call last):
    File "c:/Users/Gamer/Downloads/TimingReady/PC/archivos/prueba.py", line 8, in
      with open(csvUrl) as csvFile:
  OSError: [Errno 22] Invalid argument: 'http://localhost/_144141/api/0WUFVJB4ZTBENW5F6JT3QAUV4ASMRH10.csv'

My code is as follows:

```<code>            import csv
            import json

            csvUrl = input("Paste the event URL: ")
            jsonFinal = "jsonEvento.json"

            data = {}
            with open(csvUrl) as csvFile:
                csvReader = csv.DictReader(csvFile)
                for csvRow in csvReader:
                    Place = csvRow["Place"]
                    data[Place] = csvRow

            root = {}
            roo["Participantes"] = data

            with open(jsonFinal, "w") as jsonFile:
                jsonFile.write(json.dumps(root, indent=4))
</code>```

And the CSV file is as follows:

"Place";"Chip";"Numero";"Apellido";"Nombre";"Tiempo"
  "1.";"739";"139";"MARTINEZ GUTIERREZ";"JOSE";"00:30:12,91"
  "2.";"707";"107";"SUAREZ MORERA";"DANIEL";"02:00:17,54"
  "3.";"1686";"274";"RODRIGUEZ VARGAS";"JOSE LUIS";"02:01:09,09"
  "4.";"761";"161";"GONZALEZ MORENO";"MAURICIO ALBERTO";"02:03:18,29"
  "5.";"775";"175";"HERNANDEZ";"ALEJANDRO";"02:05:05,93"
  "6.";"1709";"297";"CASTILLO";"JOSE GREGORIO";"02:09:51,26"
  "7.";"721";"121";"TELLEZ CRUZ";"CARLOS ALBERTO";"02:11:08,34"
  "8.";"1711";"299";"MEDINA JARAMILLO";"JEFERSON";"02:12:26,48"
  "9.";"766";"166";"JIMENEZ";"FRANCE ELIAS";"02:12:44,48"
  "10.";"1671";"259";"GOMEZ PRIETO";"JEAN JENNER";"02:14:03,54"
  "11.";"778";"178";"CAMPO SARMIENTO";"JOSE FRANCISCO";"02:15:45,05"
  "12.";"1702";"290";"BUITRAGO HERNANDEZ";"NORBEY";"02:15:45,49"

Which I need in JSON like this

```<code>            {
                "nombreEvento": "Intercontinental Sunset Cartagena",
                "participantes": [
                    {
                    "Apellido": "MARTINEZ GUTIERREZ",
                    "Chip": 739,
                    "Nombre": "JOSE",
                    "Numero": 139,
                    "Place": "1.",
                    "Tiempo": "00:30:12,91"
                    },
                    {
                    "Apellido": "SUAREZ MORERA",
                    "Chip": 707,
                    "Nombre": "DANIEL",
                    "Numero": 107,
                    "Place": "2.",
                    "Tiempo": "02:00:17,54"
                    },
                    {
                    "Apellido": "RODRIGUEZ VARGAS",
                    "Chip": 1686,
                    "Nombre": "JOSE LUIS",
                    "Numero": 274,
                    "Place": "3.",
                    "Tiempo": "02:01:09,09"
                    }
                ]
            }
</code>```

I want to make Python stream the csv file in real time to json.

答:
Thanks to Timo Frionnet

In my case I needed a manual way to add the "EventName" and also a URL because the program I use does not provide me with the facility of a RestApi

```<code>            import csv
            import json
            from io import StringIO
            from urllib.request import urlopen

            url = input("Pega aqui la URL de RaceResult: ")
            data = []
            final = {}

            csvfile = urlopen(url).read().decode('ascii', 'ignore')
            datafile = StringIO(csvfile)

            csvReader = csv.DictReader(datafile, delimiter=';')
            for csvRow in csvReader:
                print(csvRow)
                data.append(csvRow)

            final['nombreEvento'] = input("Escribe el Nombre del Evento: ")
            final['participantes'] = data
            jsonFinal = "jsonEvento.json"
            with open(jsonFinal, "w") as jsonFile:
               jsonFile.write(json.dumps(final, indent=4))
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to convert CSV to JSON-Python

Body:
I am having trouble converting a url from a csv file to json, change whatever changes anything always shows me the following error:

Traceback (most recent call last):
    File "c:/Users/Gamer/Downloads/TimingReady/PC/archivos/prueba.py", line 8, in
      with open(csvUrl) as csvFile:
  OSError: [Errno 22] Invalid argument: 'http://localhost/_144141/api/0WUFVJB4ZTBENW5F6JT3QAUV4ASMRH10.csv'

My code is as follows:

            import csv
            import json

            csvUrl = input("Paste the event URL: ")
            jsonFinal = "jsonEvento.json"

            data = {}
            with open(csvUrl) as csvFile:
                csvReader = csv.DictReader(csvFile)
                for csvRow in csvReader:
                    Place = csvRow["Place"]
                    data[Place] = csvRow

            root = {}
            roo["Participantes"] = data

            with open(jsonFinal, "w") as jsonFile:
                jsonFile.write(json.dumps(root, indent=4))

And the CSV file is as follows:

"Place";"Chip";"Numero";"Apellido";"Nombre";"Tiempo"
  "1.";"739";"139";"MARTINEZ GUTIERREZ";"JOSE";"00:30:12,91"
  "2.";"707";"107";"SUAREZ MORERA";"DANIEL";"02:00:17,54"
  "3.";"1686";"274";"RODRIGUEZ VARGAS";"JOSE LUIS";"02:01:09,09"
  "4.";"761";"161";"GONZALEZ MORENO";"MAURICIO ALBERTO";"02:03:18,29"
  "5.";"775";"175";"HERNANDEZ";"ALEJANDRO";"02:05:05,93"
  "6.";"1709";"297";"CASTILLO";"JOSE GREGORIO";"02:09:51,26"
  "7.";"721";"121";"TELLEZ CRUZ";"CARLOS ALBERTO";"02:11:08,34"
  "8.";"1711";"299";"MEDINA JARAMILLO";"JEFERSON";"02:12:26,48"
  "9.";"766";"166";"JIMENEZ";"FRANCE ELIAS";"02:12:44,48"
  "10.";"1671";"259";"GOMEZ PRIETO";"JEAN JENNER";"02:14:03,54"
  "11.";"778";"178";"CAMPO SARMIENTO";"JOSE FRANCISCO";"02:15:45,05"
  "12.";"1702";"290";"BUITRAGO HERNANDEZ";"NORBEY";"02:15:45,49"

Which I need in JSON like this

            {
                "nombreEvento": "Intercontinental Sunset Cartagena",
                "participantes": [
                    {
                    "Apellido": "MARTINEZ GUTIERREZ",
                    "Chip": 739,
                    "Nombre": "JOSE",
                    "Numero": 139,
                    "Place": "1.",
                    "Tiempo": "00:30:12,91"
                    },
                    {
                    "Apellido": "SUAREZ MORERA",
                    "Chip": 707,
                    "Nombre": "DANIEL",
                    "Numero": 107,
                    "Place": "2.",
                    "Tiempo": "02:00:17,54"
                    },
                    {
                    "Apellido": "RODRIGUEZ VARGAS",
                    "Chip": 1686,
                    "Nombre": "JOSE LUIS",
                    "Numero": 274,
                    "Place": "3.",
                    "Tiempo": "02:01:09,09"
                    }
                ]
            }

I want to make Python stream the csv file in real time to json.

Body:
Thanks to Timo Frionnet

In my case I needed a manual way to add the "EventName" and also a URL because the program I use does not provide me with the facility of a RestApi

            import csv
            import json
            from io import StringIO
            from urllib.request import urlopen

            url = input("Pega aqui la URL de RaceResult: ")
            data = []
            final = {}

            csvfile = urlopen(url).read().decode('ascii', 'ignore')
            datafile = StringIO(csvfile)

            csvReader = csv.DictReader(datafile, delimiter=';')
            for csvRow in csvReader:
                print(csvRow)
                data.append(csvRow)

            final['nombreEvento'] = input("Escribe el Nombre del Evento: ")
            final['participantes'] = data
            jsonFinal = "jsonEvento.json"
            with open(jsonFinal, "w") as jsonFile:
               jsonFile.write(json.dumps(final, indent=4))


问:
Updating all the way from angular 5 to 9, problem with angular material @7
I have a project which has been under low maintenance for over a year, and web development goes quite a bit forward in that time. So now I have the task of updating Angular from 5 to 9. I have been successfully able to go up to Angular 7, but when updating the angular/material library to version 7 I get these:

ng update @angular/material@7

```<code>              Package "codelyzer" has an incompatible peer dependency to "@angular/compiler" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.0.1").
              Package "@angular/http" has an incompatible peer dependency to "@angular/platform-browser" (requires "7.2.16" (extended), would install "9.0.1").
              Package "codelyzer" has an incompatible peer dependency to "@angular/core" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.0.1").*
</code>```

When checking the dependencies of angular/material, I cannot find that it has dependencies to any of those libraries, so why does it even try to update them? And why to version 9.0.1, since that sounds a little bit like Angular 9?

EDIT

Now I understand the reason. @angular/material@7 packages have dependencies defined with ^7.3.2 for example. This notation causes it to fetch the latest package which is the version 9.0.1 (or currently 9.0.2). But the other codelyzer and @angular/http versions do not support this new version.

So, how can I update a package in npm so that it takes the noted dependency versions in package.json instead of the newest ones?

答:
Depending on application size if its not to big I would advise to upgrade straight to 9. But to help you with this problem you probably should run:

```<code>npm i @angular/compiler@9 @angular/platform-browser@9 @angular/core@9
</code>```

from this error it looks like you have some libraries that where updated to version that require version 9 of those above dependencies.

Body:
I have a project which has been under low maintenance for over a year, and web development goes quite a bit forward in that time. So now I have the task of updating Angular from 5 to 9. I have been successfully able to go up to Angular 7, but when updating the angular/material library to version 7 I get these:

ng update @angular/material@7

              Package "codelyzer" has an incompatible peer dependency to "@angular/compiler" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.0.1").
              Package "@angular/http" has an incompatible peer dependency to "@angular/platform-browser" (requires "7.2.16" (extended), would install "9.0.1").
              Package "codelyzer" has an incompatible peer dependency to "@angular/core" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.0.1").*

When checking the dependencies of angular/material, I cannot find that it has dependencies to any of those libraries, so why does it even try to update them? And why to version 9.0.1, since that sounds a little bit like Angular 9?

EDIT

Now I understand the reason. @angular/material@7 packages have dependencies defined with ^7.3.2 for example. This notation causes it to fetch the latest package which is the version 9.0.1 (or currently 9.0.2). But the other codelyzer and @angular/http versions do not support this new version.

So, how can I update a package in npm so that it takes the noted dependency versions in package.json instead of the newest ones?

Body:
Depending on application size if its not to big I would advise to upgrade straight to 9. But to help you with this problem you probably should run:

npm i @angular/compiler@9 @angular/platform-browser@9 @angular/core@9

from this error it looks like you have some libraries that where updated to version that require version 9 of those above dependencies.


问:
Running mkdir -p remotely via ssh results in is not a valid local path or glob error
I'm using Fabric (http://www.fabfile.org) framework which connects via ssh to a VPS (Droplet on DigitalOcean) to push some bash commands.

Running a simple bash command mkdir fails with

```<code>ValueError: 'mkdir -p /opt/create_this_dir' is not a valid local path or glob.
</code>```

What could be the problem here? When I log into the VPS via ssh as root, I'm able to run

```<code>"mkdir -p /opt/create_this_dir"
</code>```

and the directory gets created under /opt/ without same error I get when I run command remotely with fabric script seen in screenshot below.

答:
I need to use

```<code>run("sudo mkdir -p /opt/reimaginedworks")
</code>```

instead of

```<code>put("sudo mkdir -p /opt/reimaginedworks")
</code>```

Body:
I'm using Fabric (http://www.fabfile.org) framework which connects via ssh to a VPS (Droplet on DigitalOcean) to push some bash commands.

Running a simple bash command mkdir fails with

ValueError: 'mkdir -p /opt/create_this_dir' is not a valid local path or glob.

What could be the problem here? When I log into the VPS via ssh as root, I'm able to run

"mkdir -p /opt/create_this_dir"

and the directory gets created under /opt/ without same error I get when I run command remotely with fabric script seen in screenshot below.

Body:
I need to use

run("sudo mkdir -p /opt/reimaginedworks")

instead of

put("sudo mkdir -p /opt/reimaginedworks")


问:
How do I make my 3rd dynamic drop down reset once I pick a different option in the 1st drop down?
I have this task to make a dynamic dropdown using Jquery ajax and json in js. Everything works ok, except one thing. To put for example, when I pick something in dropdown A, dropdown B loads items from Json via Ajax and jquery. After I pick an option in dropdown B, dropdown C is populated also from Json file. Now, once I try and switch dropdown B option and do it, dropdown C is populated differently. However, when I try have all 3 dropdowns chosen, and then try to change dropdown A option, dropdown B resets but dropdown C does not.

I really need help i cannot seem to find a solution. Please help me out if anyone can.

Here is my code which populates the html dropdowns from the JSON.

```<code>    window.onload = (function() {
  load_json_data("vehicle");

  function load_json_data(id, parent_id) {
    var html_code = "";
    $.getJSON("/js/model/vehicles.json", function(data) {
      html_code += '<option value="">Select the type of the ' + id + "!</option>";
      $.each(data, function(key, value) {
        if (id == "vehicle") {
          if (value.parent_id == "0") {
            html_code +=
              '<option value="' + value.id + '">' + value.name + "</option>";
          }
        } else {
          if (value.parent_id == parent_id) {
            html_code +=
              '<option value="' + value.id + '">' + value.name + "</option>";
          }
        }
      });
      $("#" + id).html(html_code);
    });
  }

  $(document).on("change", "#vehicle", function() {
    var vehicle_id = $(this).val();
    if (vehicle_id != "") {
      load_json_data("brand", vehicle_id);
    } else {
      $("#brand").html('<option value="">Select a vehicle brand!</option>');
      $("#model").html('<option value="">Select a vehicle model!</option>');
    }
  });
  $(document).on("change", "#brand", function() {
    var brand_id = $(this).val();
    if (brand_id != "") {
      load_json_data("model", brand_id);
    } else {
      $("#model").html('<option value="">Select a vehicle model!</option>');
    }
  });
});
</code>```

Thank you!

答:
Create reset function for each drop-down, for which you want to clear data and call that function depending upon the parent drop-down.
In your case, create function for drop-down B and C, and on the change event of drop-down A call the rest function for B and C, similarly on change event of B call reset function of C. </p>

Body:
I have this task to make a dynamic dropdown using Jquery ajax and json in js. Everything works ok, except one thing. To put for example, when I pick something in dropdown A, dropdown B loads items from Json via Ajax and jquery. After I pick an option in dropdown B, dropdown C is populated also from Json file. Now, once I try and switch dropdown B option and do it, dropdown C is populated differently. However, when I try have all 3 dropdowns chosen, and then try to change dropdown A option, dropdown B resets but dropdown C does not.

I really need help i cannot seem to find a solution. Please help me out if anyone can.

Here is my code which populates the html dropdowns from the JSON.

    window.onload = (function() {
  load_json_data("vehicle");

  function load_json_data(id, parent_id) {
    var html_code = "";
    $.getJSON("/js/model/vehicles.json", function(data) {
      html_code += '<option value="">Select the type of the ' + id + "!</option>";
      $.each(data, function(key, value) {
        if (id == "vehicle") {
          if (value.parent_id == "0") {
            html_code +=
              '<option value="' + value.id + '">' + value.name + "</option>";
          }
        } else {
          if (value.parent_id == parent_id) {
            html_code +=
              '<option value="' + value.id + '">' + value.name + "</option>";
          }
        }
      });
      $("#" + id).html(html_code);
    });
  }

  $(document).on("change", "#vehicle", function() {
    var vehicle_id = $(this).val();
    if (vehicle_id != "") {
      load_json_data("brand", vehicle_id);
    } else {
      $("#brand").html('<option value="">Select a vehicle brand!</option>');
      $("#model").html('<option value="">Select a vehicle model!</option>');
    }
  });
  $(document).on("change", "#brand", function() {
    var brand_id = $(this).val();
    if (brand_id != "") {
      load_json_data("model", brand_id);
    } else {
      $("#model").html('<option value="">Select a vehicle model!</option>');
    }
  });
});

Thank you!


问:
AVAudioPlayer plays music in iPod touch 2G and 3G
I'm trying to play an audio file on iPhone and iPod touch with AVAudioPlayer. The code works fine in iPhone and iPod touch 4G, I can hear the music. But when I test it on iPod touch 2G, iPod touch 3G, I can't hear anything.

Below is the code I use to play audio file:

```<code>NSString *zeroAudioPath = [[NSBundle mainBundle] pathForResource:@"TimerBell"
                                                          ofType:@"aif"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:zeroAudioPath];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file
                                                                    error:nil];
[file release];

self.zeroAudioPlayer = audioPlayer;
zeroAudioPlayer.delegate = self;
[audioPlayer release];
[zeroAudioPlayer prepareToPlay];
[zeroAudioPlayer play];
</code>```

答: I found that changing from kAudioSessionCategory_PlayAndRecord to kAudioSessionCategory_AmbientSound corrected this issue.  I suspect this has something to do with a hardware difference on the iPod touch related to recording.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to play an audio file on iPhone and iPod touch with AVAudioPlayer. The code works fine in iPhone and iPod touch 4G, I can hear the music. But when I test it on iPod touch 2G, iPod touch 3G, I can't hear anything.

Below is the code I use to play audio file:

NSString *zeroAudioPath = [[NSBundle mainBundle] pathForResource:@"TimerBell"
                                                          ofType:@"aif"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:zeroAudioPath];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file
                                                                    error:nil];
[file release];

self.zeroAudioPlayer = audioPlayer;
zeroAudioPlayer.delegate = self;
[audioPlayer release];
[zeroAudioPlayer prepareToPlay];
[zeroAudioPlayer play];


问:
Whatsapp Click-to-Chat "Couldn't open link" Error Chrome Android/iPhone
I'm using Whatsapp Click-to-chat functionality, without a phone number. It previously worked but with the new Chrome version 76.0.3809.132, both on iOS and Android is not working anymore. On Android, it's showing a Toast with Couldn't open link. Tried contacting Whatsapp Support but no answer as of yet. With the latest update their own documentation example is not working, link to docs. Any suggestions or experiences?

Link example:

```

Error picture Imgur: picture

A table with href="https://imgur.com/z7sXEjE?" rel="noreferrer">my tested devices and versions on Imgur

答:
The best is to use the custom url scheme format. Universal links do not work well with native clients

```<code>whatsapp://send/?phone=&text&source&data
</code>```

It will work without phone number also.

My issue on a recent breaking-change: Universal links stopped working

There was a great blog post about the issue, however it is already outdated and proposes a php specific solution (nevertheless might gives you a good idea, how to think about the problem)

Body:
I'm using Whatsapp Click-to-chat functionality, without a phone number. It previously worked but with the new Chrome version 76.0.3809.132, both on iOS and Android is not working anymore. On Android, it's showing a Toast with Couldn't open link. Tried contacting Whatsapp Support but no answer as of yet. With the latest update their own documentation example is not working, link to docs. Any suggestions or experiences?

Link example:

Error picture Imgur: picture

A table with my tested devices and versions on Imgur

Body:
The best is to use the custom url scheme format. Universal links do not work well with native clients

whatsapp://send/?phone=&text&source&data

It will work without phone number also.

My issue on a recent breaking-change: Universal links stopped working

There was a great blog post about the issue, however it is already outdated and proposes a php specific solution (nevertheless might gives you a good idea, how to think about the problem)


问:
Reverse elements via pipeline
Is there a function that reverses elements passed via pipeline?

E.g.:

```<code>PS C:\> 10, 20, 30 | Reverse
30
20
10
</code>```

答:
You can use Linq.Enumerable.Reverse, but it's hard work. Either of the following work:

```<code>,(10, 20, 30) | % { [Linq.Enumerable]::Reverse([int[]]$_) }
,([int[]]10, 20, 30) | % { [Linq.Enumerable]::Reverse($_) }
</code>```

The two challenges are putting the whole array into the pipeline rather than one element at a time (solved by making it an array of arrays with the initial comma) and hitting the type signature of Reverse (solved by the [int[]]).

Title: Reverse elements via pipeline

Body:
Is there a function that reverses elements passed via pipeline?

E.g.:

PS C:\> 10, 20, 30 | Reverse
30
20
10

Body:
You can use Linq.Enumerable.Reverse, but it's hard work. Either of the following work:

,(10, 20, 30) | % { [Linq.Enumerable]::Reverse([int[]]$_) }
,([int[]]10, 20, 30) | % { [Linq.Enumerable]::Reverse($_) }

The two challenges are putting the whole array into the pipeline rather than one element at a time (solved by making it an array of arrays with the initial comma) and hitting the type signature of Reverse (solved by the [int[]]).


问:
Different probability for ranges of random numbers
I'm looking for the best way of implementing random number generator, that will allow me to have control over probability from what range the generated number will be returned. To visualize what I'm trying to achieve I have a picture :

So to summarize :
Let's say that my range is 400. At the beginning I'd like to have 5% probability of getting number 0-20. But at some moment in time I'd like to have this probability increased up to 50%. Hope you get the idea.

答:
Hmm, working on your original I had a pretty simple algorithm to generate ranges in an array in the appropriate proportion, then randomly select a range and generate a random number within that range. No doubt it can be optimised if necessary, but it works for me.

It looks like a lot of code, but 3/4 of it is comments, test data and function, the actual randomRange function is only 17 lines of code.

```<code><script type="text/javascript">

function randomRange(dataArray) {

  // Helper function
  function getRandomInRange(s, f) {
    return (Math.random() * (f-s+1) | 0) + s
  }

  // Generate new data array based on probability
  var i, j = dataArray.length;
  var oArray = [];
  var o;
  while (j--) {
    o = dataArray[j];

    // Make sure probability is an integer
    for (i=0, iLen=o.probability|0; i<iLen; i++) {
      oArray.push([o.rangeStart, o.rangeEnd]);
    }
  }

  // Randomly select a range from new data array and
  // generate a random number in that range
  var oEnd = oArray.length;
  var range = oArray[getRandomInRange(0, oArray.length - 1)];
  return getRandomInRange(range[0], range[1]);
}

// Test data set. Probability just has to be
// representative, so 50/50 === 1/1
var dataArray = [
  {
    rangeStart: 0,
    rangeEnd  : 20,
    probability: 1
  },
  {
    rangeStart: 21,
    rangeEnd  : 400,
    probability: 1
  }
];

// Test function to show range and number is randomly
// selected for given probability
function testIt() {
  var el0 = document.getElementById('div0');
  var el1 = document.getElementById('div1');
  function run() {
    var n = randomRange(dataArray);
    if (n <= 20) {
      el0.innerHTML += '*';
    } else {
      el1.innerHTML += '*';
    }
  }
  setInterval(run, 500);
}

</script>

<button onclick="testIt();">Generate random number</button>

<div>Numbers 0 - 20</div>
<div id="div0"></div>
<div>Numbers 21 - 400</div>
<div id="div1"></div>
</code>```

Body:
Hmm, working on your original I had a pretty simple algorithm to generate ranges in an array in the appropriate proportion, then randomly select a range and generate a random number within that range. No doubt it can be optimised if necessary, but it works for me.

It looks like a lot of code, but 3/4 of it is comments, test data and function, the actual randomRange function is only 17 lines of code.

<script type="text/javascript">

function randomRange(dataArray) {

  // Helper function
  function getRandomInRange(s, f) {
    return (Math.random() * (f-s+1) | 0) + s
  }

  // Generate new data array based on probability
  var i, j = dataArray.length;
  var oArray = [];
  var o;
  while (j--) {
    o = dataArray[j];

    // Make sure probability is an integer
    for (i=0, iLen=o.probability|0; i<iLen; i++) {
      oArray.push([o.rangeStart, o.rangeEnd]);
    }
  }

  // Randomly select a range from new data array and
  // generate a random number in that range
  var oEnd = oArray.length;
  var range = oArray[getRandomInRange(0, oArray.length - 1)];
  return getRandomInRange(range[0], range[1]);
}

// Test data set. Probability just has to be
// representative, so 50/50 === 1/1
var dataArray = [
  {
    rangeStart: 0,
    rangeEnd  : 20,
    probability: 1
  },
  {
    rangeStart: 21,
    rangeEnd  : 400,
    probability: 1
  }
];

// Test function to show range and number is randomly
// selected for given probability
function testIt() {
  var el0 = document.getElementById('div0');
  var el1 = document.getElementById('div1');
  function run() {
    var n = randomRange(dataArray);
    if (n <= 20) {
      el0.innerHTML += '*';
    } else {
      el1.innerHTML += '*';
    }
  }
  setInterval(run, 500);
}

</script>

<button onclick="testIt();">Generate random number</button>

<div>Numbers 0 - 20</div>
<div id="div0"></div>
<div>Numbers 21 - 400</div>
<div id="div1"></div>


问:
How I can get access to GCP cloud function from python code using service account?
I've deployed a simple GCP Cloud Function which returns "Hello World!".
I need this function to be under authorization. I unmarked "Allow unauthenticated invocations" checkbox, so only authenticated invocations can call this code.
I also created Service Account and give next roles:
 - Cloud Functions Invoker
 - Cloud Functions Service Agent

my code:

```<code>from google.oauth2 import service_account
from google.auth.transport.urllib3 import AuthorizedHttp

if __name__ == '__main__':
    credentials = service_account.Credentials.from_service_account_file('service-account.json',
        scopes=['https://www.googleapis.com/auth/cloud-platform'],
        subject='service-acc@<project_id>.iam.gserviceaccount.com')
    authed_session = AuthorizedHttp(credentials)
    response = authed_session.urlopen('POST', 'https://us-central1-<project_id>.cloudfunctions.net/main')
    print(response.data)
</code>```

and I've got response:

```<code>b'\n<html><head>\n<meta http-equiv="content-type" content="text/html;charset=utf-8">\n<title>401 Unauthorized</title>\n</head>\n<body text=#000000 bgcolor=#ffffff>\n<h1>Error: Unauthorized</h1>\n<h2>Your client does not have permission to the requested URL <code>/main</code>.</h2>\n<h2></h2>\n</body></html>\n'

</code>```

How to become authorized?

答:
Your example code is generating an access token. Below is a real example that generates an identity token and uses that token to call a Cloud Functions endpoint. The Function needs to have the Cloud Function Invoker role for the service account being used for authorization.</p>

```<code>import json
import base64
import requests

import google.auth.transport.requests
from google.oauth2.service_account import IDTokenCredentials

# The service account JSON key file to use to create the Identity Token
sa_filename = 'service-account.json'

# Endpoint to call
endpoint = 'https://us-east1-replace_with_project_id.cloudfunctions.net/main'

# The audience that this ID token is intended for (example Google Cloud Functions service URL)
aud = 'https://us-east1-replace_with_project_id.cloudfunctions.net/main'

def invoke_endpoint(url, id_token):
    headers = {'Authorization': 'Bearer ' + id_token}

    r = requests.get(url, headers=headers)

    if r.status_code != 200:
        print('Calling endpoint failed')
        print('HTTP Status Code:', r.status_code)
        print(r.content)
        return None

    return r.content.decode('utf-8')

if __name__ == '__main__':
    credentials = IDTokenCredentials.from_service_account_file(
            sa_filename,
            target_audience=aud)

    request = google.auth.transport.requests.Request()

    credentials.refresh(request)

    # This is debug code to show how to decode Identity Token
    # print('Decoded Identity Token:')
    # print_jwt(credentials.token.encode())

    response = invoke_endpoint(endpoint, credentials.token)

    if response is not None:
        print(response)
</code>```

Body:
I've deployed a simple GCP Cloud Function which returns "Hello World!".
I need this function to be under authorization. I unmarked "Allow unauthenticated invocations" checkbox, so only authenticated invocations can call this code.
I also created Service Account and give next roles:
 - Cloud Functions Invoker
 - Cloud Functions Service Agent

my code:

from google.oauth2 import service_account
from google.auth.transport.urllib3 import AuthorizedHttp

if __name__ == '__main__':
    credentials = service_account.Credentials.from_service_account_file('service-account.json',
        scopes=['https://www.googleapis.com/auth/cloud-platform'],
        subject='service-acc@<project_id>.iam.gserviceaccount.com')
    authed_session = AuthorizedHttp(credentials)
    response = authed_session.urlopen('POST', 'https://us-central1-<project_id>.cloudfunctions.net/main')
    print(response.data)

and I've got response:

b'\n\n<meta http-equiv="content-type" content="text/html;charset=utf-8">\n<title>401 Unauthorized</title>\n\n\n
Error: Unauthorized
\n
Your client does not have permission to the requested URL /main.
\n

\n\n'

How to become authorized?

Body:
Your example code is generating an access token. Below is a real example that generates an identity token and uses that token to call a Cloud Functions endpoint. The Function needs to have the Cloud Function Invoker role for the service account being used for authorization.

import json
import base64
import requests

import google.auth.transport.requests
from google.oauth2.service_account import IDTokenCredentials

# The service account JSON key file to use to create the Identity Token
sa_filename = 'service-account.json'

# Endpoint to call
endpoint = 'https://us-east1-replace_with_project_id.cloudfunctions.net/main'

# The audience that this ID token is intended for (example Google Cloud Functions service URL)
aud = 'https://us-east1-replace_with_project_id.cloudfunctions.net/main'

def invoke_endpoint(url, id_token):
    headers = {'Authorization': 'Bearer ' + id_token}

    r = requests.get(url, headers=headers)

    if r.status_code != 200:
        print('Calling endpoint failed')
        print('HTTP Status Code:', r.status_code)
        print(r.content)
        return None

    return r.content.decode('utf-8')

if __name__ == '__main__':
    credentials = IDTokenCredentials.from_service_account_file(
            sa_filename,
            target_audience=aud)

    request = google.auth.transport.requests.Request()

    credentials.refresh(request)

    # This is debug code to show how to decode Identity Token
    # print('Decoded Identity Token:')
    # print_jwt(credentials.token.encode())

    response = invoke_endpoint(endpoint, credentials.token)

    if response is not None:
        print(response)


问:
How can i do an http-request with a post method to an api in Angular 9
This is the first time I'm trying to do that and I don't know exactly how to start, if someone can guide me that would be very help full. I'm trying to do a login and if i want it to work a i have to do an http request with a post method to the API and will return me the information i need, but when I tried said Error 404 with URL, I tried with Postman and said other error that i will let below . I'm not telling that someone have to do it for me , just need someone to tell how can i start

This is the APIhttps://devapi.shocklogic.com/v1.0/:key/Users/login/

To make the petition to this endpoint i have to send this token in the header Token Token-App': '7875d82ca05f8ba818011eb04a890c20cb44c52e'

Also i need to send three params Key, Identifier of the person and Password

Error that Postman said

{
    "type": "error",
    "message": "please make sure your meet the following field requirements",
    "check": 0,
    "passed": false,
    "requirements": [
        [
            "Identifier",
            {
                "is_required": true,
                "requires_value": true,
                "min_length": 1,
                "max_length": 150
            }
        ],
        [
            "Password",
            {
                "is_required": true,
                "requires_value": true,
                "min_length": 1,
                "max_length": 60
            }
        ]
    ]
}
```

答:
here's a sample code doing post request </p>

```<code>let headers = new Headers({'Content-Type': 'application/json'});
headers.append('Authorization','Bearer <your auth here>')
let options = new RequestOptions({headers: headers});
const body = { username, password }; // will depend on how your api will accept
 return this.http.post(APIname,body,options)
  .map(this.extractData)
  .catch(this.handleError);
</code>```

Body:
here's a sample code doing post request

let headers = new Headers({'Content-Type': 'application/json'});
headers.append('Authorization','Bearer <your auth here>')
let options = new RequestOptions({headers: headers});
const body = { username, password }; // will depend on how your api will accept
 return this.http.post(APIname,body,options)
  .map(this.extractData)
  .catch(this.handleError);


问:
conditional conversion from character to date for a dataframe column in r
I have a dataframe I read from an excel file, like below. Date turned out to be in 5-digits format or a date string format.

```<code>df = data.frame(Date = c('42195', '3/31/2016', '42198'), Value = c(123, 445, 222))

Date     Value
42195      123
3/31/2016  445
42198      222
</code>```

I want to clean up the column and convert everything into date format.
I did the following.

```<code>df %>%
  mutate(Date = ifelse(length(Date)==5,as.Date(Date, origin = '1899-12-30'), as.Date(Date) ))
</code>```

I got error like this:

```<code>Error in charToDate(x) : character string is not in a standard unambiguous format
</code>```

What did I do wrong? I could not figure out why after many attempts to fix it.
Thanks a lot.

答:
There are few changes that you need to do :

1) Instead of length(Date)==5, I guess you are looking for nchar

2) To change excel date to R date, they need to be numeric. Currently they are factors.

3) You need to provide specific format to as.Date when date is not in standard format.

4) Use if_else instead of ifelse since the latter would change them to numbers.

```<code>library(dplyr)

df %>%
  mutate(Date = as.character(Date),
         Date = if_else(nchar(Date) ==5,
                   as.Date(as.numeric(Date), origin = '1899-12-30'),
                   as.Date(Date, "%m/%d/%Y")))

#        Date Value
#1 2015-07-10   123
#2 2016-03-31   445
#3 2015-07-13   222
</code>```

Body:
I have a dataframe I read from an excel file, like below. Date turned out to be in 5-digits format or a date string format.

df = data.frame(Date = c('42195', '3/31/2016', '42198'), Value = c(123, 445, 222))

Date     Value
42195      123
3/31/2016  445
42198      222

I want to clean up the column and convert everything into date format.
I did the following.

df %>%
  mutate(Date = ifelse(length(Date)==5,as.Date(Date, origin = '1899-12-30'), as.Date(Date) ))

I got error like this:

Error in charToDate(x) : character string is not in a standard unambiguous format

What did I do wrong? I could not figure out why after many attempts to fix it.
Thanks a lot.

Body:
There are few changes that you need to do :

1) Instead of length(Date)==5, I guess you are looking for nchar

2) To change excel date to R date, they need to be numeric. Currently they are factors.

3) You need to provide specific format to as.Date when date is not in standard format.

4) Use if_else instead of ifelse since the latter would change them to numbers.

library(dplyr)

df %>%
  mutate(Date = as.character(Date),
         Date = if_else(nchar(Date) ==5,
                   as.Date(as.numeric(Date), origin = '1899-12-30'),
                   as.Date(Date, "%m/%d/%Y")))

#        Date Value
#1 2015-07-10   123
#2 2016-03-31   445
#3 2015-07-13   222


问:
wxpython: How do I make my window full-sized when I make the window?
I'm new to wxpython and I want to know how to make my window full sized. How would I do this? Here's my code:</p>

```<code>import wx

app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True)
app.MainLoop()
</code>```

答:
```<code>import wx

app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Maximize(True)
frame.Show(True)
app.MainLoop()
</code>```

Body:
I'm new to wxpython and I want to know how to make my window full sized. How would I do this? Here's my code:

import wx

app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True)
app.MainLoop()


问:
carthage bootstrap fails because of parallel git processes accessing shared cache index.lock file
I'm triggering multiple iOS builds in parallel from Jenkins on a Jenkins slave.
When the build triggers the below command I get an error.

Command

```<code>carthage bootstrap --no-use-binaries --platform ios --use-ssh --cache-builds
</code>```

Output

```<code>2020-01-29 21:34:58.471 carthage[85379:2625480] INFO: fetch-response is unable to open the file /Users/user/Library/Caches/carthage/fsCachedData/7A4CE621-0AC6-4FAF-B0CE-33FDD32A0113. Errno: 2
*** Checking out Alamofire at "4.8.2"
*** Checking out ios-client at "3.0.0"
*** Checking out stripe-ios at "v18.3.0"
*** Checking out swift-protobuf at "1.5.0"
A shell task (/usr/bin/env git checkout --quiet --force v18.3.0 (launched in /Users/user/Library/Caches/org.carthage.CarthageKit/dependencies/stripe-ios)) failed with exit code 128:
fatal: Unable to create '/Users/user/Library/Caches/org.carthage.CarthageKit/dependencies/stripe-ios/./index.lock': File exists.

Another git process seems to be running in this repository, e.g.
an editor opened by 'git commit'. Please make sure all processes
are terminated then try again. If it still fails, a git process
may have crashed in this repository earlier:
remove the file manually to continue.

make: *** [carthage-install] Error 1
</code>```

How can this issue be fixed? I guess this happens because multiple processes are trying to access the shared Carthage cache.

答:
Did you find this issue in the Carthage repository? Seems like it describes the problem you are having: https://github.com/Carthage/Carthage/issues/1187

The issue is that Carthage was never intended to be run in parallel since it uses locks that can hang if multiple Carthage jobs run as the same user. If you configure your CI machine to have multiple users, where one Carthage job runs for each user, this problem should not occur. If you have one user logged in automatically when the machine starts where that user starts multiple build agents, and those agents can overlap in their Carthage activity, builds can fail in the way you describe.

There is a fork of Carthage that claims to have addressed this problem: https://github.com/nsoperations/Carthage - I have not tried it yet but think I will. If you are stuck using Carthage, and you want your Mac CI machine to recover from power loss to a state where multiple build agents (e.g. for Buildkite) are running I think it might be the only answer. If I knew a reliable way to cause multiple users to become logged in automatically, with agent processes started by each as they become logged in, that would make continuing to use the main branch of Carthage possible.

Body:
I'm triggering multiple iOS builds in parallel from Jenkins on a Jenkins slave.
When the build triggers the below command I get an error.

Command

carthage bootstrap --no-use-binaries --platform ios --use-ssh --cache-builds

Output

2020-01-29 21:34:58.471 carthage[85379:2625480] INFO: fetch-response is unable to open the file /Users/user/Library/Caches/carthage/fsCachedData/7A4CE621-0AC6-4FAF-B0CE-33FDD32A0113. Errno: 2
*** Checking out Alamofire at "4.8.2"
*** Checking out ios-client at "3.0.0"
*** Checking out stripe-ios at "v18.3.0"
*** Checking out swift-protobuf at "1.5.0"
A shell task (/usr/bin/env git checkout --quiet --force v18.3.0 (launched in /Users/user/Library/Caches/org.carthage.CarthageKit/dependencies/stripe-ios)) failed with exit code 128:
fatal: Unable to create '/Users/user/Library/Caches/org.carthage.CarthageKit/dependencies/stripe-ios/./index.lock': File exists.

Another git process seems to be running in this repository, e.g.
an editor opened by 'git commit'. Please make sure all processes
are terminated then try again. If it still fails, a git process
may have crashed in this repository earlier:
remove the file manually to continue.

make: *** [carthage-install] Error 1

How can this issue be fixed? I guess this happens because multiple processes are trying to access the shared Carthage cache.


问:
Array not updating in for loop
```<code>L_list = np.array([7,8,9])
one_list = [1] * 3
L_vec = np.diag(one_list) # making a 2d array with 1s in diagonal position

for j in range(2):
    for i in range(1, 3):
        L_vec[i,j] = L_list[j]
</code>```

I want to set up 3x3 L_vec with 1s in diagonal position and update the the L_vec with elements in L_list.

I went through the debug and nothing is changing. I can't figure out why. Can you explain what is going on?

答:
Adding a print(L_vec) after your code shows me this:

```<code>[[1 0 0]
 [7 8 0]
 [7 8 1]]
</code>```

So, something has definitely changed. Is this not the result you expected to get, or did you mean something else by "nothing is changing"?

Title: Array not updating in for loop

Body:
L_list = np.array([7,8,9])
one_list = [1] * 3
L_vec = np.diag(one_list) # making a 2d array with 1s in diagonal position

for j in range(2):
    for i in range(1, 3):
        L_vec[i,j] = L_list[j]

I want to set up 3x3 L_vec with 1s in diagonal position and update the the L_vec with elements in L_list.

I went through the debug and nothing is changing. I can't figure out why. Can you explain what is going on?

Body:
Adding a print(L_vec) after your code shows me this:

[[1 0 0]
 [7 8 0]
 [7 8 1]]

So, something has definitely changed. Is this not the result you expected to get, or did you mean something else by "nothing is changing"?


答:
Your Arrow class could potentially have a DrawMethod which takes a control

Your UserControl, should publish events

You form should listen to the UserControl Events

Your form should override OnPaint to draw the method on demand

Title: How can I draw a line in my form from another class?

Body:
I have 3 classes in my program:

Arrow (it contains the logic for drawing arrow, and all required information about it, like: starting point, ending point, etc.)

Form1 (that contains the drawing area(basically panel), where this arrow will be located in the future)

UserControl, is located in Form1 (I did Form1.Controls.Add(UserControl)). It has a Form1 as a parent. In this UserControl, I have a button, when I click it, an arrow should be drawn on the Form1's drawing area.

And I'm so confused with the logic that this program should have. I tried to create Arrow class object in the UserControl.Button_Click(), and call all the Arrow's methods from there, but I can't access to Form1's controls. I also thought maybe I can create object of Arrow in the Form1. So I tried to subscribe event UserControl.Button_Click() with some Form1's delegate, but I don't know how to do it. In this case, does delegate and the method that this delegate have as a reference should be Static?

So this is how my code looks like.
(I little bit simplified and shortened my classes)
Arrow:

public class Arrow
{
    public Point PointBeginning { get => pointBeginning; set => pointBeginning = value; }
    public Point PointEnding { get => pointEnding; set => pointEnding = value; }
    public int ArrowClickCounter { get => arrowClickCounter; set => arrowClickCounter = value; }

    public void Draw(object sender, MouseEventArgs e)
    {
        //code for drawing
    }
}

Form1:

public class Form1
{
    public delegate void DrawArrowDelegate(object sender, MouseEventArgs e);
    DrawArrowDelegate drawArrowDelegate = DrawArrow;
    /* .. */

    private void DrawArrow(object sender, MouseEventArgs e)
    {
        Arrow arrow = new Arrow();
        arrow.PointBegining = //some point
        arrow.PointEnding = //some another point
        arrow.Draw(sender, e);
    }
}

UserControl:

public class UserControl
{
    /*...*/

    private void button_MouseClick(object sender, MouseEventArgs e)
    {
        //And here i somehow want to call delegate. But don't know how :(
    }
}

Sorry for such confused code :(

Can you please recommend me something?


问:
Wordpress/Elementor Hamburger Menu issue
I'm creating a website for a friend using wordpress and elementor. I'm struggling to understand why the drop-down menu won't work when I put to a mobile screen resolution. When I'm editing it within the elementor editor, it works fine, when I publish it it doesn't work at all.

http://jungledlondon.com/

Any help would be greatly appreciated.

Thanks

答:
I found an error triggered by JavaScript.
I found this on Chrome Console:

```<code>Uncaught TypeError: Cannot read property 'top' of undefined
    at HTMLDocument.<anonymous> (main-menu.js?ver=1.0.3:24)
    at i (jquery.js?ver=1.12.4-wp:2)
    at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4-wp:2)
    at Function.ready (jquery.js?ver=1.12.4-wp:2)
    at HTMLDocument.J (jquery.js?ver=1.12.4-wp:2)
</code>```

I'm not sullying sure about this, but it looks that the js code that makes the primary button displays the main menu is not working.
If you are the developer you need to check that code again.

Below is the entire function that is triggering this error:

```<code>( function( $ ) {
$(document).ready(function() {

    // Nav Main DD Toggle
    $( ".navbarprimary .dropdowntoggle" ).click(function() {
        if( $(this).parent('li').hasClass('navbarprimary-open') ) {
            $(this).parent('li').removeClass('navbarprimary-open');
        } else {
            $(this).parent('li').addClass('navbarprimary-open');
        }

        if( $(this).children('span').hasClass('fa-chevron-circle-down') ) {
            $(this).children('span').removeClass('fa-chevron-circle-down');
            $(this).children('span').addClass('fa-chevron-circle-right');
        } else {
            $(this).children('span').removeClass('fa-chevron-circle-right');
            $(this).children('span').addClass('fa-chevron-circle-down');
        }

        return false;
    });

    // Sticky nav bar
    var h = $('.navbarprimary').offset().top;
    $(window).scroll(function () {
        if( $(this).scrollTop() > h ) {
            $('.navbarprimary').addClass('sticky_menu_top');
        } else {
            $('.navbarprimary').removeClass('sticky_menu_top');
        }

    });

});
} )( jQuery );
</code>```

Body:
I found an error triggered by JavaScript.
I found this on Chrome Console:

Uncaught TypeError: Cannot read property 'top' of undefined
    at HTMLDocument.<anonymous> (main-menu.js?ver=1.0.3:24)
    at i (jquery.js?ver=1.12.4-wp:2)
    at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4-wp:2)
    at Function.ready (jquery.js?ver=1.12.4-wp:2)
    at HTMLDocument.J (jquery.js?ver=1.12.4-wp:2)

I'm not sullying sure about this, but it looks that the js code that makes the primary button displays the main menu is not working.
If you are the developer you need to check that code again.

Below is the entire function that is triggering this error:

( function( $ ) {
$(document).ready(function() {

    // Nav Main DD Toggle
    $( ".navbarprimary .dropdowntoggle" ).click(function() {
        if( $(this).parent('li').hasClass('navbarprimary-open') ) {
            $(this).parent('li').removeClass('navbarprimary-open');
        } else {
            $(this).parent('li').addClass('navbarprimary-open');
        }

        if( $(this).children('span').hasClass('fa-chevron-circle-down') ) {
            $(this).children('span').removeClass('fa-chevron-circle-down');
            $(this).children('span').addClass('fa-chevron-circle-right');
        } else {
            $(this).children('span').removeClass('fa-chevron-circle-right');
            $(this).children('span').addClass('fa-chevron-circle-down');
        }

        return false;
    });

    // Sticky nav bar
    var h = $('.navbarprimary').offset().top;
    $(window).scroll(function () {
        if( $(this).scrollTop() > h ) {
            $('.navbarprimary').addClass('sticky_menu_top');
        } else {
            $('.navbarprimary').removeClass('sticky_menu_top');
        }

    });

});
} )( jQuery );


问:
AWS xray put trace segment command return error
I am trying to send segment doc manually using the CLI with example on this page: https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html#xray-api-segments

I created my own Trace ID and also start and end time.

The command i used are:

```<code>> DOC='{"trace_id": "'$TRACE_ID'", "id": "6226467e3f841234", "start_time": 1581596193, "end_time": 1581596198, "name": "test.com"}'

>echo $DOC
{"trace_id": "1-5e453c54-3dc3e03a3c86f97231d06c88", "id": "6226467e3f845502", "start_time": 1581596193, "end_time": 1581596198, "name": "test.com"}

> aws xray put-trace-segments --trace-segment-documents $DOC
{
"UnprocessedTraceSegments": [
{
"ErrorCode": "ParseError",
"Message": "Invalid segment. ErrorCode: ParseError"
},
{
"ErrorCode": "MissingId",
"Message": "Invalid segment. ErrorCode: MissingId"
},
{
"ErrorCode": "MissingId",
"Message": "Invalid segment. ErrorCode: MissingId"
},
.................
</code>```

The put-trace-segment keep giving me error. The segment doc comply with the JSON schema too. Am i missing something else?

Thanks.

答:
I need to enclose the JSON with "..". The command that works for me was: aws xray put-trace-segments --trace-segment-documents "$DOC"

This is probably due an error in the documentation or that the xray team was using another kind of shell.

Body:
I am trying to send segment doc manually using the CLI with example on this page: https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html#xray-api-segments

I created my own Trace ID and also start and end time.

The command i used are:

> DOC='{"trace_id": "'$TRACE_ID'", "id": "6226467e3f841234", "start_time": 1581596193, "end_time": 1581596198, "name": "test.com"}'

>echo $DOC
{"trace_id": "1-5e453c54-3dc3e03a3c86f97231d06c88", "id": "6226467e3f845502", "start_time": 1581596193, "end_time": 1581596198, "name": "test.com"}

> aws xray put-trace-segments --trace-segment-documents $DOC
{
"UnprocessedTraceSegments": [
{
"ErrorCode": "ParseError",
"Message": "Invalid segment. ErrorCode: ParseError"
},
{
"ErrorCode": "MissingId",
"Message": "Invalid segment. ErrorCode: MissingId"
},
{
"ErrorCode": "MissingId",
"Message": "Invalid segment. ErrorCode: MissingId"
},
.................

The put-trace-segment keep giving me error. The segment doc comply with the JSON schema too. Am i missing something else?

Thanks.


问:
Finding the maximum values of a set of local maxima using matplotlib and numpy
I want to ask a question about finding the maxima of a set of peaks using matplotlib and numpy.

I have been given data containing peaks and asked to calculate the maxima of the set of peaks.

Below is a picture of the peaks.

I discovered the find_peaks method and attempted to solve the problem using this.

I wrote the following block of code in Jupyter:

```<code>%pylab inline
from scipy.signal import find_peaks

testdata = loadtxt("testdata.dat", usecols=(0,1))
testdata_x = testdata[100:200,0]
testdata_y = testdata[100:200,1]
plot(testdata_x, testdata_y)
show()

peaks = find_peaks(testdata_y)
peaks
</code>```

However, I get the following output for peaks:

```<code>(array([ 7, 12, 36, 40, 65, 69, 93, 97]), {})
</code>```

I cannot understand why I get an output as above and am struggling to find a solution.

I attempted also to pass the following:

```<code>peaks = find_peaks(testdata_y, testdata_x)
</code>```

but this was to no avail.

How can I sort out the matter?

I have attached the data file here as a download link if necessary (hoested on filehosting.org)

答:
Like the comments say, the values returned by find_peaks are the indices (or locations) of the peaks.

To find the values of these peaks, use the peak indices to get the values out of testdata_y. Then you can get the max.

%pylab inline
from scipy.signal import find_peaks

testdata = loadtxt("testdata.dat", usecols=(0,1))
testdata_x = testdata[100:200,0]
testdata_y = testdata[100:200,1]
plot(testdata_x, testdata_y)
show()

peaks = find_peaks(testdata_y)
peak_values = testdata_y[peaks[0]]
max_peak = max(peak_values)
```

Body:
I want to ask a question about finding the maxima of a set of peaks using matplotlib and numpy.

I have been given data containing peaks and asked to calculate the maxima of the set of peaks.

Below is a picture of the peaks.

I discovered the find_peaks method and attempted to solve the problem using this.

I wrote the following block of code in Jupyter:

%pylab inline
from scipy.signal import find_peaks

testdata = loadtxt("testdata.dat", usecols=(0,1))
testdata_x = testdata[100:200,0]
testdata_y = testdata[100:200,1]
plot(testdata_x, testdata_y)
show()

peaks = find_peaks(testdata_y)
peaks

However, I get the following output for peaks:

(array([ 7, 12, 36, 40, 65, 69, 93, 97]), {})

I cannot understand why I get an output as above and am struggling to find a solution.

I attempted also to pass the following:

peaks = find_peaks(testdata_y, testdata_x)

but this was to no avail.

How can I sort out the matter?

I have attached the data file here as a download link if necessary (hoested on filehosting.org)


问:
Get access token to EWS and User.Read.All
I try to get an access token to the scopes: 'https://outlook.office.com/EWS.AccessAsUser.All', 'User.Read.All'.

If I use the following URL to get authorization code: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?scope=https%3A%2F%2Foutlook.office.com%2FEWS.AccessAsUser.All+User.Read.All&client_id=AAA...ZZZ&redirect_uri=http%3A%2F%2Flocalhost%3A9999&response_type=code
an access token response is:

```<code>{
'scope': 'https://outlook.office.com/EWS.AccessAsUser.All https://outlook.office.com/User.Read https://outlook.office.com/User.Read.All',
'ext_expires_in': 3599,
'expires_in': 3599,
'token_type': 'Bearer',
'access_token': '123...zzz'
}
</code>```

Please note the scope in the response.
This access token works in EWS requests without errors. But requests to MS Graph API return:

```<code>{
    "error": {
        "code": "InvalidAuthenticationToken",
        "innerError": {
            "date": "2020-02-15T19:45:50",
            "request-id": "4542b743-05e1-4555-b612-e0419c3b624b"
        },
        "message": "Access token validation failure. Invalid audience."
    }
}
</code>```

If I use the following URL to get authorization code: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A9999&client_id=AAA...ZZZ&scope=User.Read.All+https%3A%2F%2Foutlook.office.com%2FEWS.AccessAsUser.All&response_type=code an access token response is:

```<code>{
'scope': 'EWS.AccessAsUser.All User.Read User.Read.All profile openid email',
'ext_expires_in': 3599,
'access_token': '0123...zzz',
'token_type': 'Bearer',
 'expires_in': 3599
}
</code>```

Again, please note the scope in the response.
This access token works in MS Graph requests without errors. But EWS requests return the error:

```<code>Error: Microsoft.Exchange.WebServices.Data.ServiceRequestException: The request failed. The remote server returned an error: (401) Unauthorized. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()
</code>```

MSAL doesn't work in this case too.

```<code>var pcaOptions = new PublicClientApplicationOptions
{
  ClientId = _appId,
  TenantId = _tenantId
};
var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(pcaOptions).Build();
var ewsScopes = new string[] { "User.Read.All", "https://outlook.office.com/EWS.AccessAsUser.All" };
var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();
foreach (var s in authResult.Scopes)
{
    Console.WriteLine($"Scope: {s}");
}
</code>```

If https://outlook.office.com/EWS.AccessAsUser.All is in the scope list, an access token works in EWS requests. A request to MS Graph returns the error:

```<code>Error: Status Code: Unauthorized
Microsoft.Graph.ServiceException: Code: InvalidAuthenticationToken
Message: Access token validation failure. Invalid audience.
</code>```

答: According to the information you provided,  you want to request access token to call Microsoft Graph and Outlook Rest API and you use one request to request the access token for the two API. But we cannot do that. Because All the Microsoft Provided authentication flow does not allow multiple Resource/Scope while you would request for token. In other words, one request just can request the access token for Microsoft graph or Outlook Rest API. For more details, please refer to Accessing Multiple resources in a single authorization request

Body:
I try to get an access token to the scopes: 'https://outlook.office.com/EWS.AccessAsUser.All', 'User.Read.All'.

If I use the following URL to get authorization code: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?scope=https%3A%2F%2Foutlook.office.com%2FEWS.AccessAsUser.All+User.Read.All&client_id=AAA...ZZZ&redirect_uri=http%3A%2F%2Flocalhost%3A9999&response_type=code
an access token response is:

{
'scope': 'https://outlook.office.com/EWS.AccessAsUser.All https://outlook.office.com/User.Read https://outlook.office.com/User.Read.All',
'ext_expires_in': 3599,
'expires_in': 3599,
'token_type': 'Bearer',
'access_token': '123...zzz'
}

Please note the scope in the response.
This access token works in EWS requests without errors. But requests to MS Graph API return:

{
    "error": {
        "code": "InvalidAuthenticationToken",
        "innerError": {
            "date": "2020-02-15T19:45:50",
            "request-id": "4542b743-05e1-4555-b612-e0419c3b624b"
        },
        "message": "Access token validation failure. Invalid audience."
    }
}

If I use the following URL to get authorization code: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A9999&client_id=AAA...ZZZ&scope=User.Read.All+https%3A%2F%2Foutlook.office.com%2FEWS.AccessAsUser.All&response_type=code an access token response is:

{
'scope': 'EWS.AccessAsUser.All User.Read User.Read.All profile openid email',
'ext_expires_in': 3599,
'access_token': '0123...zzz',
'token_type': 'Bearer',
 'expires_in': 3599
}

Again, please note the scope in the response.
This access token works in MS Graph requests without errors. But EWS requests return the error:

Error: Microsoft.Exchange.WebServices.Data.ServiceRequestException: The request failed. The remote server returned an error: (401) Unauthorized. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()

MSAL doesn't work in this case too.

var pcaOptions = new PublicClientApplicationOptions
{
  ClientId = _appId,
  TenantId = _tenantId
};
var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(pcaOptions).Build();
var ewsScopes = new string[] { "User.Read.All", "https://outlook.office.com/EWS.AccessAsUser.All" };
var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();
foreach (var s in authResult.Scopes)
{
    Console.WriteLine($"Scope: {s}");
}

If https://outlook.office.com/EWS.AccessAsUser.All is in the scope list, an access token works in EWS requests. A request to MS Graph returns the error:

Error: Status Code: Unauthorized
Microsoft.Graph.ServiceException: Code: InvalidAuthenticationToken
Message: Access token validation failure. Invalid audience.


问:
C# convert image data to bytes array
I have a image with src = "data:image/png;base64....".

I want to convert this image into byte array byte[].

I have tried something like this:

```<code>string[] Base64 = ImageData.Split(new char[] { ',' });

byte[] imageBytes = System.Convert.FromBase64String(Base64[1].ToString());
</code>```

What am I doing wrong here?

答:
C# 8 version, without using Regex or MemoryStream:

var base64Image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAJFBMVEUAAACAgIAAAAD/AACAAAAAAP8AgAAA/wAAAICAgAD//wD///9wmW9uAAAAAXRSTlMAQObYZgAAAAFiS0dECx/XxMAAAAAHdElNRQfiBhoANycSsUctAAAA60lEQVQoz53Qv07DMBAG8DtH2X2JsscfaaFMIe4TFB4gRLLEzNAHYCA7ElLnbGVkw0+JnYSqDVu/LT9d7o+JrgovQf2rWJbUaiGalZx/J1QzJESfhuhaEGLmujKh/GEUyNwi4dzi0e6A+FdKJVvOK2t3e5ipRSm2qewW/XssaVPKSmlu7HY9geaUM+DJNhMoatlFqXDbv5mxRSsuwwHY969mvLVopbtzL8B6HMuKi2esXLc5TnsQgwt8uu7eD2baXZAF+Pjy3zNQPOQA74e/e0nC2I33OAFxoOOPOX+msNtwAVE0XcoSSOi6/ALgpCd992FfggAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxOC0wNi0yNlQwMDo1NTozOS0wNDowMAwZ2oMAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTgtMDYtMjZUMDA6NTU6MzktMDQ6MDB9RGI/AAAAAElFTkSuQmCC";

var offset = base64Image.IndexOf(',') + 1;

var imageInBytes = Convert.FromBase64String(base64Image[offset..^0]);
```

Title: C# convert image data to bytes array

Body:
I have a image with src = "data:image/png;base64....".

I want to convert this image into byte array byte[].

I have tried something like this:

string[] Base64 = ImageData.Split(new char[] { ',' });

byte[] imageBytes = System.Convert.FromBase64String(Base64[1].ToString());

What am I doing wrong here?


问:
Angular: Setting the default value in mat select from API call
What is the optimal way of setting the Default Value for a Angular Material Select dropdown? The mat select is calling an API which populates the dropdown list. Then its preselecting the value to defaultAddressFormat variable. Its being done in the subscribe function.

Curious if there is more optimal way of doing this,
this.addressService.getAddressFormatAll() is an observable

After presetting value, user should be able to select different selection if needed.

If the default is set before API fully loads,  sometimes it may not render, so being called in subscribe method.

```<code>this.addressService.getAddressFormatAll().subscribe(res => {
    this.addressFormatList = res.body;
    if (this.addressFormatList.length > 1) {
      this.addressHeaderForm.patchValue({ addressFormat: this.defaultAddressFormat });
    }
});

<mat-form-field>
     <mat-label>Address Format</mat-label>
     <mat-select
          formControlName = "addressFormat"
          [compareWith]="compareAddressFormatDataObjects"
          placeholder ="Select"
          (selectionChange)="addressFormatChangeEvent($event)" required >
          <mat-option (click)="addressHeaderForm.controls.addressFormat.reset()">Select</mat-option>
          <mat-option
               *ngFor="let addressFormatItem of addressFormatList"
               [value]="addressFormatItem"
           >
           {{addressFormatItem.addressFormatDescription}}
           </mat-option>
      </mat-select>
  </mat-form-field>
</code>```

Other resources:

Set default option in mat-select

Angular Material: mat-select not selecting default

答:
This is already one of the optimal ways of doing so. As you have known, HTTP requests are asynchronous, thus doing something like:

```<code>this.addressService.getAddressFormatAll().subscribe()
this.addressHeaderForm.patchValue({ addressFormat: this.defaultAddressFormat });
</code>```

Won't work, as the patchValue method will be called before getAddressFormatAll has been subscribed and returned.

Therefore, your code is valid, and I don't think there is a need to change anything within it.

Of course, there areyou could choose to handle it as a side effect through RxJS pipeline, but doing so would bring no additional benefit, unless you are working with other operations, such as additional asynchronous methods to be called.

```<code>this.addressService.getAddressFormatAll()
  pipe(
    tap((res) => {
      this.addressFormatList = res.body;
      if (this.addressFormatList.length > 1) {
        this.addressHeaderForm.patchValue({ addressFormat: this.defaultAddressFormat });
      }
    }),
  ).subscribe();
</code>```

Alternatively, you can make use of the async pipe. One benefit of doing so, is that you do not need to manually unsubscribe on your component.

```<code>this.addressFormatList = this.addressService.getAddressFormatAll()
</code>```

And on your component.html,

```<code><mat-option
  *ngFor="let addressFormatItem of addressFormatList | async"
  [value]="addressFormatItem"
>
</code>```

Body:
What is the optimal way of setting the Default Value for a Angular Material Select dropdown? The mat select is calling an API which populates the dropdown list. Then its preselecting the value to defaultAddressFormat variable. Its being done in the subscribe function.

Curious if there is more optimal way of doing this,
this.addressService.getAddressFormatAll() is an observable

After presetting value, user should be able to select different selection if needed.

If the default is set before API fully loads,  sometimes it may not render, so being called in subscribe method.

this.addressService.getAddressFormatAll().subscribe(res => {
    this.addressFormatList = res.body;
    if (this.addressFormatList.length > 1) {
      this.addressHeaderForm.patchValue({ addressFormat: this.defaultAddressFormat });
    }
});

<mat-form-field>
     <mat-label>Address Format</mat-label>
     <mat-select
          formControlName = "addressFormat"
          [compareWith]="compareAddressFormatDataObjects"
          placeholder ="Select"
          (selectionChange)="addressFormatChangeEvent($event)" required >
          <mat-option (click)="addressHeaderForm.controls.addressFormat.reset()">Select</mat-option>
          <mat-option
               *ngFor="let addressFormatItem of addressFormatList"
               [value]="addressFormatItem"
           >
           {{addressFormatItem.addressFormatDescription}}
           </mat-option>
      </mat-select>
  </mat-form-field>

Other resources:

Set default option in mat-select

Angular Material: mat-select not selecting default

Body:
This is already one of the optimal ways of doing so. As you have known, HTTP requests are asynchronous, thus doing something like:

this.addressService.getAddressFormatAll().subscribe()
this.addressHeaderForm.patchValue({ addressFormat: this.defaultAddressFormat });

Won't work, as the patchValue method will be called before getAddressFormatAll has been subscribed and returned.

Therefore, your code is valid, and I don't think there is a need to change anything within it.

Of course, there areyou could choose to handle it as a side effect through RxJS pipeline, but doing so would bring no additional benefit, unless you are working with other operations, such as additional asynchronous methods to be called.

this.addressService.getAddressFormatAll()
  pipe(
    tap((res) => {
      this.addressFormatList = res.body;
      if (this.addressFormatList.length > 1) {
        this.addressHeaderForm.patchValue({ addressFormat: this.defaultAddressFormat });
      }
    }),
  ).subscribe();

Alternatively, you can make use of the async pipe. One benefit of doing so, is that you do not need to manually unsubscribe on your component.

this.addressFormatList = this.addressService.getAddressFormatAll()

And on your component.html,

<mat-option
  *ngFor="let addressFormatItem of addressFormatList | async"
  [value]="addressFormatItem"
>


问:
dequeueBuffer: can't dequeue multiple buffers without setting the buffer count
I'm getting the error below on Android 4.4.2 Moto X 2013 in a Rhomobile 5.0.2 WebView app. The app is compiled with SDK 19 and minAPI 17.

After some research it seems that this is an issue with Snapdragon 800 / Adreno GPU devices:

here and here are the links to this problem on google issue tracker

Disabling hardware acceleration is not really an option, because it makes the WebView very sluggish.

Since the error is:

```<code>dequeueBuffer: can't dequeue multiple buffers without setting the buffer count
</code>```

How can I set the buffer count in the com.rhomobile.rhodes.RhodesActivity ?

```<code>11-08 18:28:31.227: I/SFPerfTracer(238):      triggers: (rate: 0:0) (423387 sw vsyncs) (0 skipped) (0:361861 vsyncs) (2:863582)
11-08 18:28:31.328: W/Adreno-EGLSUB(4749): <DequeueBuffer:593>: dequeue native buffer fail: Unknown error 2147483646, buffer=0x61213afc, handle=0x0
11-08 18:28:31.331: W/Adreno-EGLSUB(4749): <SwapBuffers:1343>: Invalid native buffer. Failed to queueBuffer
11-08 18:28:31.331: W/Adreno-EGLSUB(4749): <updater_thread:456>: native buffer is NULL
11-08 18:28:31.346: E/BufferQueue(238): [com.myapp.myapp/com.rhomobile.rhodes.RhodesActivity] dequeueBuffer: can't dequeue multiple buffers without setting the buffer count
11-08 18:28:31.346: W/Adreno-EGLSUB(4749): <DequeueBuffer:593>: dequeue native buffer fail: Invalid argument, buffer=0x61213afc, handle=0x0
11-08 18:28:31.347: W/Adreno-ES20(4749): <gl2_surface_swap:43>: GL_OUT_OF_MEMORY
11-08 18:28:31.347: W/Adreno-EGL(4749): <qeglDrvAPI_eglSwapBuffers:3596>: EGL_BAD_SURFACE
11-08 18:28:31.347: W/HardwareRenderer(4749): EGL error: EGL_BAD_SURFACE
11-08 18:28:31.352: W/HardwareRenderer(4749): Mountain View, we've had a problem here. Switching back to software rendering.
11-08 18:28:31.478: D/qdgralloc(4749): Invalid gralloc handle (at 0x0): ver(-1/12) ints(-1/12) fds(-1/2) magic(????/gmsm)
11-08 18:28:31.478: W/GraphicBufferMapper(4749): lock(...) failed -22 (Invalid argument)
11-08 18:28:31.478: W/Surface(4749): failed locking buffer (handle = 0x0)
11-08 18:28:31.531: E/ViewRootImpl(4749): Could not lock surface
11-08 18:28:31.531: E/ViewRootImpl(4749): java.lang.IllegalArgumentException
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Surface.nativeLockCanvas(Native Method)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Surface.lockCanvas(Surface.java:243)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl.drawSoftware(ViewRootImpl.java:2466)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl.draw(ViewRootImpl.java:2440)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2284)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1914)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1024)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5796)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Choreographer.doCallbacks(Choreographer.java:574)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Choreographer.doFrame(Choreographer.java:544)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.os.Handler.handleCallback(Handler.java:733)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.os.Handler.dispatchMessage(Handler.java:95)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.os.Looper.loop(Looper.java:136)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.app.ActivityThread.main(ActivityThread.java:5102)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at java.lang.reflect.Method.invokeNative(Native Method)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at java.lang.reflect.Method.invoke(Method.java:515)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
This is an out of memory problem as it is indicated here:

11-08 18:28:31.347: W/Adreno-ES20(4749): <gl2_surface_swap:43>:
GL_OUT_OF_MEMORY

android.view.Surface is making more updates then the GPU can handle. I am not sure that you can even try-catch this one.

I also believe that on many devices where there is no crash the users will experience occasional UI lags.

I faced a similar problem a few years ago. In my case, it was primarily lags, but I believe that the problem is the same.

To solve it I added a counter to measure the frame rate. I saw that the frame rate is high but then all of a sudden it falls badly, so I applied a balance-logic to search for the highest FPS that will not lag.

Start with 60 FPS

If its lags, divide the FPS by 2

If it's not, then set it to average between the last value and the current.

repeat until you are happy ;)

It's basically a binary search for the perfect FPS.

In your case, it's a bit more tricky, since you experience crashes, so you will have to persist the FPS counter, and be more careful with the search.

Send FPS logs to your server. Once you have enough data, you can be smarter with the FPS staring point per device module.

As far as putting your hands on the WebView SurfaceView I guess this is not trivial as well, but we are talking about Android 4.4.2, so there nothing you can't do with reflection :)

Body:
I'm getting the error below on Android 4.4.2 Moto X 2013 in a Rhomobile 5.0.2 WebView app. The app is compiled with SDK 19 and minAPI 17.

After some research it seems that this is an issue with Snapdragon 800 / Adreno GPU devices:

here and here are the links to this problem on google issue tracker

Disabling hardware acceleration is not really an option, because it makes the WebView very sluggish.

Since the error is:

dequeueBuffer: can't dequeue multiple buffers without setting the buffer count

How can I set the buffer count in the com.rhomobile.rhodes.RhodesActivity ?

11-08 18:28:31.227: I/SFPerfTracer(238):      triggers: (rate: 0:0) (423387 sw vsyncs) (0 skipped) (0:361861 vsyncs) (2:863582)
11-08 18:28:31.328: W/Adreno-EGLSUB(4749): <DequeueBuffer:593>: dequeue native buffer fail: Unknown error 2147483646, buffer=0x61213afc, handle=0x0
11-08 18:28:31.331: W/Adreno-EGLSUB(4749): <SwapBuffers:1343>: Invalid native buffer. Failed to queueBuffer
11-08 18:28:31.331: W/Adreno-EGLSUB(4749): <updater_thread:456>: native buffer is NULL
11-08 18:28:31.346: E/BufferQueue(238): [com.myapp.myapp/com.rhomobile.rhodes.RhodesActivity] dequeueBuffer: can't dequeue multiple buffers without setting the buffer count
11-08 18:28:31.346: W/Adreno-EGLSUB(4749): <DequeueBuffer:593>: dequeue native buffer fail: Invalid argument, buffer=0x61213afc, handle=0x0
11-08 18:28:31.347: W/Adreno-ES20(4749): <gl2_surface_swap:43>: GL_OUT_OF_MEMORY
11-08 18:28:31.347: W/Adreno-EGL(4749): <qeglDrvAPI_eglSwapBuffers:3596>: EGL_BAD_SURFACE
11-08 18:28:31.347: W/HardwareRenderer(4749): EGL error: EGL_BAD_SURFACE
11-08 18:28:31.352: W/HardwareRenderer(4749): Mountain View, we've had a problem here. Switching back to software rendering.
11-08 18:28:31.478: D/qdgralloc(4749): Invalid gralloc handle (at 0x0): ver(-1/12) ints(-1/12) fds(-1/2) magic(????/gmsm)
11-08 18:28:31.478: W/GraphicBufferMapper(4749): lock(...) failed -22 (Invalid argument)
11-08 18:28:31.478: W/Surface(4749): failed locking buffer (handle = 0x0)
11-08 18:28:31.531: E/ViewRootImpl(4749): Could not lock surface
11-08 18:28:31.531: E/ViewRootImpl(4749): java.lang.IllegalArgumentException
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Surface.nativeLockCanvas(Native Method)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Surface.lockCanvas(Surface.java:243)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl.drawSoftware(ViewRootImpl.java:2466)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl.draw(ViewRootImpl.java:2440)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2284)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1914)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1024)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5796)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Choreographer.doCallbacks(Choreographer.java:574)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Choreographer.doFrame(Choreographer.java:544)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.os.Handler.handleCallback(Handler.java:733)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.os.Handler.dispatchMessage(Handler.java:95)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.os.Looper.loop(Looper.java:136)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at android.app.ActivityThread.main(ActivityThread.java:5102)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at java.lang.reflect.Method.invokeNative(Native Method)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at java.lang.reflect.Method.invoke(Method.java:515)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-08 18:28:31.531: E/ViewRootImpl(4749):      at dalvik.system.NativeStart.main(Native Method)


问:
Load Values From Closed Workbook Into Array
I have not used VBA in a while so I'm a bit rusty. Seeking help.

The task:
I need to pull all unique value from a given range in a closed workbook, into my sub's workbook.
I'm thinking of calling a function that returns an array of my unique non-blank values. because I need to know the quantity of unique values to insert the right amount of lines in the main workbook. Can't juts copy-paste the values. And also because I need to remove the duplicates.

Some relevant code bits up to know:

```<code>    Sub PullACParts()

    Dim FullFilePath As String
    Dim arrPartList() As String

FullFilePath = "C:\Users\[...]file1.xlsx"
arrPartList() = GetValues(FullFilePath)
</code>```

and that calls:

```<code>Function GetValues(path as string) as Variant
    Dim arrValues() As String
    Dim arrUnikVals As String

    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    Dim src As Workbook

    ' OPEN THE SOURCE EXCEL WORKBOOK IN "READ ONLY MODE".
    Set src = Workbooks.Open(FullFilePath, True, True)

    ' GET THE TOTAL ROWS FROM THE SOURCE WORKBOOK.
    Dim iTotalRows As Integer
    TotalRows = src.Worksheets("Sheet1").Range("D1:D" & Cells(Rows.Count, "D").End(xlUp).Row).Rows.Count

    ' COPY NON-BLANK DATA FROM SOURCE FILE COLUMN-4 TO ARRAY.
    Dim iCnt As Integer         ' COUNTER.
    Dim ArrDim As Long: ArrDim = 0

    For iCnt = 4 To TotalRows

        If src.Worksheets("Sheet1").Range("D" & iCnt).Value <> "" Then
            arrValues(ArrDim) = src.Worksheets("Sheet1").Cells(4 & iCnt).Formula 'FAILS HERE
            ArrDim = ArrDim + 1
        End If

    Next iCnt

    ' CLOSE THE SOURCE FILE.
    src.Close False             ' FALSE - DON'T SAVE THE SOURCE FILE.
    Set src = Nothing

    ' Remove Duplicates
    arrUnikVals = RemoveDupesColl(arrValues)
    GetValues = arrUnikVals

ErrHandler:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Function
</code>```

It fails when I try loading the array. Says "arrValues(ArrDim) =
I tried a few different things but just can't figure it out.
Thanks in advance for the help!!

答:
You don't need to loop this. First set your variable types.

```<code>Dim arrValue as Variant, lr as long
</code>```

Once this is a variant you can simply grab the array from the range in one go by transposing it:

```<code>lr = src.Worksheets("Sheet1").range("D" & rows.count).end(xlup).row
Application.transpose(src.Worksheets("Sheet1").range("D4:D" & lr))
</code>```

If you need to loop the values in the array later you simply do something like this:

```<code>Dim X as long
For X = lbound(arrValue) to ubound(arrValue)
    msgbox arrValue(X)
next
</code>```

I do however note in your question you say you want to pull data from a CLOSED workbook but your code is opening the book. There are ways to pull data direct from a closed book but it would be difficult because you don't know how many rows it will be without opening the book. If you absolutely have to leave the book closed then post back.

I also note you are using cells(4 & iCnt) to try and populate the array, you do know that is just the cell counting from left to right then row to row? in other words cells(2) is B1 and cells(16386) is B2. You should use cells(Row,Column) I think from what you have said you want to increment the row but if not then post back, we simply double transpose if it's across columns instead of rows.

Body:
I have not used VBA in a while so I'm a bit rusty. Seeking help.

The task:
I need to pull all unique value from a given range in a closed workbook, into my sub's workbook.
I'm thinking of calling a function that returns an array of my unique non-blank values. because I need to know the quantity of unique values to insert the right amount of lines in the main workbook. Can't juts copy-paste the values. And also because I need to remove the duplicates.

Some relevant code bits up to know:

    Sub PullACParts()

    Dim FullFilePath As String
    Dim arrPartList() As String

FullFilePath = "C:\Users\[...]file1.xlsx"
arrPartList() = GetValues(FullFilePath)

and that calls:

Function GetValues(path as string) as Variant
    Dim arrValues() As String
    Dim arrUnikVals As String

    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    Dim src As Workbook

    ' OPEN THE SOURCE EXCEL WORKBOOK IN "READ ONLY MODE".
    Set src = Workbooks.Open(FullFilePath, True, True)

    ' GET THE TOTAL ROWS FROM THE SOURCE WORKBOOK.
    Dim iTotalRows As Integer
    TotalRows = src.Worksheets("Sheet1").Range("D1:D" & Cells(Rows.Count, "D").End(xlUp).Row).Rows.Count

    ' COPY NON-BLANK DATA FROM SOURCE FILE COLUMN-4 TO ARRAY.
    Dim iCnt As Integer         ' COUNTER.
    Dim ArrDim As Long: ArrDim = 0

    For iCnt = 4 To TotalRows

        If src.Worksheets("Sheet1").Range("D" & iCnt).Value <> "" Then
            arrValues(ArrDim) = src.Worksheets("Sheet1").Cells(4 & iCnt).Formula 'FAILS HERE
            ArrDim = ArrDim + 1
        End If

    Next iCnt

    ' CLOSE THE SOURCE FILE.
    src.Close False             ' FALSE - DON'T SAVE THE SOURCE FILE.
    Set src = Nothing

    ' Remove Duplicates
    arrUnikVals = RemoveDupesColl(arrValues)
    GetValues = arrUnikVals

ErrHandler:
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Function

It fails when I try loading the array. Says "arrValues(ArrDim) =
I tried a few different things but just can't figure it out.
Thanks in advance for the help!!

Body:
You don't need to loop this. First set your variable types.

Dim arrValue as Variant, lr as long

Once this is a variant you can simply grab the array from the range in one go by transposing it:

lr = src.Worksheets("Sheet1").range("D" & rows.count).end(xlup).row
Application.transpose(src.Worksheets("Sheet1").range("D4:D" & lr))

If you need to loop the values in the array later you simply do something like this:

Dim X as long
For X = lbound(arrValue) to ubound(arrValue)
    msgbox arrValue(X)
next

I do however note in your question you say you want to pull data from a CLOSED workbook but your code is opening the book. There are ways to pull data direct from a closed book but it would be difficult because you don't know how many rows it will be without opening the book. If you absolutely have to leave the book closed then post back.

I also note you are using cells(4 & iCnt) to try and populate the array, you do know that is just the cell counting from left to right then row to row? in other words cells(2) is B1 and cells(16386) is B2. You should use cells(Row,Column) I think from what you have said you want to increment the row but if not then post back, we simply double transpose if it's across columns instead of rows.


问:
How to install openjdk-8-jdk on Debian 10 (Buster)?
It seems Debian does not support openjdk-8-jdk anymore due to a security issue. What is the easiest way to install openjdk-8-jdk for Debian 10 (Buster)?</p>

答:
I needed to install a 32-bit version but this wasn't available at adoptopenjdk far as I could see. I tracked down a copy of a binary at java.com i their downloads area:

```<code>jre-8u241-linux-i586.tar.gz
</code>```

All I needed was the JRE (rather than a JDK, but the process should be the same for either) and since it was also for a personal use only, the Oracle binary was OK (they have limitations in this regard).

I downloaded the binary and placed it in the home folder (~/) of the user that needed to run it and then unzipped it like so:

```<code>mkdir ~/java && cd ~/java && tar -xf jre-8u241-linux-i586.tar.gz
</code>```

Then added the location to the path of the user that would run the Java application by appending this line to ~/.profile:

```<code>export PATH=$PATH:/home/youruserid/java/jre1.8.0_241/bin
</code>```

This worked fine for my case but there are no doubt better ways to install a binary. For example so it is available for all Unix users rather than just one.

Body:
I needed to install a 32-bit version but this wasn't available at adoptopenjdk far as I could see. I tracked down a copy of a binary at java.com i their downloads area:

jre-8u241-linux-i586.tar.gz

All I needed was the JRE (rather than a JDK, but the process should be the same for either) and since it was also for a personal use only, the Oracle binary was OK (they have limitations in this regard).

I downloaded the binary and placed it in the home folder (~/) of the user that needed to run it and then unzipped it like so:

mkdir ~/java && cd ~/java && tar -xf jre-8u241-linux-i586.tar.gz

Then added the location to the path of the user that would run the Java application by appending this line to ~/.profile:

export PATH=$PATH:/home/youruserid/java/jre1.8.0_241/bin

This worked fine for my case but there are no doubt better ways to install a binary. For example so it is available for all Unix users rather than just one.


问:
How did these big companies start from these three main points?
So this is something that Iv'e been thinking about lately, and it basically is : How did big music web apps or websites like Spotify, Youtube, or Anghami(if you know that one) start? I was actually thinking about 3 things, the first : How did they get these huge music libraries? the second : Did each of those big companies need to buy a special server to hold the website data and music Library? and if yes, how much does a special server cost in this case? and the third question is : How did they solve the copyrights with all of these creators or authors or publishers or whatever they're called, the copyrights owners in this case...?</p>

答:
1. They are uploaded by the artists/creators. I'd imagine pre-release Spotify would have had a library already put together by working with the artists.

2. Yes. They cost a lot. There are hundreds of millions of users and terabytes upon terabytes of data, spread around the world. Server costs will be in the millions. Starting out the upfront cost to set up infrastructure would be very high too.

3. This is definitely not the place to ask this kind of question. I would Google information on how copyrights with artists usually work