问:
Downloading Hidden file and Viewing it in an UIWebView
I am Downloading a file from service into the iPhone of type txt and I view the file into a UIWebview that works perfectly.

But when I set the file attribute hidden on the server before I Download it, the UIWebview can't load the file, on the webview delegate webView:didFailLoadWithError: I receive the following error:

```<code> Error Domain=NSURLErrorDomain Code=-1102 "You do not have permission to access the requested resource."
</code>```

Can I change the File attribute hidden after I download the file? or there is other solution for this?

答: I don't know why you are trying to make a file hidden on your web server. If it is so that it will not show in a directory listing, then you could try and use a "." (on all variants of unix, including MacOS X, a file that begins with a period is "hidden"), instead of the hidden file attribute (which is specific to MacOS X), and then try to customize access to hidden files by customizing .htaccess, with the help of this article.

Body:
I am Downloading a file from service into the iPhone of type txt and I view the file into a UIWebview that works perfectly.

But when I set the file attribute hidden on the server before I Download it, the UIWebview can't load the file, on the webview delegate webView:didFailLoadWithError: I receive the following error:

 Error Domain=NSURLErrorDomain Code=-1102 "You do not have permission to access the requested resource."

Can I change the File attribute hidden after I download the file? or there is other solution for this?


来源: stackexchange

问:
Repeated local notifications
I am developing an application with local notifications with values coming from the database. However, it is repeating the notification with the same value countless times until changing to another.

Example:

1st - "The invoice of house #1 will expire"

2nd - "The invoice of house #1 will expire"

3rd - "The invoice of house #2 will expire"

Any idea what that might be and how to fix it?

```<code>    calculateDif(idHouse, dateBill) {
       let billDate= moment(dateBill);
       var MyDate = new Date();
       var MyDateString;
       MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
                                           + '-' + ('0' + MyDate.getDate()).slice(-2);
       let warningDate= billDate.diff(MyDateString, 'days');

       if (warningDate <= 5) {
         this.localNotifications.schedule({
           id: 1,
           text: 'The invoice of house ' idHouse + ' will expire',
           sound: null,
           data: { secret: 1 }
         });
       }
    }
</code>```

答:
I think the problem is in the function that execute calculateDif();

You can also create an array of your articles that you have already notified, for example notifiedHouses = []
and check if the id is already notified using .some

```<code>calculateDif(idHouse, dateBill) {

       let billDate= moment(dateBill);
       var MyDate = new Date();
       var MyDateString;
       MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
                                           + '-' + ('0' + MyDate.getDate()).slice(-2);
       let warningDate= billDate.diff(MyDateString, 'days');

       if (warningDate <= 5 && !this.notifiedHouses.some( item => item.idHouse === idHouse )) {
         this.localNotifications.schedule({
           id: 1,
           text: 'The invoice of house ' idHouse + ' will expire',
           sound: null,
           data: { secret: 1 }
         });
         const house = {idHouse: idHouse}
         this.notifiedHouses.push(house);
       }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Repeated local notifications

Body:
I am developing an application with local notifications with values coming from the database. However, it is repeating the notification with the same value countless times until changing to another.

Example:

1st - "The invoice of house #1 will expire"

2nd - "The invoice of house #1 will expire"

3rd - "The invoice of house #2 will expire"

Any idea what that might be and how to fix it?

    calculateDif(idHouse, dateBill) {
       let billDate= moment(dateBill);
       var MyDate = new Date();
       var MyDateString;
       MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
                                           + '-' + ('0' + MyDate.getDate()).slice(-2);
       let warningDate= billDate.diff(MyDateString, 'days');

       if (warningDate <= 5) {
         this.localNotifications.schedule({
           id: 1,
           text: 'The invoice of house ' idHouse + ' will expire',
           sound: null,
           data: { secret: 1 }
         });
       }
    }

Body:
I think the problem is in the function that execute calculateDif();

You can also create an array of your articles that you have already notified, for example notifiedHouses = []
and check if the id is already notified using .some

calculateDif(idHouse, dateBill) {

       let billDate= moment(dateBill);
       var MyDate = new Date();
       var MyDateString;
       MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
                                           + '-' + ('0' + MyDate.getDate()).slice(-2);
       let warningDate= billDate.diff(MyDateString, 'days');

       if (warningDate <= 5 && !this.notifiedHouses.some( item => item.idHouse === idHouse )) {
         this.localNotifications.schedule({
           id: 1,
           text: 'The invoice of house ' idHouse + ' will expire',
           sound: null,
           data: { secret: 1 }
         });
         const house = {idHouse: idHouse}
         this.notifiedHouses.push(house);
       }
    }


问:
Cannot get python to load json file
This is the error I keep getting

```<code>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

This is what the json data looks like:

```<code>{
    "TITLE": "Rome: The Punic Wars - The First Punic War - Extra History - #1",
    "CHANNEL_NAME": "Extra Credits",
    "NUMBER_OF_VIEWS": "3,954,083 views",
    "LIKES": "50,431",
    "DISLIKES": "887",
    "NUMBER_OF_SUBSCRIPTIONS": "2.37M",
    "HASH_TAGS": []
}
</code>```

I've tried to modify the file to point of deleting all but the curly brackets, then even them to, but the error still happens.

This is what my code looks like:

```<code>import json

with open('C:/Users/longv/Desktop/data.json') as f:
    print('hello')
    data = json.load(f)
</code>```

I also searched StackOverflow, but the discussions are so over my head I don't even understand, and it doesn't look like it'd work in my case anyway.

EDIT: This is a load of BS, because I used the online platform repl.it and this code worked fine.

答:
First, you have to put the JSON file and the python code in the same directory.
Then try to write the following:</p>

```<code>with open('yourjsonfile.json') as f:
    data = json.load(f)
# then,if you want to print out the "TITLE" in your context
print(data['TITLE'])
</code>```

Title: Cannot get python to load json file

Body:
This is the error I keep getting

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This is what the json data looks like:

{
    "TITLE": "Rome: The Punic Wars - The First Punic War - Extra History - #1",
    "CHANNEL_NAME": "Extra Credits",
    "NUMBER_OF_VIEWS": "3,954,083 views",
    "LIKES": "50,431",
    "DISLIKES": "887",
    "NUMBER_OF_SUBSCRIPTIONS": "2.37M",
    "HASH_TAGS": []
}

I've tried to modify the file to point of deleting all but the curly brackets, then even them to, but the error still happens.

This is what my code looks like:

import json

with open('C:/Users/longv/Desktop/data.json') as f:
    print('hello')
    data = json.load(f)

I also searched StackOverflow, but the discussions are so over my head I don't even understand, and it doesn't look like it'd work in my case anyway.

EDIT: This is a load of BS, because I used the online platform repl.it and this code worked fine.

Body:
First, you have to put the JSON file and the python code in the same directory.
Then try to write the following:

with open('yourjsonfile.json') as f:
    data = json.load(f)
# then,if you want to print out the "TITLE" in your context
print(data['TITLE'])


问:
Change value in for-loop whilst looping
I'm stuck on a dice exercise. For each dice that rolls 6, they need to be excluded from the count and rolled again. Problem is that I don't know how to change the value of a for range loop whilst looping through it, and I'm not sure how to attack it otherwise. Here's where I'm at:

```<code>numRolls = 10
initSum = 0

for i in range(0,numRolls):
    diceScore = random.randint(1,6)
    if(diceScore == 6):
        print("You rolled a 6! You receive two extra rolls.")
        numRolls = numRolls + 2
        # Not making its way to the top of the for-loop
    else:
        totalSum = initSum + diceScore
print("Done! You've rolled a total of ",totalSum)
totalSum = 0

</code>```

I'm guessing numRolls in the for-loop is out of scope. The alternative solutions I've come up with would mean absolutely endless amount of separate rolls. Randoming between 1 and 5 is not a viable option.. :)

Can someone point me in the right direction here?

答:
Consider this smaller example:

```<code>for i in range(0, 3):
    i = i + 1
</code>```

This is equivalent to

```<code>i = 0
i = i + 1
i = 1
i = i + 1
i = 2
i = i + 1
</code>```

I'm sure you see why your idea doesn't work.

Use while instead of for.

If you count down instead of up, you don't need any more variables.

```<code>while numRolls > 0:
    numRolls = numRolls - 1
    diceScore = random.randint(1,6)
    if(diceScore == 6):
        print("You rolled a 6! You receive two extra rolls.")
        numRolls = numRolls + 2
    else:
        totalSum = initSum + diceScore
print("Done! You've rolled a total of ",totalSum)
totalSum = 0
</code>```

Title: Change value in for-loop whilst looping

Body:
I'm stuck on a dice exercise. For each dice that rolls 6, they need to be excluded from the count and rolled again. Problem is that I don't know how to change the value of a for range loop whilst looping through it, and I'm not sure how to attack it otherwise. Here's where I'm at:

numRolls = 10
initSum = 0

for i in range(0,numRolls):
    diceScore = random.randint(1,6)
    if(diceScore == 6):
        print("You rolled a 6! You receive two extra rolls.")
        numRolls = numRolls + 2
        # Not making its way to the top of the for-loop
    else:
        totalSum = initSum + diceScore
print("Done! You've rolled a total of ",totalSum)
totalSum = 0

I'm guessing numRolls in the for-loop is out of scope. The alternative solutions I've come up with would mean absolutely endless amount of separate rolls. Randoming between 1 and 5 is not a viable option.. :)

Can someone point me in the right direction here?

Body:
Consider this smaller example:

for i in range(0, 3):
    i = i + 1

This is equivalent to

i = 0
i = i + 1
i = 1
i = i + 1
i = 2
i = i + 1

I'm sure you see why your idea doesn't work.

Use while instead of for.

If you count down instead of up, you don't need any more variables.

while numRolls > 0:
    numRolls = numRolls - 1
    diceScore = random.randint(1,6)
    if(diceScore == 6):
        print("You rolled a 6! You receive two extra rolls.")
        numRolls = numRolls + 2
    else:
        totalSum = initSum + diceScore
print("Done! You've rolled a total of ",totalSum)
totalSum = 0


问:
How to select and get two input value?
I have an issue when I select an option it will get the input value perfectly but I want to add one more input value which is email so for example,
when I select (Elvis) option & get two value phone and email in different input field. </p>

```<code><select class="name" name="name[]">
<option value="" selected="selected">Please select...</option>
<option value="Elvis" data-phonenumber="11111" data-email="abc@gmail.com">Elvis</option>
<option value="Frank" data-phonenumber="22222" data-email="123@gmail.com">Frank</option>
<option value="Jim" data-phonenumber="33333" data-email="123@gmail.com">Jim</option>
</select>

<input type="text" class="phonenumber" name="phonenumber[]" value="" >
<input type="text" class="email" name="email[]" value="" >

<br />
<select class="name" name="name[]">
<option value="" selected="selected">Please select...</option>
<option value="Elvis" data-phonenumber="11111" data-email="abc@gmail.com">Elvis</option>
<option value="Frank" data-phonenumber="22222" data-email="123@gmail.com">Frank</option>
<option value="Jim" data-phonenumber="33333" data-email="123@gmail.com">Jim</option>
</select>

<input type="text" class="phonenumber" name="phonenumber[]" value="" >
<input type="text" class="email" name="email[]" value="" >
<br />

here is script

<script>
$(document).ready(function() {
    $('.name').live('change', function() {
$(this).next($('.phonenumber')).val($(this).find('option:selected').attr('data-phonenumber'));

    })
 });
</script>
</code>```

答:
Hope it helps. I've used jquery

-edit----

code indent and added comments

//body render wait
$(document).ready(function (){

    //loop selects with "name" class a attach change callback on each
  $('.name').each(function(idx, elem){

    $(elem).change(function(){
      //get selected option element
      var option = $(this).find(':selected');
      //get phone number data
      var p = $(option).data('phonenumber');
      //get email data
      var e = $(option).data('email');
      //find next phonenumber input and set value
      $(elem).parent().find('.phonenumber').val(p);
      //find next email input and set value
      $(elem).parent().find('.email').val(e);
    });

  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tamplate">
  <select class="name">
    <option value="">Please select...</option>
    <option value="Elvis" data-phonenumber="11111" data-email="abc@gmail.com">Elvis</option>
    <option value="Frank" data-phonenumber="22222" data-email="123@gmail.com">Frank</option>
    <option value="Jim" data-phonenumber="33333" data-email="123@gmail.com">Jim</option>
  </select>

  <input type="text" class="phonenumber" name="phonenumber" value="" >
  <input type="text" class="email" name="email" value="" >
</div>

<div class="tamplate">
  <select class="name">
    <option value="">Please select...</option>
    <option value="Elvis" data-phonenumber="11111" data-email="abc@gmail.com">Elvis</option>
    <option value="Frank" data-phonenumber="22222" data-email="123@gmail.com">Frank</option>
    <option value="Jim" data-phonenumber="33333" data-email="123@gmail.com">Jim</option>
  </select>

  <input type="text" class="phonenumber" name="phonenumber" value="" >
  <input type="text" class="email" name="email" value="" >
</div></code>```

Title: How to select and get two input value?

Body:
I have an issue when I select an option it will get the input value perfectly but I want to add one more input value which is email so for example,
when I select (Elvis) option & get two value phone and email in different input field.

<select class="name" name="name[]">
<option value="" selected="selected">Please select...</option>
<option value="Elvis" data-phonenumber="11111" data-email="abc@gmail.com">Elvis</option>
<option value="Frank" data-phonenumber="22222" data-email="123@gmail.com">Frank</option>
<option value="Jim" data-phonenumber="33333" data-email="123@gmail.com">Jim</option>
</select>

<input type="text" class="phonenumber" name="phonenumber[]" value="" >
<input type="text" class="email" name="email[]" value="" >

<select class="name" name="name[]">
<option value="" selected="selected">Please select...</option>
<option value="Elvis" data-phonenumber="11111" data-email="abc@gmail.com">Elvis</option>
<option value="Frank" data-phonenumber="22222" data-email="123@gmail.com">Frank</option>
<option value="Jim" data-phonenumber="33333" data-email="123@gmail.com">Jim</option>
</select>

<input type="text" class="phonenumber" name="phonenumber[]" value="" >
<input type="text" class="email" name="email[]" value="" >

here is script

Body:
Hope it helps. I've used jquery

-edit----

code indent and added comments

//body render wait
$(document).ready(function (){

    //loop selects with "name" class a attach change callback on each
  $('.name').each(function(idx, elem){

    $(elem).change(function(){
      //get selected option element
      var option = $(this).find(':selected');
      //get phone number data
      var p = $(option).data('phonenumber');
      //get email data
      var e = $(option).data('email');
      //find next phonenumber input and set value
      $(elem).parent().find('.phonenumber').val(p);
      //find next email input and set value
      $(elem).parent().find('.email').val(e);
    });

  });

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tamplate">
  <select class="name">
    <option value="">Please select...</option>
    <option value="Elvis" data-phonenumber="11111" data-email="abc@gmail.com">Elvis</option>
    <option value="Frank" data-phonenumber="22222" data-email="123@gmail.com">Frank</option>
    <option value="Jim" data-phonenumber="33333" data-email="123@gmail.com">Jim</option>
  </select>

  <input type="text" class="phonenumber" name="phonenumber" value="" >
  <input type="text" class="email" name="email" value="" >
</div>

<div class="tamplate">
  <select class="name">
    <option value="">Please select...</option>
    <option value="Elvis" data-phonenumber="11111" data-email="abc@gmail.com">Elvis</option>
    <option value="Frank" data-phonenumber="22222" data-email="123@gmail.com">Frank</option>
    <option value="Jim" data-phonenumber="33333" data-email="123@gmail.com">Jim</option>
  </select>

  <input type="text" class="phonenumber" name="phonenumber" value="" >
  <input type="text" class="email" name="email" value="" >
</div>


问:
How to programmatically test if assertions are enabled?
One of the correct answers from OCP Java SE 6 Programmer Practice Exams is:

You can programmatically test wheather assertions have been enabled
  without throwing an AssertionError.

How can I do that?

答:
I'm using AssertsEnabled from jdk.nashorn.internal.

```<code>System.out.println(AssertsEnabled.assertsEnabled());
// "assertsEnabled()" returns boolean value
</code>```

Maybe it helps someone.

ContentLicense: CC BY-SA 3.0

Body:
I'm using AssertsEnabled from jdk.nashorn.internal.

System.out.println(AssertsEnabled.assertsEnabled());
// "assertsEnabled()" returns boolean value

Maybe it helps someone.


问:
Send JSON POST request with PHP
I have this JSON data:

```<code>{
    userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
    itemKind: 0,
    value: 1,
    description: 'Saude',
    itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
</code>```

and I need to post to JSON URL:
http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount

How can I send this POST request using PHP?

答:
You can use CURL for this purpose see the example code:</p>

```<code>$url = "your url";
$content = json_encode("your data to be sent");

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}

curl_close($curl);

$response = json_decode($json_response, true);
</code>```

Title: Send JSON POST request with PHP

Body:
I have this JSON data:

{
    userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
    itemKind: 0,
    value: 1,
    description: 'Saude',
    itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}

and I need to post to JSON URL:
http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount

How can I send this POST request using PHP?

Body:
You can use CURL for this purpose see the example code:

$url = "your url";
$content = json_encode("your data to be sent");

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}

curl_close($curl);

$response = json_decode($json_response, true);


问:
Error "LoadLibrary failed with error 126: The module could not be found" when launching Spyder IDE through VPN
Here's what happens:

Using a Macbook Pro, I use the Microsoft Remote Desktop Connection application to connect to my work computer, which is a Windows 10 machine

If I try to launch Spyder on my work computer, I get this error:
Load Library Error

However:

If I am at my work computer (i.e. physically at work instead of logging in remotely), I can launch Spyder successfully

If I leave Spyder open on my work computer, then go home and do a remote log-in to my work computer, I can use Spyder without issue. The problem/error described above arises only if I try to open Spyder through the remote connection.

This error only seems to affect Spyder and I can use all other programs without issue through a remote connection. As a workaround I've been using other IDEs and successfully running scripts, but I strongly prefer Spyder.

What I have tried so far (without success):

The 4 troubleshooting steps posted by Fazil M. to this Microsoft thread

Uninstalling/reinstalling Spyder using Conda

Restarting my work computer

System Information:

Work Computer OS: Windows 10, 64-bit

OS of computer through which I'm logging in to work computer: Mac OS X El Capitan 10.11.6

Spyder version: 4.1.1

Any thoughts as to what could be going on?

Update--More information and trials:

I checked out Issue #3736 on Spyder's GitHub. It says to download and add a file called opengl32sw.dll to the folder ~\Lib\site-packages\PyQt5\Qt\bin. But when I go to the PyQt5 folder, I do not see a subfolder for Qt. I tried placing it into the PyQt5 main folder, but that did not fix the problem.

I've heard this can be a graphics card issue too. On my machine I have two graphics cards: AMD RadeonT R5 430 and Intel(R) HD Graphics 630.

答:
Darren's answer did not work for me. What did work was to:

First option: go into the device manager and disable the Intel HD Graphics card under "display adapters."

Second option:

run "Gpedit.msc"

navigate to Computer Configuration->Administrative
Templates->Windows Components->Remote Desktop Services->Remote
Desktop Session Host->Remote Session Environment

Disable "use WDDM graphics display driver for remote desktop
connections"

Restart the computer

See https://answers.microsoft.com/en-us/windows/forum/all/windows-10-1903-may-update-black-screen-with/23c8a740-0c79-4042-851e-9d98d0efb539


问:
How to downscale an image without losing discrete values?
I have an image of a city with discrete colors (Green=meadow, black=buildings, white/yellow=roads). Using Pillow, I import the picture in my (Python) program and convert it to a Numpy array with discrete values for the colors (i.e. green pixels become 1's, black pixels become 2's, etc).

I want to downscale the resolution of the image (for computational purposes) while retaining as much information as possible. However, using Pillow's resize() method, colors deviate from these discrete values. How can I downscale this image while (most importantly) retaining the discrete colors and (also important) with losing as little information as possible?

Here an example of the image: https://i.imgur.com/6Tef55H.png

EDIT: per request, some code:

```<code>from PIL import Image
import Numpy as np

picture = Image.open(some_image.png)

width, height = picture.size

pic_array = np.zeros(width,height)

# Turn the image into discrete values
for i in range(0,width):
    for j in range(0,height):
        red, green, blue = picture.getpixel((i,j))
        if red == a and green == b and blue == c:
            #An example of how discrete colors are converted to values
            pic_array[i][j] = 1

</code>```

Scaling can be done in two ways:

1) Scaling the original image using Pillow's resize library or
2) rescaling the final array using something like:

```<code>scaled_array = pic_array[0:width:5, 0:height,5]
</code>```

Option 1 is "well" in terms of retaining information but loses discrete values, while option 2 does it the other way around.

答:
I was interested in this question and wrote some code to try out some ideas - specifically the "mode" filter suggested by @jasonharper in the comments. So, I programmed it up.

First of all the input image is not 4 nicely defined classes, but actually has 6,504 different colours, so I made a palette of 4 colours using ImageMagick like this:

```<code>magick xc:black xc:white xc:yellow xc:green +append palette.png
</code>```

Here it is enlarged - in reality is 4x1 pixels:

Then I mapped the colours in the image to the palette of 4 discrete colours:

```<code>magick map.png +dither -remap palette.png start.png
</code>```

Then I tried this code to calculate the median and the mode of each 3x3 window:

```<code>#!/usr/bin/env python3

from PIL import Image
import numpy as np
from scipy import stats
from skimage.util import view_as_blocks

# Open image and make into Numpy array
im = Image.open('start.png')
na = np.array(im)

# Make a view as 3x3 blocks - crop anything not a multiple of 3
block_shape=(3,3)
view = view_as_blocks(na[:747,:], block_shape)
flatView = view.reshape(view.shape[0], view.shape[1], -1)   # now (249,303,9)

# Get median of each 3x3 block
resMedian = np.median(flatView, axis=2).astype(np.uint8)
Image.fromarray(resMedian*60).save('resMedian.png')        # arbitrary scaling by 60 for contrast

# Get mode of each 3x3 block
resMode   = stats.mode(flatView, axis=2)[0].reshape((249,303)).astype(np.uint8)
Image.fromarray(resMode*60).save('resMode.png')            # arbitrary scaling by 60 for contrast
</code>```

Here is the result of the median filter:

And here is the result of the "mode" filter which is indeed better IMHO:

Here is animated comparison:

If anyone wants to take the code and adapt it to try new ideas, please feel free!

Body:
I have an image of a city with discrete colors (Green=meadow, black=buildings, white/yellow=roads). Using Pillow, I import the picture in my (Python) program and convert it to a Numpy array with discrete values for the colors (i.e. green pixels become 1's, black pixels become 2's, etc).

I want to downscale the resolution of the image (for computational purposes) while retaining as much information as possible. However, using Pillow's resize() method, colors deviate from these discrete values. How can I downscale this image while (most importantly) retaining the discrete colors and (also important) with losing as little information as possible?

Here an example of the image: https://i.imgur.com/6Tef55H.png

EDIT: per request, some code:

from PIL import Image
import Numpy as np

picture = Image.open(some_image.png)

width, height = picture.size

pic_array = np.zeros(width,height)

# Turn the image into discrete values
for i in range(0,width):
    for j in range(0,height):
        red, green, blue = picture.getpixel((i,j))
        if red == a and green == b and blue == c:
            #An example of how discrete colors are converted to values
            pic_array[i][j] = 1

Scaling can be done in two ways:

1) Scaling the original image using Pillow's resize library or
2) rescaling the final array using something like:

scaled_array = pic_array[0:width:5, 0:height,5]

Option 1 is "well" in terms of retaining information but loses discrete values, while option 2 does it the other way around.

Body:
I was interested in this question and wrote some code to try out some ideas - specifically the "mode" filter suggested by @jasonharper in the comments. So, I programmed it up.

First of all the input image is not 4 nicely defined classes, but actually has 6,504 different colours, so I made a palette of 4 colours using ImageMagick like this:

magick xc:black xc:white xc:yellow xc:green +append palette.png

Here it is enlarged - in reality is 4x1 pixels:

Then I mapped the colours in the image to the palette of 4 discrete colours:

magick map.png +dither -remap palette.png start.png

Then I tried this code to calculate the median and the mode of each 3x3 window:

#!/usr/bin/env python3

from PIL import Image
import numpy as np
from scipy import stats
from skimage.util import view_as_blocks

# Open image and make into Numpy array
im = Image.open('start.png')
na = np.array(im)

# Make a view as 3x3 blocks - crop anything not a multiple of 3
block_shape=(3,3)
view = view_as_blocks(na[:747,:], block_shape)
flatView = view.reshape(view.shape[0], view.shape[1], -1)   # now (249,303,9)

# Get median of each 3x3 block
resMedian = np.median(flatView, axis=2).astype(np.uint8)
Image.fromarray(resMedian*60).save('resMedian.png')        # arbitrary scaling by 60 for contrast

# Get mode of each 3x3 block
resMode   = stats.mode(flatView, axis=2)[0].reshape((249,303)).astype(np.uint8)
Image.fromarray(resMode*60).save('resMode.png')            # arbitrary scaling by 60 for contrast

Here is the result of the median filter:

And here is the result of the "mode" filter which is indeed better IMHO:

Here is animated comparison:

If anyone wants to take the code and adapt it to try new ideas, please feel free!


问:
Detect faces without eyebrows and jaw using opencv
I am trying to detect faces (specifically, faces with opened eyes) using OpenCV haar cascade classifier. However, I had a problem detecting the faces that do not have eyebrows and/or jaw, as shown in the following image. I had tried many haar cascade for face detection such as haarcascade_frontalface_default.xml, haarcascade_frontalface_alt_tree.xml, etc. But all of these did not work.

Here is my code:

```<code>import cv2
import os
import glob

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye_tree_eyeglasses.xml')

count = 0
path = "./test/*.png"
for index, filename in enumerate(glob.glob(path)):
    img = cv2.imread(filename)
    basename = os.path.splitext(os.path.basename(filename))[0]

    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in faces:
        # cv2.rectangle(img,(x,y),(x+w, y+h),(255,0,0), 2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        eyes = eye_cascade.detectMultiScale(roi_gray)

        if len(eyes) >= 2:
            count = count + 1
            output_dir = './test/output'
            cv2.imwrite(f'{output_dir}/{basename}.png', img)

cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Thank you in advance!

答:
If you have tensorflow installed you can use a neural net to detect faces which give much better accuracy than the simple haar classifier.

Here's an example using the MTCNN detector which uses tensorflow as the backend.

```<code>from mtcnn.mtcnn import MTCNN
from PIL import Image
import numpy as np

img = Image.open('6qNFu.png') # load the image
img = np.asarray(img, dtype='uint8') # convert to numpy array
img = img[:,:,0:3] # drop the alpha channel

detector = MTCNN() # initialize MTCNN detector
print(detector.detect_faces(img)) # use MTCNN detector to return bounding box and face metrics
</code>```

Using the bounding box you can extract the face from the image. Note: if the face is truncated like in the instances above, it might return a negative coordinate which is an extrapolation of where it thinks the face might be.

Here is a the documentation on MTCNN library: https://pypi.org/project/mtcnn/
It also tells you how to install it.

Body:
I am trying to detect faces (specifically, faces with opened eyes) using OpenCV haar cascade classifier. However, I had a problem detecting the faces that do not have eyebrows and/or jaw, as shown in the following image. I had tried many haar cascade for face detection such as haarcascade_frontalface_default.xml, haarcascade_frontalface_alt_tree.xml, etc. But all of these did not work.

Here is my code:

import cv2
import os
import glob

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye_tree_eyeglasses.xml')

count = 0
path = "./test/*.png"
for index, filename in enumerate(glob.glob(path)):
    img = cv2.imread(filename)
    basename = os.path.splitext(os.path.basename(filename))[0]

    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in faces:
        # cv2.rectangle(img,(x,y),(x+w, y+h),(255,0,0), 2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        eyes = eye_cascade.detectMultiScale(roi_gray)

        if len(eyes) >= 2:
            count = count + 1
            output_dir = './test/output'
            cv2.imwrite(f'{output_dir}/{basename}.png', img)

cv2.waitKey(0)
cv2.destroyAllWindows()

Thank you in advance!

Body:
If you have tensorflow installed you can use a neural net to detect faces which give much better accuracy than the simple haar classifier.

Here's an example using the MTCNN detector which uses tensorflow as the backend.

from mtcnn.mtcnn import MTCNN
from PIL import Image
import numpy as np

img = Image.open('6qNFu.png') # load the image
img = np.asarray(img, dtype='uint8') # convert to numpy array
img = img[:,:,0:3] # drop the alpha channel

detector = MTCNN() # initialize MTCNN detector
print(detector.detect_faces(img)) # use MTCNN detector to return bounding box and face metrics

Using the bounding box you can extract the face from the image. Note: if the face is truncated like in the instances above, it might return a negative coordinate which is an extrapolation of where it thinks the face might be.

Here is a the documentation on MTCNN library: https://pypi.org/project/mtcnn/
It also tells you how to install it.


问:
Why does my Linkedin share button not work?
I want to create a share button for Linkedin, the GUI button is all set up, but it doesn't work when clicking it. I researched a bit and came to the conclusion that using the same sharing mechanism, other sites work but mine doesn't.

I narrowed the problem down and now I'm trying to figure out why google.com works but my site doesn't. I don't use my real company website because it's personal information, but it's a website that has been on the internet for more than 10 years (in case this information is useful). When I go to the links, my website throws an error, but Google works fine.

Ⓧ　https://www.linkedin.com/cws/share/?url=https://www.my-company-website.com

〇　https://www.linkedin.com/cws/share/?url=https://www.google.com

Is there any pre-requisite I'm missing, which makes my site not work?

答:
If you ever get stuck on trying to figure out why your page simply doesn't populate nice preview data on your LinkedIn share page, then check out the LinkedIn Post Inspector.

Insert the URL of your page (i.e., example.com), not the URL you are using to share (i.e., linkedin.com/share?url=example.com).  You'll get detailed information on how your site will appear and why, like, for instance, sharing wikipedia.org...

Hope this helps someone else with a LinkedIn share issue!


问:
Safari on macOS is not showing my images but chrome and safari mobile does
In my Vuejs (2.6.11) App, I am displaying images from Google Cloud Storage this way (result of v-for):

```<code><img slot="image" class="card-img-top" :src="img_basepath + result.header_img" alt="Card image cap" >
</code>```

While everything works fine in Chrome and Safari on iOS, the images are broken on Safari 13.1 and show blue squares with question mark:

If I check the HTML using Safari's inspect tool it shows the following:

```<code><div class="card-image">
<img src="https://storage.cloud.google.com/heavnt-test/artistes/May2020/xoGD1P848Id9dmSrLJWX.png" alt="Card image cap" class="card-img-top">
</div>
</code>```

And if check the resources loaded, I got this:

Of course, the link is working (check it here) and, by itself, load fine in Safari.

As it's the only browser where it is not working, I have no idea where to look to fix this issue.

EDIT 24/05/20 @ 14:14

If I login in my App using firebase Auth, then the images loads .. Do not help me to know what's wrong but if it can help any one to tell me ...

答:
Find out it was because I used a bucket like in the form of:

https://storage.cloud.google.com/<bucket name>/<file name>

which require to be logged with a google account, so it was working on chrome because I was logged while not on Safari.

To properly access my Cloud Storage public files I needed to use:

https://storage.googleapis.com/<bucket name>/<file name>

Body:
In my Vuejs (2.6.11) App, I am displaying images from Google Cloud Storage this way (result of v-for):

While everything works fine in Chrome and Safari on iOS, the images are broken on Safari 13.1 and show blue squares with question mark:

If I check the HTML using Safari's inspect tool it shows the following:

And if check the resources loaded, I got this:

Of course, the link is working (<a href="https://00e9e64baca5a875668a1a87c563d9d1a8f18ea8511edb8c61-apidata.googleusercontent.com/download/storage/v1/b/heavnt-test/o/artistes%2FMay2020%2FxoGD1P848Id9dmSrLJWX.png?qk=AD5uMEtu6IDmnHE-DUQ0aVNgmQR87YfZVoYVbCvkKFaaGeAWfLdJQ7sjWjCjIB8WN6yR3JvPD4hnqt8xJq1DjUDp7fmB2L6AcAqtHeiPShadk7d3me4BhNIw4VfBwX_QRpyyq0GfM4oqtzXMchafZFopbNRClPKI-6YZWKExyLTBiYOpZOEU8cp4EIpVlNDnG9uunLf0rLoGJhJUoWUkVZx7r6BLlu5rHua4B1LZayTC2dG5EDdDCT9ozVfZvdjQb7M3lns_dLVFH1MnPBykvHYU9wVAue07tLym3EmpddetRPwG5ExEkUvxa8t_Mjy-Vuz3LhGtwFm-0iNoUvyQXFdFKD1XTAEDC1Bz6U_LXby8qlU3m05WRmdaQYT3kZ2nVdcGA0IMnPZnRppa8H1kqfBxcknaWlDCpsNETqbf9XEaT2LdeyokS-2Qcq-UH89Y7yPtEp6i7AJRDWdr85qU694NqI1W1JyPBFdwg3fZtAvdKOeS5qPZQYz7mUR3k1migNK4ZjScEcAwcn_pni6PzNoXytYkFQqidyZavFbLCpryk-TWSd3N2RPRRx6XLP6_DH1liDR4oF2wkx_lhQVGRGrFo_r18D2VJwJd3cSlou0Gp-BQrM_N66Au8YDitLmK8zdYgXkJX8kExYhgk56gdzvqpCM7_iynR5fP3Bkoy2VHcnumu1Zj7O-MOygvCOSDnV5g4m0OlQD4Fo7Mk0tteaSZjtgRS4dfYiiN6kewa-ycivAeXtTTS4ygH5z2vUR1XrMrtz84ElgMwdBpfpAe6Wxq9ITFaZPlJ03AcaR3bzG2J8neg0D5cKruKfbxDmK_G3gENx4deK29eIVT5ugPv6QyEOjwuHtLNA&isca=1" rel="nofollow noreferrer">check it here) and, by itself, load fine in Safari.

As it's the only browser where it is not working, I have no idea where to look to fix this issue.

EDIT 24/05/20 @ 14:14

If I login in my App using firebase Auth, then the images loads .. Do not help me to know what's wrong but if it can help any one to tell me ...


问:
How to scan or decode QRCode and EAN_13 barcode using blackberry API 6?
How to scan or decode QRCode and EAN_13 barcode using blackberry API 6? Any help is appreciated. I have searched lot on google but haven't find any proper solution.

My Code is.....

```<code>formats.addElement(BarcodeFormat.QR_CODE);
formats.addElement(BarcodeFormat.EAN_13);
</code>```

But i can't decode EAN_13 barcode but only QRCode.

Thanks in advance.

答: if you want to decode EAN_13 barcode then you have to rotate scanded image in CW or give the image which is already rotated.</p>

Body:
How to scan or decode QRCode and EAN_13 barcode using blackberry API 6? Any help is appreciated. I have searched lot on google but haven't find any proper solution.

My Code is.....

formats.addElement(BarcodeFormat.QR_CODE);
formats.addElement(BarcodeFormat.EAN_13);

But i can't decode EAN_13 barcode but only QRCode.

Thanks in advance.


问:
Styling buttons generated by JavaScript
I have generated some buttons using javascript to use in html and css: The code is as follows:

for(letter in currentQuestion.answers){

          // ...add an HTML button
          answers.push(
            `
              <input class="press" type="button" value="${letter}" >
            `
          );
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

I am trying to style this code so that 2 buttons come on each row, however, my code causes the buttons to stack on top of each other. My code is more or less generating buttons from scratch in javascript, query. I have tried using display: inline-block; e.t.c and read up on using grids. Could anyone help me find a solution to my problem? Here is what I would like it to look like:
Question:
Button1 Button2
Button3
What styling should I use please?

答:
```<code>    let answers = []
    let rest = [1,2,3,4,5,6,7,8]
    for(letter in rest){
          // ...add an HTML button
          answers.push(
            `<div class="inner">
                <label>
                  <input class="press" type="button" value="${letter}" >
                </label>
            <div>`
          );
        }
        console.log(answers)
        $('.appendHere').append(answers)
</code>```

HTML

```<code><div class="appendHere"></div>
</code>```

CSS

```<code>.appendHere .inner{
  float: left;
}
.appendHere .inner:nth-child(2n + 1){
  clear: left;
}

</code>```

Title: Styling buttons generated by JavaScript

Body:
I have generated some buttons using javascript to use in html and css: The code is as follows:

for(letter in currentQuestion.answers){

          // ...add an HTML button
          answers.push(
            `
              <input class="press" type="button" value="${letter}" >
            `
          );
        }

I am trying to style this code so that 2 buttons come on each row, however, my code causes the buttons to stack on top of each other. My code is more or less generating buttons from scratch in javascript, query. I have tried using display: inline-block; e.t.c and read up on using grids. Could anyone help me find a solution to my problem? Here is what I would like it to look like:
Question:
Button1 Button2
Button3
What styling should I use please?

Body:
    let answers = []
    let rest = [1,2,3,4,5,6,7,8]
    for(letter in rest){
          // ...add an HTML button
          answers.push(
            `<div class="inner">
                <label>
                  <input class="press" type="button" value="${letter}" >
                </label>
            <div>`
          );
        }
        console.log(answers)
        $('.appendHere').append(answers)

HTML

<div class="appendHere"></div>

CSS

.appendHere .inner{
  float: left;
}
.appendHere .inner:nth-child(2n + 1){
  clear: left;
}


问:
How do I set up Babel, then hit "npm run dev" in the command prompt without getting the "ERROR in ./src/js/index.js"?
What I want to do is bundle the babel/polyfill with the index.js files (using webpack). After ma set up, I ran "npm run dev" in the command prompt but it didn't work. The first line of error displayed is "ERROR in ./src/js/index.js". Am working on javascript (ES6).

This is ma webpack.config.js file.

```<code>const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: ["@babel/polyfill", "./src/js/index.js"],
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "js/bundle.js",
    },
    devServer: {
        contentBase: "./dist"
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: "index.html",
            template: "./src/index.html"
        })
    ],
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    }
};
</code>```

This is ma .babelrc file.

```<code>{
    "presets": [
        ["@babel/env", {
            "targets": {
                "browsers": [
                    "last 5 versions",
                    "ie >= 8"
                ]
            }
        }]
    ]
}
</code>```

This is ma package.json file.

```<code>{
  "name": "forkify",
  "version": "1.0.0",
  "description": "forkify project",
  "main": "index.js",
  "scripts": {
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "start": "webpack-dev-server --mode development --open"
  },
  "author": "AGO McAGO",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.10.1",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.1.0",
    "babel-preset-env": "^1.7.0",
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.11.0"
  },
  "dependencies": {
    "babel-polyfill": "^6.26.0"
  }
}
</code>```

This is the entire error (in the command prompt, windows10).

```<code>> webpack --mode development

Hash: 54008735e66cf4b55f83
Version: webpack 4.43.0
Time: 20104ms
Built at: 05/31/2020 18:20:37
       Asset      Size  Chunks             Chunk Names
  index.html  17.6 KiB          [emitted]
js/bundle.js  9.49 KiB    main  [emitted]  main
Entrypoint main = js/bundle.js
[0] multi ./src/js/index.js 28 bytes {main} [built]
[./src/js/index.js] 4.7 KiB {main} [built] [failed] [1 error]

ERROR in ./src/js/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
TypeError: C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\src\js\index.js: Cannot read property 'bindings' of null
    at Scope.moveBindingTo (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\scope\index.js:933:13)
    at BlockScoping.updateScopeInfo (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\babel-plugin-transform-es2015-block-scoping\lib\index.js:364:17)
    at BlockScoping.run (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\babel-plugin-transform-es2015-block-scoping\lib\index.js:330:12)
    at PluginPass.BlockStatementSwitchStatementProgram (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\babel-plugin-transform-es2015-block-scoping\lib\index.js:70:24)
    at newFn (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\visitors.js:179:21)
    at NodePath._call (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\path\context.js:55:20)
    at NodePath.call (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\path\context.js:42:17)
    at NodePath.visit (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\path\context.js:90:31)
    at TraversalContext.visitQueue (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\context.js:112:16)
    at TraversalContext.visitSingle (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\context.js:84:19)
    at TraversalContext.visit (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\context.js:140:19)
    at Function.traverse.node (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\index.js:84:17)
    at traverse (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\index.js:66:12)
    at transformFile (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\core\lib\transformation\index.js:107:29)
    at transformFile.next (<anonymous>)
    at run (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\core\lib\transformation\index.js:35:12)
    at run.next (<anonymous>)
    at Function.transform (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\core\lib\transform.js:27:41)
    at transform.next (<anonymous>)
    at step (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:254:32)
    at C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:266:13
    at async.call.result.err.err (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:216:11)
    at C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:184:28
    at C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\core\lib\gensync-utils\async.js:72:7
    at C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:108:33
    at step (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:280:14)
    at C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:266:13
    at async.call.result.err.err (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:216:11)
 @ multi ./src/js/index.js main[0]
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 18.3 KiB {HtmlWebpackPlugin_0} [built]
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! forkify@1.0.0 dev: `webpack --mode development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the forkify@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\asus1\AppData\Roaming\npm-cache\_logs\2020-05-31T17_20_37_349Z-debug.log
</code>```

答:
It seems like you want to use babel 7, which start to have a prefix @babel/ namespace on the package name, but your babel-preset-env (in babel 7 context, it is @babel/preset-env) is capable with babel 6 so you will always meet strange mistake.

And you have two babel-core:

@babel/core, which is babel 7

babel-core,   which is babel 6

babel has lot plugin, preset..... which has lots of concept, need good foundation knowledge to set it right, I will suggest javascript new comer use template like Create-react-app (you should could use it to help you make the code bundle, use modern syntax...even if you don't use react) to not to get involve into the babel-madness...

more reference: similar mistake that other people ask on the Github

Body:
What I want to do is bundle the babel/polyfill with the index.js files (using webpack). After ma set up, I ran "npm run dev" in the command prompt but it didn't work. The first line of error displayed is "ERROR in ./src/js/index.js". Am working on javascript (ES6).

This is ma webpack.config.js file.

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: ["@babel/polyfill", "./src/js/index.js"],
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "js/bundle.js",
    },
    devServer: {
        contentBase: "./dist"
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: "index.html",
            template: "./src/index.html"
        })
    ],
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    }
};

This is ma .babelrc file.

{
    "presets": [
        ["@babel/env", {
            "targets": {
                "browsers": [
                    "last 5 versions",
                    "ie >= 8"
                ]
            }
        }]
    ]
}

This is ma package.json file.

{
  "name": "forkify",
  "version": "1.0.0",
  "description": "forkify project",
  "main": "index.js",
  "scripts": {
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "start": "webpack-dev-server --mode development --open"
  },
  "author": "AGO McAGO",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.10.1",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.1.0",
    "babel-preset-env": "^1.7.0",
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.11.0"
  },
  "dependencies": {
    "babel-polyfill": "^6.26.0"
  }
}

This is the entire error (in the command prompt, windows10).

> webpack --mode development

Hash: 54008735e66cf4b55f83
Version: webpack 4.43.0
Time: 20104ms
Built at: 05/31/2020 18:20:37
       Asset      Size  Chunks             Chunk Names
  index.html  17.6 KiB          [emitted]
js/bundle.js  9.49 KiB    main  [emitted]  main
Entrypoint main = js/bundle.js
[0] multi ./src/js/index.js 28 bytes {main} [built]
[./src/js/index.js] 4.7 KiB {main} [built] [failed] [1 error]

ERROR in ./src/js/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
TypeError: C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\src\js\index.js: Cannot read property 'bindings' of null
    at Scope.moveBindingTo (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\scope\index.js:933:13)
    at BlockScoping.updateScopeInfo (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\babel-plugin-transform-es2015-block-scoping\lib\index.js:364:17)
    at BlockScoping.run (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\babel-plugin-transform-es2015-block-scoping\lib\index.js:330:12)
    at PluginPass.BlockStatementSwitchStatementProgram (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\babel-plugin-transform-es2015-block-scoping\lib\index.js:70:24)
    at newFn (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\visitors.js:179:21)
    at NodePath._call (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\path\context.js:55:20)
    at NodePath.call (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\path\context.js:42:17)
    at NodePath.visit (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\path\context.js:90:31)
    at TraversalContext.visitQueue (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\context.js:112:16)
    at TraversalContext.visitSingle (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\context.js:84:19)
    at TraversalContext.visit (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\context.js:140:19)
    at Function.traverse.node (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\index.js:84:17)
    at traverse (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\traverse\lib\index.js:66:12)
    at transformFile (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\core\lib\transformation\index.js:107:29)
    at transformFile.next (<anonymous>)
    at run (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\core\lib\transformation\index.js:35:12)
    at run.next (<anonymous>)
    at Function.transform (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\core\lib\transform.js:27:41)
    at transform.next (<anonymous>)
    at step (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:254:32)
    at C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:266:13
    at async.call.result.err.err (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:216:11)
    at C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:184:28
    at C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\@babel\core\lib\gensync-utils\async.js:72:7
    at C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:108:33
    at step (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:280:14)
    at C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:266:13
    at async.call.result.err.err (C:\Users\asus1\Documents\AGO McAGO\1.pracareas\7.5Javascript\Jonas Schmedtmann\46.Forkify\node_modules\gensync\index.js:216:11)
 @ multi ./src/js/index.js main[0]
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 18.3 KiB {HtmlWebpackPlugin_0} [built]
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! forkify@1.0.0 dev: `webpack --mode development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the forkify@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\asus1\AppData\Roaming\npm-cache\_logs\2020-05-31T17_20_37_349Z-debug.log


问:
In a JSON array, how to search for a certain record returned by ConvertFrom-Json?
With Powershell 6 I am able to download a file in JSON format with:

```<code>PS C:\> Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys

kty    : RSA
use    : sig
kid    : CtTuhMJmD5M7DLdzD2v2x3QKSRY
x5t    : CtTuhMJmD5M7DLdzD2v2x3QKSRY
n      : 18uZ3P3IgOySlnOsxeIN5WUKzvlm6evPDMFbmXPtTF0GMe7tD2JPfai2UGn74s7AFwqxWO5DQZRu6VfQUux8uMR4J7nxm1Kf__7pVEVJJyDuL5a8PARRYQtH68w-0IZxcFOkgsSdhtIzPQ2jj4mmRzWXIwh8M_8pJ6qiOjvjF9bhEq0CC_f27BnljPaFn8hxY69pCoxenWWqFcsUhFZvCMthhRubAbBilDr74KaXS5xCgySBhPzwekD9_NdCUu
         Csdqavd4T-VWnbplbB8YsC-R00FptBFKuTyT9zoGZjWZilQVmj7v3k8jXqYB2nWKgTAfwjmiyKz78FHkaE-nCIDw
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQXVogj9BAf49IpuOSIvztNDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDMxNzAwMDAwMFoXDTI1MDMxNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBANfLmdz9yIDskpZzrMXiDeVlCs75ZunrzwzBW5lz7UxdBjHu7Q9iT32otlBp++LOwBcKsVjuQ0GUbulX0FLsfLjEeCe58ZtSn//+6VRFSScg7i+WvDwEUWELR+vMPtCGcXBTpILEnYbSMz0No4+Jpkc1lyMIfDP/KSeqojo74xfW4RKtAgv39uwZ5Yz2hZ/IcWOvaQqMXp1lqhXLFIRWbwjLYYUbmwGwYpQ6++Cml0u
         cQoMkgYT88HpA/fzXQlLgrHamr3eE/lVp26ZWwfGLAvkdNBabQRSrk8k/c6BmY1mYpUFZo+795PI16mAdp1ioEwH8I5osis+/BR5GhPpwiA8CAwEAAaMhMB8wHQYDVR0OBBYEFF8MDGklOGhGNVJvsHHRCaqtzexcMA0GCSqGSIb3DQEBCwUAA4IBAQCKkegw/mdpCVl1lOpgU4G9RT+1gtcPqZK9kpimuDggSJju6KUQlOCi5/lIH5DCzpjFd
         mG17TjWVBNve5kowmrhLzovY0Ykk7+6hYTBK8dNNSmd4SK7zY++0aDIuOzHP2Cur+kgFC0gez50tPzotLDtMmp40gknXuzltwJfezNSw3gLgljDsGGcDIXK3qLSYh44qSuRGwulcN2EJUZBI9tIxoODpaWHIN8+z2uZvf8JBYFjA3+n9FRQn51X16CTcjq4QRTbNVpgVuQuyaYnEtx0ZnDvguB3RjGSPIXTRBkLl2x7e8/6uAZ6tchw8rhcOtP
         sFgJuoJokGjvcUSR/6Eqd}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0

kty    : RSA
use    : sig
kid    : SsZsBNhZcF3Q9S4trpQBTByNRRI
x5t    : SsZsBNhZcF3Q9S4trpQBTByNRRI
n      : uHPewhg4WC3eLVPkEFlj7RDtaKYWXCI5G-LPVzsMKOuIu7qQQbeytIA6P6HT9_iIRt8zNQvuw4P9vbNjgUCpI6vfZGsjk3XuCVoB_bAIhvuBcQh9ePH2yEwS5reR-NrG1PsqzobnZZuigKCoDmuOb_UDx1DiVyNCbMBlEG7UzTQwLf5NP6HaRHx027URJeZvPAWY7zjHlSOuKoS_d1yUveaBFIgZqPWLCg44ck4gvik45HsNVWT9zYfT74dvUS
         SrMSR-SHFT7Hy1XjbVXpHJHNNAXpPoGoWXTuc0BxMsB4cqjfJqoftFGOG4x32vEzakArLPxAKwGvkvu0jToAyvSQ
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQWHw7h/Ysh6hPcXpnrJ0N8DANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDQyNzAwMDAwMFoXDTI1MDQyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBALhz3sIYOFgt3i1T5BBZY+0Q7WimFlwiORviz1c7DCjriLu6kEG3srSAOj+h0/f4iEbfMzUL7sOD/b2zY4FAqSOr32RrI5N17glaAf2wCIb7gXEIfXjx9shMEua3kfjaxtT7Ks6G52WbooCgqA5rjm/1A8dQ4lcjQmzAZRBu1M00MC3+TT+h2kR8dNu1ESXmbzwFmO84x5UjriqEv3dclL3mgRSIGaj1iwoOOHJOIL4
         pOOR7DVVk/c2H0++Hb1EkqzEkfkhxU+x8tV421V6RyRzTQF6T6BqFl07nNAcTLAeHKo3yaqH7RRjhuMd9rxM2pAKyz8QCsBr5L7tI06AMr0kCAwEAAaMhMB8wHQYDVR0OBBYEFOI7M+DDFMlP7Ac3aomPnWo1QL1SMA0GCSqGSIb3DQEBCwUAA4IBAQBv+8rBiDY8sZDBoUDYwFQM74QjqCmgNQfv5B0Vjwg20HinERjQeH24uAWzyhWN9++Fm
         eY4zcRXDY5UNmB0nJz7UGlprA9s7voQ0Lkyiud0DO072RPBg38LmmrqoBsLb3MB9MZ2CGBaHftUHfpdTvrgmXSP0IJn7mCUq27g+hFk7n/MLbN1k8JswEODIgdMRvGqN+mnrPKkviWmcVAZccsWfcmS1pKwXqICTKzd6WmVdz+cL7ZSd9I2X0pY4oRwauoE2bS95vrXljCYgLArI3XB2QcnglDDBRYu3Z3aIJb26PTIyhkVKT7xaXhXl4Ogrbm
         Qon9/O61G2dzpjzzBPqNP}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0
</code>```

(and there are more records in the keys array...)

How could I please search for the record with kid = "SsZsBNhZcF3Q9S4trpQBTByNRRI" and then return its x5c property?

Is the following a good way to find the record (I am confused by -expand, does it strip the outside JSON object and return just the keys array?) and then how to access its x5c property please?

```<code>PS C:\> Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys |
>> Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI

kty    : RSA
use    : sig
kid    : SsZsBNhZcF3Q9S4trpQBTByNRRI
x5t    : SsZsBNhZcF3Q9S4trpQBTByNRRI
n      : uHPewhg4WC3eLVPkEFlj7RDtaKYWXCI5G-LPVzsMKOuIu7qQQbeytIA6P6HT9_iIRt8zNQvuw4P9vbNjgUCpI6vfZGsjk3XuCVoB_bAIhvuBcQh9ePH2yEwS5reR-NrG1PsqzobnZZuigKCoDmuOb_UDx1DiVyNCbMBlEG7UzTQwLf5NP6HaRHx027URJeZvPAWY7zjHlSOuKoS_d1yUveaBFIgZqPWLCg44ck4gvik45HsNVWT9zYfT74dvUS
         SrMSR-SHFT7Hy1XjbVXpHJHNNAXpPoGoWXTuc0BxMsB4cqjfJqoftFGOG4x32vEzakArLPxAKwGvkvu0jToAyvSQ
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQWHw7h/Ysh6hPcXpnrJ0N8DANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDQyNzAwMDAwMFoXDTI1MDQyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBALhz3sIYOFgt3i1T5BBZY+0Q7WimFlwiORviz1c7DCjriLu6kEG3srSAOj+h0/f4iEbfMzUL7sOD/b2zY4FAqSOr32RrI5N17glaAf2wCIb7gXEIfXjx9shMEua3kfjaxtT7Ks6G52WbooCgqA5rjm/1A8dQ4lcjQmzAZRBu1M00MC3+TT+h2kR8dNu1ESXmbzwFmO84x5UjriqEv3dclL3mgRSIGaj1iwoOOHJOIL4
         pOOR7DVVk/c2H0++Hb1EkqzEkfkhxU+x8tV421V6RyRzTQF6T6BqFl07nNAcTLAeHKo3yaqH7RRjhuMd9rxM2pAKyz8QCsBr5L7tI06AMr0kCAwEAAaMhMB8wHQYDVR0OBBYEFOI7M+DDFMlP7Ac3aomPnWo1QL1SMA0GCSqGSIb3DQEBCwUAA4IBAQBv+8rBiDY8sZDBoUDYwFQM74QjqCmgNQfv5B0Vjwg20HinERjQeH24uAWzyhWN9++Fm
         eY4zcRXDY5UNmB0nJz7UGlprA9s7voQ0Lkyiud0DO072RPBg38LmmrqoBsLb3MB9MZ2CGBaHftUHfpdTvrgmXSP0IJn7mCUq27g+hFk7n/MLbN1k8JswEODIgdMRvGqN+mnrPKkviWmcVAZccsWfcmS1pKwXqICTKzd6WmVdz+cL7ZSd9I2X0pY4oRwauoE2bS95vrXljCYgLArI3XB2QcnglDDBRYu3Z3aIJb26PTIyhkVKT7xaXhXl4Ogrbm
         Qon9/O61G2dzpjzzBPqNP}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0
</code>```

答:
Store the output of the function in a variable like:

```<code>$var = Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys | ConvertFrom-Json
</code>```

then take the "keys" and "x5c" part of the variable with:

```<code>$var.keys; $var.x5c
</code>```

Body:
With Powershell 6 I am able to download a file in JSON format with:

PS C:\> Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys

kty    : RSA
use    : sig
kid    : CtTuhMJmD5M7DLdzD2v2x3QKSRY
x5t    : CtTuhMJmD5M7DLdzD2v2x3QKSRY
n      : 18uZ3P3IgOySlnOsxeIN5WUKzvlm6evPDMFbmXPtTF0GMe7tD2JPfai2UGn74s7AFwqxWO5DQZRu6VfQUux8uMR4J7nxm1Kf__7pVEVJJyDuL5a8PARRYQtH68w-0IZxcFOkgsSdhtIzPQ2jj4mmRzWXIwh8M_8pJ6qiOjvjF9bhEq0CC_f27BnljPaFn8hxY69pCoxenWWqFcsUhFZvCMthhRubAbBilDr74KaXS5xCgySBhPzwekD9_NdCUu
         Csdqavd4T-VWnbplbB8YsC-R00FptBFKuTyT9zoGZjWZilQVmj7v3k8jXqYB2nWKgTAfwjmiyKz78FHkaE-nCIDw
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQXVogj9BAf49IpuOSIvztNDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDMxNzAwMDAwMFoXDTI1MDMxNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBANfLmdz9yIDskpZzrMXiDeVlCs75ZunrzwzBW5lz7UxdBjHu7Q9iT32otlBp++LOwBcKsVjuQ0GUbulX0FLsfLjEeCe58ZtSn//+6VRFSScg7i+WvDwEUWELR+vMPtCGcXBTpILEnYbSMz0No4+Jpkc1lyMIfDP/KSeqojo74xfW4RKtAgv39uwZ5Yz2hZ/IcWOvaQqMXp1lqhXLFIRWbwjLYYUbmwGwYpQ6++Cml0u
         cQoMkgYT88HpA/fzXQlLgrHamr3eE/lVp26ZWwfGLAvkdNBabQRSrk8k/c6BmY1mYpUFZo+795PI16mAdp1ioEwH8I5osis+/BR5GhPpwiA8CAwEAAaMhMB8wHQYDVR0OBBYEFF8MDGklOGhGNVJvsHHRCaqtzexcMA0GCSqGSIb3DQEBCwUAA4IBAQCKkegw/mdpCVl1lOpgU4G9RT+1gtcPqZK9kpimuDggSJju6KUQlOCi5/lIH5DCzpjFd
         mG17TjWVBNve5kowmrhLzovY0Ykk7+6hYTBK8dNNSmd4SK7zY++0aDIuOzHP2Cur+kgFC0gez50tPzotLDtMmp40gknXuzltwJfezNSw3gLgljDsGGcDIXK3qLSYh44qSuRGwulcN2EJUZBI9tIxoODpaWHIN8+z2uZvf8JBYFjA3+n9FRQn51X16CTcjq4QRTbNVpgVuQuyaYnEtx0ZnDvguB3RjGSPIXTRBkLl2x7e8/6uAZ6tchw8rhcOtP
         sFgJuoJokGjvcUSR/6Eqd}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0

kty    : RSA
use    : sig
kid    : SsZsBNhZcF3Q9S4trpQBTByNRRI
x5t    : SsZsBNhZcF3Q9S4trpQBTByNRRI
n      : uHPewhg4WC3eLVPkEFlj7RDtaKYWXCI5G-LPVzsMKOuIu7qQQbeytIA6P6HT9_iIRt8zNQvuw4P9vbNjgUCpI6vfZGsjk3XuCVoB_bAIhvuBcQh9ePH2yEwS5reR-NrG1PsqzobnZZuigKCoDmuOb_UDx1DiVyNCbMBlEG7UzTQwLf5NP6HaRHx027URJeZvPAWY7zjHlSOuKoS_d1yUveaBFIgZqPWLCg44ck4gvik45HsNVWT9zYfT74dvUS
         SrMSR-SHFT7Hy1XjbVXpHJHNNAXpPoGoWXTuc0BxMsB4cqjfJqoftFGOG4x32vEzakArLPxAKwGvkvu0jToAyvSQ
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQWHw7h/Ysh6hPcXpnrJ0N8DANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDQyNzAwMDAwMFoXDTI1MDQyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBALhz3sIYOFgt3i1T5BBZY+0Q7WimFlwiORviz1c7DCjriLu6kEG3srSAOj+h0/f4iEbfMzUL7sOD/b2zY4FAqSOr32RrI5N17glaAf2wCIb7gXEIfXjx9shMEua3kfjaxtT7Ks6G52WbooCgqA5rjm/1A8dQ4lcjQmzAZRBu1M00MC3+TT+h2kR8dNu1ESXmbzwFmO84x5UjriqEv3dclL3mgRSIGaj1iwoOOHJOIL4
         pOOR7DVVk/c2H0++Hb1EkqzEkfkhxU+x8tV421V6RyRzTQF6T6BqFl07nNAcTLAeHKo3yaqH7RRjhuMd9rxM2pAKyz8QCsBr5L7tI06AMr0kCAwEAAaMhMB8wHQYDVR0OBBYEFOI7M+DDFMlP7Ac3aomPnWo1QL1SMA0GCSqGSIb3DQEBCwUAA4IBAQBv+8rBiDY8sZDBoUDYwFQM74QjqCmgNQfv5B0Vjwg20HinERjQeH24uAWzyhWN9++Fm
         eY4zcRXDY5UNmB0nJz7UGlprA9s7voQ0Lkyiud0DO072RPBg38LmmrqoBsLb3MB9MZ2CGBaHftUHfpdTvrgmXSP0IJn7mCUq27g+hFk7n/MLbN1k8JswEODIgdMRvGqN+mnrPKkviWmcVAZccsWfcmS1pKwXqICTKzd6WmVdz+cL7ZSd9I2X0pY4oRwauoE2bS95vrXljCYgLArI3XB2QcnglDDBRYu3Z3aIJb26PTIyhkVKT7xaXhXl4Ogrbm
         Qon9/O61G2dzpjzzBPqNP}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0

(and there are more records in the keys array...)

How could I please search for the record with kid = "SsZsBNhZcF3Q9S4trpQBTByNRRI" and then return its x5c property?

Is the following a good way to find the record (I am confused by -expand, does it strip the outside JSON object and return just the keys array?) and then how to access its x5c property please?

PS C:\> Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys |
>> Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI

kty    : RSA
use    : sig
kid    : SsZsBNhZcF3Q9S4trpQBTByNRRI
x5t    : SsZsBNhZcF3Q9S4trpQBTByNRRI
n      : uHPewhg4WC3eLVPkEFlj7RDtaKYWXCI5G-LPVzsMKOuIu7qQQbeytIA6P6HT9_iIRt8zNQvuw4P9vbNjgUCpI6vfZGsjk3XuCVoB_bAIhvuBcQh9ePH2yEwS5reR-NrG1PsqzobnZZuigKCoDmuOb_UDx1DiVyNCbMBlEG7UzTQwLf5NP6HaRHx027URJeZvPAWY7zjHlSOuKoS_d1yUveaBFIgZqPWLCg44ck4gvik45HsNVWT9zYfT74dvUS
         SrMSR-SHFT7Hy1XjbVXpHJHNNAXpPoGoWXTuc0BxMsB4cqjfJqoftFGOG4x32vEzakArLPxAKwGvkvu0jToAyvSQ
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQWHw7h/Ysh6hPcXpnrJ0N8DANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDQyNzAwMDAwMFoXDTI1MDQyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBALhz3sIYOFgt3i1T5BBZY+0Q7WimFlwiORviz1c7DCjriLu6kEG3srSAOj+h0/f4iEbfMzUL7sOD/b2zY4FAqSOr32RrI5N17glaAf2wCIb7gXEIfXjx9shMEua3kfjaxtT7Ks6G52WbooCgqA5rjm/1A8dQ4lcjQmzAZRBu1M00MC3+TT+h2kR8dNu1ESXmbzwFmO84x5UjriqEv3dclL3mgRSIGaj1iwoOOHJOIL4
         pOOR7DVVk/c2H0++Hb1EkqzEkfkhxU+x8tV421V6RyRzTQF6T6BqFl07nNAcTLAeHKo3yaqH7RRjhuMd9rxM2pAKyz8QCsBr5L7tI06AMr0kCAwEAAaMhMB8wHQYDVR0OBBYEFOI7M+DDFMlP7Ac3aomPnWo1QL1SMA0GCSqGSIb3DQEBCwUAA4IBAQBv+8rBiDY8sZDBoUDYwFQM74QjqCmgNQfv5B0Vjwg20HinERjQeH24uAWzyhWN9++Fm
         eY4zcRXDY5UNmB0nJz7UGlprA9s7voQ0Lkyiud0DO072RPBg38LmmrqoBsLb3MB9MZ2CGBaHftUHfpdTvrgmXSP0IJn7mCUq27g+hFk7n/MLbN1k8JswEODIgdMRvGqN+mnrPKkviWmcVAZccsWfcmS1pKwXqICTKzd6WmVdz+cL7ZSd9I2X0pY4oRwauoE2bS95vrXljCYgLArI3XB2QcnglDDBRYu3Z3aIJb26PTIyhkVKT7xaXhXl4Ogrbm
         Qon9/O61G2dzpjzzBPqNP}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0

Body:
Store the output of the function in a variable like:

$var = Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys | ConvertFrom-Json

then take the "keys" and "x5c" part of the variable with:

$var.keys; $var.x5c


答:
Use facial landmarks with dlib, this method may work for you, see these two links:

facial-landmarks-dlib-opencv-python

opencv-face-recognition

Also, see this link:

dlib-and-deep-learning

Title: Detect faces without eyebrows and jaw using opencv


问:
How can I get my JLabel Icon Images to be high resolution?
I want to make an application with a small jLabel(50x50) in its corner.

The Problem I now have is that the Image the Label displays is looking really bad.

I also added the same Image as an Icon to a shortcut in windows on my desktop just as a comparison.

Windows on the left side and Java JLabel on the right.

How can I archive a similar scaling result in Jave with no loss in quality?

It does not need to use JLabel.

Code:

```<code>    ImageIcon imgIcon = new ImageIcon(path);
    Image img = imgIcon.getImage();
    Image imgScaled = img.getScaledInstance((int) (getWidth()), (int) (getHeight()),
    Image.SCALE_SMOOTH);

    ImageIcon image = new ImageIcon(imgScaled);
    label.setIcon(image);
</code>```

EDIT:

If you look at these Google Chrome Icons, they are extremely tiny but still sharp and high resolution, how can I archive this in Java?

答:
I see two options, or maybe a combination of this:

You're using a weird resolution image for your ImageIcon

Ratio of width to height is not equal, thus skewed scaling

EDIT In case 2, make sure the JComponent you're using to fetch dimensions from (the one you're calling getWidth and getHeight on) has equal dimensions for both width and height.

I cut your left image, at 62px width/height. First row shows that image scaled, second row shows what happens when I scale the source image down to 32px in graphics program first:

Dimensions, as you can see below, go from 62px up by increments of 10px. Code was run on Java 1.8, Windows 10:

```<code>void addSeries(Image srcImg, JPanel targetPanel) {
    for (int i = 0; i < 50; i += 10) {
        int dimension = 62 + i;
        Image imgScaled = srcImg.getScaledInstance(dimension, dimension, Image.SCALE_SMOOTH);

        ImageIcon scaledIcon = new ImageIcon(imgScaled);
        JLabel label = new JLabel();
        label.setIcon(scaledIcon);
        targetPanel.add(label);
    }
}
</code>```

Body:
I want to make an application with a small jLabel(50x50) in its corner.

The Problem I now have is that the Image the Label displays is looking really bad.

I also added the same Image as an Icon to a shortcut in windows on my desktop just as a comparison.

Windows on the left side and Java JLabel on the right.

How can I archive a similar scaling result in Jave with no loss in quality?

It does not need to use JLabel.

Code:

    ImageIcon imgIcon = new ImageIcon(path);
    Image img = imgIcon.getImage();
    Image imgScaled = img.getScaledInstance((int) (getWidth()), (int) (getHeight()),
    Image.SCALE_SMOOTH);

    ImageIcon image = new ImageIcon(imgScaled);
    label.setIcon(image);

EDIT:

If you look at these Google Chrome Icons, they are extremely tiny but still sharp and high resolution, how can I archive this in Java?

Body:
I see two options, or maybe a combination of this:

You're using a weird resolution image for your ImageIcon

Ratio of width to height is not equal, thus skewed scaling

EDIT In case 2, make sure the JComponent you're using to fetch dimensions from (the one you're calling getWidth and getHeight on) has equal dimensions for both width and height.

I cut your left image, at 62px width/height. First row shows that image scaled, second row shows what happens when I scale the source image down to 32px in graphics program first:

Dimensions, as you can see below, go from 62px up by increments of 10px. Code was run on Java 1.8, Windows 10:

void addSeries(Image srcImg, JPanel targetPanel) {
    for (int i = 0; i < 50; i += 10) {
        int dimension = 62 + i;
        Image imgScaled = srcImg.getScaledInstance(dimension, dimension, Image.SCALE_SMOOTH);

        ImageIcon scaledIcon = new ImageIcon(imgScaled);
        JLabel label = new JLabel();
        label.setIcon(scaledIcon);
        targetPanel.add(label);
    }
}


问:
Why does Xcode line-out autocomplete methods for selector?
Ever since I upgraded to the latest Xcode, autocomplete lines out (strikethrough) methods for the selector object. I cannot tell if this is a bug with Xcode or there is some new syntax change I'm unaware of. If you plug this into your Playground and erase the method inside #selector(tapHandler(_:)) and re-enter it, does autocomplete line-out the tapHandler(_:) suggestion or not?

```<code>class Mango {
    func tap() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapHandler(_:)))
    }

    @objc func tapHandler(_ sender: UITapGestureRecognizer) {

    }
}
</code>```

答:
Instead of typing tapH and asking for autocomplete, type self.tapH and ask for autocomplete. The problem goes away.

So, yes, I do rather think it's a bug (unless Swift is changing so that you can't omit the class in a method reference), but there's also an easy workaround.

Body:
Ever since I upgraded to the latest Xcode, autocomplete lines out (strikethrough) methods for the selector object. I cannot tell if this is a bug with Xcode or there is some new syntax change I'm unaware of. If you plug this into your Playground and erase the method inside #selector(tapHandler(_:)) and re-enter it, does autocomplete line-out the tapHandler(_:) suggestion or not?

class Mango {
    func tap() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapHandler(_:)))
    }

    @objc func tapHandler(_ sender: UITapGestureRecognizer) {

    }
}


问:
determine if an application is shutting down normally
is there a way to determing if a jvm is shutting down normally?  Shutdown hook can only spawn a thread, is there a way to determine if the JVM is existing normally or abnormally at that time?</p>

答: When the JVM is shutting down normally, this means that the main thread has ended. If the JVM is shutting down for some other resaon (e.g. the user pressed Strg+C), the main thread is still running. So you can store a reference to the main thread in your shutdown hook and check whether this thread is still alive. Of course this assumes that the main thread will normally be the last running thread in your application. I don't know how the situation is if one of the threads called System.exit(), but you could easily find this out.</p>


问:
Dynamically creating buttons and assigning click actions
I'm trying to practise by making a Pokedex. I'm trying to dynamically create a list of buttons inside of an OVBoxLayout based on the response from an API call. The list of buttons is generated correctly however, none of the buttons work, code below:

```<code>from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
from app.pokeapi_client import PokeApiClient

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setup_styles()

        self.pokemon_list_data = PokeApiClient().get_pokemon_list(limit=9)
        self.setWindowTitle("Pokemon")
        self.resize(1000, 800)

       # create main layout
       main_layout = QHBoxLayout()

       # build list layout and populate with labels
       self.pokemon_list_layout = QVBoxLayout()
       self.populate_pokemon_list_layout()

       # add list layout to main layout
       main_layout.addLayout(self.pokemon_list_layout, 1)

       self.setLayout(main_layout)

    def populate_pokemon_list_layout(self):
        for pokemon in self.pokemon_list_data['results']:
            button = QPushButton(pokemon['name'])
            button.clicked.connect(self.print_this)
            self.pokemon_list_layout.addWidget(button)

    def print_this(self):
        print("hello world!")

    def setup_styles(self):
        self.setStyleSheet("""
            QWidget {
                background: red;
            }
            QPushButton {
                color: white;
                background: blue;
                border: 1px solid white;
            }
        """)
</code>```

The button.clicked.connect() doesn't appear to be assigning the function to each button, anyone know why this might be happening?

答:
Here is a MRE with your code :

```<code>from PySide2 import QtWidgets
from PySide2 import QtCore
from PySide2 import QtGui

DATA = {'results':[{'name':'pikka'}, {'name': 'dracofeu'}, {'name': 'mewtwo'}]}

class MainWindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.pokemon_list_data = DATA #Emulation data
        self.setWindowTitle("Pokemon")
        # self.resize(1000, 800)

        # create main layout
        main_layout = QtWidgets.QHBoxLayout()

        # build list layout and populate with labels
        self.pokemon_list_layout = QtWidgets.QVBoxLayout()
        self.populate_pokemon_list_layout()

        # add list layout to main layout
        main_layout.addLayout(self.pokemon_list_layout, 1)
        self.setLayout(main_layout)

    def populate_pokemon_list_layout(self):
        for pokemon in self.pokemon_list_data['results']:
            button = QtWidgets.QPushButton(pokemon['name'])
            button.clicked.connect(self.print_this)
            self.pokemon_list_layout.addWidget(button)

    def print_this(self):
        sender = self.sender()
        print(sender.text())

app = QtWidgets.QApplication([])
test = MainWindow()
test.show()
app.exec_()
</code>```

Here is the result :

As you can see I didn't change anything (except imports and the sender in the print_this method) but it works. I think you have a problem somewhere in your code.

Body:
I'm trying to practise by making a Pokedex. I'm trying to dynamically create a list of buttons inside of an OVBoxLayout based on the response from an API call. The list of buttons is generated correctly however, none of the buttons work, code below:

from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
from app.pokeapi_client import PokeApiClient

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setup_styles()

        self.pokemon_list_data = PokeApiClient().get_pokemon_list(limit=9)
        self.setWindowTitle("Pokemon")
        self.resize(1000, 800)

       # create main layout
       main_layout = QHBoxLayout()

       # build list layout and populate with labels
       self.pokemon_list_layout = QVBoxLayout()
       self.populate_pokemon_list_layout()

       # add list layout to main layout
       main_layout.addLayout(self.pokemon_list_layout, 1)

       self.setLayout(main_layout)

    def populate_pokemon_list_layout(self):
        for pokemon in self.pokemon_list_data['results']:
            button = QPushButton(pokemon['name'])
            button.clicked.connect(self.print_this)
            self.pokemon_list_layout.addWidget(button)

    def print_this(self):
        print("hello world!")

    def setup_styles(self):
        self.setStyleSheet("""
            QWidget {
                background: red;
            }
            QPushButton {
                color: white;
                background: blue;
                border: 1px solid white;
            }
        """)

The button.clicked.connect() doesn't appear to be assigning the function to each button, anyone know why this might be happening?

Body:
Here is a MRE with your code :

from PySide2 import QtWidgets
from PySide2 import QtCore
from PySide2 import QtGui

DATA = {'results':[{'name':'pikka'}, {'name': 'dracofeu'}, {'name': 'mewtwo'}]}

class MainWindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.pokemon_list_data = DATA #Emulation data
        self.setWindowTitle("Pokemon")
        # self.resize(1000, 800)

        # create main layout
        main_layout = QtWidgets.QHBoxLayout()

        # build list layout and populate with labels
        self.pokemon_list_layout = QtWidgets.QVBoxLayout()
        self.populate_pokemon_list_layout()

        # add list layout to main layout
        main_layout.addLayout(self.pokemon_list_layout, 1)
        self.setLayout(main_layout)

    def populate_pokemon_list_layout(self):
        for pokemon in self.pokemon_list_data['results']:
            button = QtWidgets.QPushButton(pokemon['name'])
            button.clicked.connect(self.print_this)
            self.pokemon_list_layout.addWidget(button)

    def print_this(self):
        sender = self.sender()
        print(sender.text())

app = QtWidgets.QApplication([])
test = MainWindow()
test.show()
app.exec_()

Here is the result :

As you can see I didn't change anything (except imports and the sender in the print_this method) but it works. I think you have a problem somewhere in your code.


问:
fetch function returns 400 bad request error for content-type 'application/x-www-form-urlencoded'
This question has been asked before but those solutions i have already tried and i shall
explain along the way.

Task:

I want to send data to api with content-type as "application/x-www-form-urlencoded".

Problem:

The URL works fine in Postman and returns me the correct response. When i try the same body parameters through my Reactjs app, it responds with 400 bad request error.

What i have tried:

```<code>myBody:{
grant_type:"XYZ",
client_id:"XYZ"
}
var request = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            method: "POST",
            body:myBody
        };
</code>```

Then i fetch something like this.

```<code>const data = yield fetch(complete_url,request);
</code>```

I also tried to compose myBody as a formData . Still gives the same error.

Apologies i have not given the URL because of restrictions. I am looking for possibilities of errors i could make.

答:
With 'Content-Type': 'application/x-www-form-urlencoded',

Your request body should follow certain rule (https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).

the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value,

example:

grant_type =value1&client_id=value2.
So i suggest what it looks like in debugger -> network tab.

If the request body is not a problem. Then you should check if there's any special chars.
You also will need to escape symbols and special chars.

Body:
This question has been asked before but those solutions i have already tried and i shall
explain along the way.

Task:

I want to send data to api with content-type as "application/x-www-form-urlencoded".

Problem:

The URL works fine in Postman and returns me the correct response. When i try the same body parameters through my Reactjs app, it responds with 400 bad request error.

What i have tried:

myBody:{
grant_type:"XYZ",
client_id:"XYZ"
}
var request = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            method: "POST",
            body:myBody
        };

Then i fetch something like this.

const data = yield fetch(complete_url,request);

I also tried to compose myBody as a formData . Still gives the same error.

Apologies i have not given the URL because of restrictions. I am looking for possibilities of errors i could make.


问:
setInterval function without arrow function
I am learning about react components following the documentation https://facebook.github.io/react/docs/state-and-lifecycle.html

Why do we need to use arrow function here:

```<code>this.timerID = setInterval(() => this.tick(), 1000);
</code>```

Why can't I just say (obviously it doesn't work)

```<code>this.timerID = setInterval(this.tick(), 1000);
</code>```

答:
Why do we need to use arrow function here

Answer is simple :
see the result inside live script example...

class Persons{

    scopeOne(){
          // your will see the result this will display our current object 'Persons'
          setInterval(function(){

              console.info(' SCOPE ONEo : '+this);

          },3000);
    }
    scopeTwo(){
          setInterval(function(){

              console.info(' SCOPE TWO : '+this);

          }.bind(this) ,3000);
    }

    scopeThree(){
        setInterval(() => { console.info(' SCOPE THREE : '+this) },3000);
    }
}

let p = new Persons();
    p.scopeOne();
    p.scopeTwo();
    p.scopeThree();```

in first scope the result is WINDOW OBJECT so we cannot access our current class scope
so in 2nd scope we using scope with bind(this) that helps to bind our current object scope,
and in third which do same as 2nd scope calling the current object....

Body:
I am learning about react components following the documentation https://facebook.github.io/react/docs/state-and-lifecycle.html

Why do we need to use arrow function here:

this.timerID = setInterval(() => this.tick(), 1000);

Why can't I just say (obviously it doesn't work)

this.timerID = setInterval(this.tick(), 1000);

Body:
Why do we need to use arrow function here

Answer is simple :
see the result inside live script example...

class Persons{

    scopeOne(){
          // your will see the result this will display our current object 'Persons'
          setInterval(function(){

              console.info(' SCOPE ONEo : '+this);

          },3000);
    }
    scopeTwo(){
          setInterval(function(){

              console.info(' SCOPE TWO : '+this);

          }.bind(this) ,3000);
    }

    scopeThree(){
        setInterval(() => { console.info(' SCOPE THREE : '+this) },3000);
    }
}

let p = new Persons();
    p.scopeOne();
    p.scopeTwo();
    p.scopeThree();

in first scope the result is WINDOW OBJECT so we cannot access our current class scope
so in 2nd scope we using scope with bind(this) that helps to bind our current object scope,
and in third which do same as 2nd scope calling the current object....


问:
Not able to access websites when Charles Proxy is opened (Windows 10)
I downloaded the app Charles Proxy, I added the certificate and I can confirm that the Charles certificate is in my certlm (Certificate Manager) in the "Trusted Root Certification" folder, I had also enabled SSL Proxying to include this location: "*:443" which I believe means that I want to see all data coming in.

I'm not sure what the problem is, but whenever I open up Charles Proxy, it doesn't allow me to access any websites, all the data coming in Charles is coming in as status: "Blocked"

I'm using Windows 10 if that helps. I didn't have this issue on MacOS, Help is appreciated!

答:
I don't have a Windows machine to try any of this out, but I've always found the documentation helpful. </p>

<p>There may be something that you've overlooked in the configuration, ssl proxying or ssl certificates sections. </p>

Body:
I don't have a Windows machine to try any of this out, but I've always found the documentation helpful.

There may be something that you've overlooked in the configuration, ssl proxying or ssl certificates sections.


问:
Using Tkinter, Threading and After method
im working on a selenium project using tkinter in python. I want to execute many selenium task at one time(could be up to 100), so I used threading to accomplish this goal, but I came to a problem, due to the fact that I need all individual selenium task to wait a couple seconds between instructions, I used the '.after' method but for some reason my program is still freezing up, I've done a lot of research but I cant seem to find the answer yet. Isn't there a way to use tkinter, threading and some sort of sleeping in python? Do I need to switch to multiprocessing? but I would need all selenium processes to finish within the same 2 minutes and each process takes about a minute.(e.g lets say i start 100, 1 minute processes at 6:00 all task would need to be finished by 6:02)

I created minimal code which mimics my selenium script, so its easier to read, here it is:

```<code>from tkinter import *
import tkinter as tk
import time
root = tk.Tk()
root.geometry('700x700')
import threading
class Make:
    def __init__(self,num):
        self.num = num.get()
        Label(root,text='HELLO WORLD WILL PRINT: '+str(self.num)+' times, press go to confirm').pack()
        Button(root, text='go', command=lambda: self.starting()).pack()

    def starting(self):

        for count in range(self.num):
            t = threading.Thread(target=gogogo())
            t.start()

def gogogo():
    tk.Label(root,text='HELLO WORLD').pack()
    root.after(2000,print('Please wait 2 seconds'))
    tk.Label(root,text='You are inside my world').pack()

Label(root,text='How many times should I print: HELLO WORLD').pack()

num = IntVar()
Entry(root, textvariable=num).pack()

Button(root, text='Start', command=lambda: Make(num)).pack()

root.mainloop()
</code>```

答:
You main problem is that after() and Thread() similar to command= needs only function's name without () and it will later use () to execute it.

Other problem is that after() doesn't stop code but it only send information to mainloop to execute function after 2000ms and later Python runs at once next line after after(). You have to add Label in fucntion executed by after()

```<code>def gogogo():
    tk.Label(root, text='HELLO WORLD').pack()
    print('Please wait 2 seconds')
    root.after(2000, next_message) # function's name without ()

def next_message():
    tk.Label(root, text='You are inside my world').pack()
</code>```

```<code># from tkinter import * # PEP8: `import *` is not preferred
import tkinter as tk
import threading
import time

class Make:

    def __init__(self, num):
        self.num = num.get()

        text = 'HELLO WORLD WILL PRINT: {} times, press go to confirm'.format(self.num)
        tk.Label(root, text=text).pack()

        tk.Button(root, text='go', command=self.starting).pack()

    def starting(self):
        for count in range(self.num):
            t = threading.Thread(target=gogogo) # function's name without ()
            t.start()

def gogogo():
    tk.Label(root, text='HELLO WORLD').pack()
    print('Please wait 2 seconds')
    root.after(2000, next_message) # function's name without ()

def next_message():
    tk.Label(root, text='You are inside my world').pack()

# --- main ---

root = tk.Tk()
root.geometry('700x700')

tk.Label(root, text='How many times should I print: HELLO WORLD').pack()

num = tk.IntVar()
tk.Entry(root, textvariable=num).pack()

tk.Button(root, text='Start', command=lambda:Make(num)).pack()

root.mainloop()
</code>```

EDIT: Because gogogo() runs in separated thread so you can also use time.sleep() because it doesn't block mainloop() in main thread

```<code>def gogogo():
    tk.Label(root, text='HELLO WORLD').pack()
    print('Please wait 2 seconds')
    time.sleep(2)
    tk.Label(root, text='You are inside my world').pack()
</code>```

Body:
im working on a selenium project using tkinter in python. I want to execute many selenium task at one time(could be up to 100), so I used threading to accomplish this goal, but I came to a problem, due to the fact that I need all individual selenium task to wait a couple seconds between instructions, I used the '.after' method but for some reason my program is still freezing up, I've done a lot of research but I cant seem to find the answer yet. Isn't there a way to use tkinter, threading and some sort of sleeping in python? Do I need to switch to multiprocessing? but I would need all selenium processes to finish within the same 2 minutes and each process takes about a minute.(e.g lets say i start 100, 1 minute processes at 6:00 all task would need to be finished by 6:02)

I created minimal code which mimics my selenium script, so its easier to read, here it is:

from tkinter import *
import tkinter as tk
import time
root = tk.Tk()
root.geometry('700x700')
import threading
class Make:
    def __init__(self,num):
        self.num = num.get()
        Label(root,text='HELLO WORLD WILL PRINT: '+str(self.num)+' times, press go to confirm').pack()
        Button(root, text='go', command=lambda: self.starting()).pack()

    def starting(self):

        for count in range(self.num):
            t = threading.Thread(target=gogogo())
            t.start()

def gogogo():
    tk.Label(root,text='HELLO WORLD').pack()
    root.after(2000,print('Please wait 2 seconds'))
    tk.Label(root,text='You are inside my world').pack()

Label(root,text='How many times should I print: HELLO WORLD').pack()

num = IntVar()
Entry(root, textvariable=num).pack()

Button(root, text='Start', command=lambda: Make(num)).pack()

root.mainloop()

Body:
You main problem is that after() and Thread() similar to command= needs only function's name without () and it will later use () to execute it.

Other problem is that after() doesn't stop code but it only send information to mainloop to execute function after 2000ms and later Python runs at once next line after after(). You have to add Label in fucntion executed by after()

def gogogo():
    tk.Label(root, text='HELLO WORLD').pack()
    print('Please wait 2 seconds')
    root.after(2000, next_message) # function's name without ()

def next_message():
    tk.Label(root, text='You are inside my world').pack()

# from tkinter import * # PEP8: `import *` is not preferred
import tkinter as tk
import threading
import time

class Make:

    def __init__(self, num):
        self.num = num.get()

        text = 'HELLO WORLD WILL PRINT: {} times, press go to confirm'.format(self.num)
        tk.Label(root, text=text).pack()

        tk.Button(root, text='go', command=self.starting).pack()

    def starting(self):
        for count in range(self.num):
            t = threading.Thread(target=gogogo) # function's name without ()
            t.start()

def gogogo():
    tk.Label(root, text='HELLO WORLD').pack()
    print('Please wait 2 seconds')
    root.after(2000, next_message) # function's name without ()

def next_message():
    tk.Label(root, text='You are inside my world').pack()

# --- main ---

root = tk.Tk()
root.geometry('700x700')

tk.Label(root, text='How many times should I print: HELLO WORLD').pack()

num = tk.IntVar()
tk.Entry(root, textvariable=num).pack()

tk.Button(root, text='Start', command=lambda:Make(num)).pack()

root.mainloop()

EDIT: Because gogogo() runs in separated thread so you can also use time.sleep() because it doesn't block mainloop() in main thread

def gogogo():
    tk.Label(root, text='HELLO WORLD').pack()
    print('Please wait 2 seconds')
    time.sleep(2)
    tk.Label(root, text='You are inside my world').pack()