问:
PI nth digit after decimal
I want to make a program which will return a nth number of digits after decimal in PI number.
It works good as long as I don't put n higher than 50. Can I fix it or Python don't allow that?

Here's my code:

```<code>pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428

def nth_pi_digit(n=input("How many digits after decimal you would like to see?(PI number):  ")):
    try:
        n = int(n)
        if n <= 204:
            return print(format(pi, f".{n}f"))
        else:
            print("Sorry, we have pi with 204 digits after decimal, so we'll print that")
            return print(format(pi, ".204f"))
    except:
        print("You need to put a integer digit")

nth_pi_digit()
</code>```

Title: PI nth digit after decimal

Body:
I want to make a program which will return a nth number of digits after decimal in PI number.
It works good as long as I don't put n higher than 50. Can I fix it or Python don't allow that?

Here's my code:

pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428

def nth_pi_digit(n=input("How many digits after decimal you would like to see?(PI number):  ")):
    try:
        n = int(n)
        if n <= 204:
            return print(format(pi, f".{n}f"))
        else:
            print("Sorry, we have pi with 204 digits after decimal, so we'll print that")
            return print(format(pi, ".204f"))
    except:
        print("You need to put a integer digit")

nth_pi_digit()

Body:
You can simply use text:

pi = '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428'

Though using decimal is better.


来源: stackexchange

问:
for jquery is there any error thrown when manipulating a dom element that doesnt exist
In my code I'm not checking if a DOM element exists before I manipulate it and jquery does not seem to throw any errors, even if it doesn't exist.

```<code>$('.test').addClass('hide');
</code>```

where the test class doesn't exist, but this doesn't throw any errors.

So is this expected? should I be checking if it exists first?

答:
You can use:

```<code>if ($('.test').length) {
   // do stuff
}
</code>```

With JS only:

```<code>document.querySelector('non existing') // => null
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my code I'm not checking if a DOM element exists before I manipulate it and jquery does not seem to throw any errors, even if it doesn't exist.

$('.test').addClass('hide');

where the test class doesn't exist, but this doesn't throw any errors.

So is this expected? should I be checking if it exists first?

Body:
You can use:

if ($('.test').length) {
   // do stuff
}

With JS only:

document.querySelector('non existing') // => null


问:
How can I cast column and use between function together in a query in postgresql
```<code>select cast (xyz as numeric)
from clustering
where xyz between 100 and 500
order by xyz asc;
</code>```

答:
Cast your column in your WHERE clause as well:

```<code>select cast(xyz as numeric)
from clustering
where cast(xyz as numeric) between 100 and 500
order by xyz asc;
</code>```

Body:
Cast your column in your WHERE clause as well:

select cast(xyz as numeric)
from clustering
where cast(xyz as numeric) between 100 and 500
order by xyz asc;


问:
Angular 8 SyntaxError: Unexpected token B in JSON at position 0 at JSON.parse httpPost
Iam trying to send form Data from my Service to the Server but i get an error Respons everytime also the File is Uploaded Properly: How can i avoid the error msg

Upload.Service.ts:

```<code>  uploadFile(id: number) {
    let success = false;
    const headers = new HttpHeaders({
      'Authorization' : ' Bearer ' + this.authService.authToken()
    });
    const options = {
      headers: headers
    };
    const formData: FormData = new FormData();
    formData.append('file', this.files[id]);
    this.http.post(URL, formData, options).toPromise().then(res => {
        console.log(res);
        success = true;
    }).catch(err => {
        console.log(err);
        success = false;
     });
     return success;
 }
</code>```

Error:

```<code>HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:5000/api/upload", ok: false, …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 200
statusText: "OK"
url: "http://localhost:5000/api/upload"
ok: false
name: "HttpErrorResponse"
message: "Http failure during parsing for http://localhost:5000/api/upload"
error:
error: SyntaxError: Unexpected token B in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:19729:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6246:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:81825:33) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6245:60) at Zone.runTask (http://localhost:4200/polyfills.js:6023:47) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:6320:34) at invokeTask (http://localhost:4200/polyfills.js:7458:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:7495:21)
text: "BlaBla - Kopie.sds"
__proto__: Object
__proto__: HttpResponseBase
constructor: class HttpErrorResponse
__proto__: Object
</code>```

Can somebody Help with that please ?

答:
just make sure your backend server returns a JSONformatted output as the response of file upload api.

or you may overwrite the default responseType to the format you are working with.

or you may read the full response without any preprocessing

https://angular.io/guide/http#reading-the-full-response

https://stackoverflow.com/a/48073486/6543507

Body:
Iam trying to send form Data from my Service to the Server but i get an error Respons everytime also the File is Uploaded Properly: How can i avoid the error msg

Upload.Service.ts:

  uploadFile(id: number) {
    let success = false;
    const headers = new HttpHeaders({
      'Authorization' : ' Bearer ' + this.authService.authToken()
    });
    const options = {
      headers: headers
    };
    const formData: FormData = new FormData();
    formData.append('file', this.files[id]);
    this.http.post(URL, formData, options).toPromise().then(res => {
        console.log(res);
        success = true;
    }).catch(err => {
        console.log(err);
        success = false;
     });
     return success;
 }

Error:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:5000/api/upload", ok: false, …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 200
statusText: "OK"
url: "http://localhost:5000/api/upload"
ok: false
name: "HttpErrorResponse"
message: "Http failure during parsing for http://localhost:5000/api/upload"
error:
error: SyntaxError: Unexpected token B in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:19729:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6246:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:81825:33) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6245:60) at Zone.runTask (http://localhost:4200/polyfills.js:6023:47) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:6320:34) at invokeTask (http://localhost:4200/polyfills.js:7458:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:7495:21)
text: "BlaBla - Kopie.sds"
__proto__: Object
__proto__: HttpResponseBase
constructor: class HttpErrorResponse
__proto__: Object

Can somebody Help with that please ?


问:
Bluez blotoothctl scan vs hcitool scan
I'm running bluez 5.50 on a Raspberry Pi (both Buster and Stretch). I have a ble sensor device that advertises data only when a button on the sensor device is pressed. So advertisements are asynchronous and there are no periodic advertisements in between (and all packets are unique, no duplicates). I'm having an issue with Bluez though where once a packet is received, Bluez seems to not report any additional packets from the device for the next approximately 11 seconds (very occasionally the interval is shorter). This is with the bluetoothctl line command tool as well as my own c++ application (based off the bluez client/main.c example). In both cases before starting a scan I clear the scan filter, set transport to le, and set duplicate-data reporting on. Conversely, when running hcitool scan I see all the packets from the sensor (it even seems to be reporting all 3 copies broadcast on the different advertisement channels). So my question is, is there a way to get those missing advertisements through the dbus api, possibly some additional setting somewhere? If not, is the hci api okay to use from c++ and should it do the trick? Any help appreciated, thanks!

Edited per Alex's questions -

Have you tried downloading the latest bluez (5.53) https://git.kernel.org/pub/scm/bluetooth/bluez.git ?

Not yet, just wanted to check and see if this might be something known beforehand.

Are you using hcitool scan or sudo hcitool lescan? If you are running hcitool scan, you are picking up bluetooth classic (not low energy packets). hcitool is a deprecated tool. I've found that sudo hcitool lescan only works with BLE 4.x controllers. The function fails on 5.x controller.

hcitool lescan (under root), and yes, the hardware is a Pi Zero/W and a P3 so BLE 4.x controllers (I assume)

Have you tried running sudo btmon to see all of the HCI communication during scanning?

I have but can't remember exactly what I saw other than it didn't contradict anything else, i.e. missing packets w/ dbus api vs hci

Can you provide code for your use of bluetoothctl, ie:

```<code>$bluetoothctl
[bluetooth]# menu scan
[bluetooth]# clear
[bluetooth]# transport le
[bluetooth]# duplicated-data on
[bluetooth]# back
[bluetooth]# scan on
</code>```

always exactly as you've noted...

Could you also provide the results of hciconfig -a

```<code>--- Results (P Zero) -

hci0:   Type: Primary  Bus: UART
        BD Address: B8:27:EB:79:2E:3F  ACL MTU: 1021:8  SCO MTU: 64:1
        UP RUNNING
        RX bytes:55476 acl:126 sco:0 events:2012 errors:0
        TX bytes:6956 acl:114 sco:0 commands:444 errors:0
        Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87
        Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
        Link policy: RSWITCH SNIFF
        Link mode: SLAVE ACCEPT
        Name: 'HubPi01'
        Class: 0x000000
        Service Classes: Unspecified
        Device Class: Miscellaneous,
        HCI Version: 4.1 (0x7)  Revision: 0x168
        LMP Version: 4.1 (0x7)  Subversion: 0x2209
        Manufacturer: Broadcom Corporation (15)

--- Results (P3) -

hci0:   Type: Primary  Bus: UART
        BD Address: B8:27:EB:2B:A2:A3  ACL MTU: 1021:8  SCO MTU: 64:1
        UP RUNNING
        RX bytes:10995 acl:0 sco:0 events:390 errors:0
        TX bytes:2145 acl:0 sco:0 commands:91 errors:0
        Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87
        Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
        Link policy: RSWITCH SNIFF
        Link mode: SLAVE ACCEPT
        Name: 'HubPi02'
        Class: 0x000000
        Service Classes: Unspecified
        Device Class: Miscellaneous,
        HCI Version: 4.1 (0x7)  Revision: 0x168
        LMP Version: 4.1 (0x7)  Subversion: 0x2209
        Manufacturer: Broadcom Corporation (15)
</code>```

Below is a scan covering about 20 seconds (editing out all unrelated packets),
where I'm pressing down the button on the sensor about every 2 seconds and then
holding it down for another 2 seconds before letting it up. The first chunk
is from bluetoothctl, the second from "hcidump --raw" (on a second raspberry pi). The first four bytes
in the bluetoothctl packet data is a little endian packet seq number
incremented by the sensor for each new packet. The next byte indicates a
button up/down action. You can see bluetoothctl reported packets numbered 05df,
05e5, 05e9. In the raw dump the seq number is at the end of the top line. There
you can see all packets are in order, reported 1 to 3 times (I assume it is
reporting all advertising channels it catches). All packets are present 05df to
05e9 in the hcidump scan. Lastly is the output from "hcitool lescan --duplicates",
which I'm not really sure how it maps...

```<code>
------ bluetoothctl
                                .
[NEW] Device E2:15:00:01:73:96 E2-15-00-01-73-96

[CHG] Device E2:15:00:01:73:96 RSSI: -46
[CHG] Device E2:15:00:01:73:96 ManufacturerData Key: 0x03da
[CHG] Device E2:15:00:01:73:96 ManufacturerData Value:
  df 05 00 00 10 a1 ac 8a b4                       .........

[CHG] Device E2:15:00:01:73:96 RSSI: -45
[CHG] Device E2:15:00:01:73:96 ManufacturerData Key: 0x03da
[CHG] Device E2:15:00:01:73:96 ManufacturerData Value:
  e5 05 00 00 10 e7 4f 67 6e                       ......Ogn
                                             .
[CHG] Device E2:15:00:01:73:96 RSSI: -65
[CHG] Device E2:15:00:01:73:96 ManufacturerData Key: 0x03da
[CHG] Device E2:15:00:01:73:96 ManufacturerData Value:
  e9 05 00 00 10 f4 f9 f8 7d                       ........}

---------- hcidump --raw

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 DF 05
  00 00 10 A1 AC 8A B4 C3
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 DF 05
  00 00 10 A1 AC 8A B4 BE

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E0 05
  00 00 11 11 0F 3E 24 B6

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E1 05
  00 00 10 F7 68 07 50 BE
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E1 05
  00 00 10 F7 68 07 50 CF
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E1 05
  00 00 10 F7 68 07 50 BA

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E2 05
  00 00 11 1D 18 A8 2A BF
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E2 05
  00 00 11 1D 18 A8 2A C0
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E2 05
  00 00 11 1D 18 A8 2A B8

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E3 05
  00 00 10 E2 29 C7 F7 BB

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E4 05
  00 00 11 57 F0 5C 76 BD
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E4 05
  00 00 11 57 F0 5C 76 C1

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E5 05
  00 00 10 E7 4F 67 6E CA

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E6 05
  00 00 11 77 63 92 CE C0
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E6 05
  00 00 11 77 63 92 CE BA
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E6 05
  00 00 11 77 63 92 CE BE

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E7 05
  00 00 10 2D 52 48 C2 BD

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E8 05
  00 00 11 EE 32 20 9D BD
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E8 05
  00 00 11 EE 32 20 9D C1

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E9 05
  00 00 10 F4 F9 F8 7D BC

------- hcitool lescan --duplicates

E2:15:00:01:73:96 (unknown)
E2:15:00:01:73:96 (unknown)
E2:15:00:01:73:96 (unknown)

E2:15:00:01:73:96 (unknown)

E2:15:00:01:73:96 (unknown)
E2:15:00:01:73:96 (unknown)

E2:15:00:01:73:96 (unknown)

</code>```

答:
Have you tried downloading the latest bluez (5.53) https://git.kernel.org/pub/scm/bluetooth/bluez.git ?

Are you using hcitool scan or sudo hcitool lescan? If you are running hcitool scan, you are picking up bluetooth classic (not low energy packets). hcitool is a deprecated tool. I've found that sudo hcitool lescan only works with BLE 4.x controllers. The function fails on 5.x controller.

Have you tried running sudo btmon to see all of the HCI communication during scanning?

Can you provide code for your use of bluetoothctl, ie:

```<code>$bluetoothctl
[bluetooth]# menu scan
[bluetooth]# clear
[bluetooth]# transport le
[bluetooth]# duplicated-data on
[bluetooth]# back
[bluetooth]# scan on
</code>```

Could you also provide the results of hciconfig -a

Title: Bluez blotoothctl scan vs hcitool scan

Body:
I'm running bluez 5.50 on a Raspberry Pi (both Buster and Stretch). I have a ble sensor device that advertises data only when a button on the sensor device is pressed. So advertisements are asynchronous and there are no periodic advertisements in between (and all packets are unique, no duplicates). I'm having an issue with Bluez though where once a packet is received, Bluez seems to not report any additional packets from the device for the next approximately 11 seconds (very occasionally the interval is shorter). This is with the bluetoothctl line command tool as well as my own c++ application (based off the bluez client/main.c example). In both cases before starting a scan I clear the scan filter, set transport to le, and set duplicate-data reporting on. Conversely, when running hcitool scan I see all the packets from the sensor (it even seems to be reporting all 3 copies broadcast on the different advertisement channels). So my question is, is there a way to get those missing advertisements through the dbus api, possibly some additional setting somewhere? If not, is the hci api okay to use from c++ and should it do the trick? Any help appreciated, thanks!

Edited per Alex's questions -

Have you tried downloading the latest bluez (5.53) https://git.kernel.org/pub/scm/bluetooth/bluez.git ?

Not yet, just wanted to check and see if this might be something known beforehand.

Are you using hcitool scan or sudo hcitool lescan? If you are running hcitool scan, you are picking up bluetooth classic (not low energy packets). hcitool is a deprecated tool. I've found that sudo hcitool lescan only works with BLE 4.x controllers. The function fails on 5.x controller.

hcitool lescan (under root), and yes, the hardware is a Pi Zero/W and a P3 so BLE 4.x controllers (I assume)

Have you tried running sudo btmon to see all of the HCI communication during scanning?

I have but can't remember exactly what I saw other than it didn't contradict anything else, i.e. missing packets w/ dbus api vs hci

Can you provide code for your use of bluetoothctl, ie:

$bluetoothctl
[bluetooth]# menu scan
[bluetooth]# clear
[bluetooth]# transport le
[bluetooth]# duplicated-data on
[bluetooth]# back
[bluetooth]# scan on

always exactly as you've noted...

Could you also provide the results of hciconfig -a

--- Results (P Zero) -

hci0:   Type: Primary  Bus: UART
        BD Address: B8:27:EB:79:2E:3F  ACL MTU: 1021:8  SCO MTU: 64:1
        UP RUNNING
        RX bytes:55476 acl:126 sco:0 events:2012 errors:0
        TX bytes:6956 acl:114 sco:0 commands:444 errors:0
        Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87
        Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
        Link policy: RSWITCH SNIFF
        Link mode: SLAVE ACCEPT
        Name: 'HubPi01'
        Class: 0x000000
        Service Classes: Unspecified
        Device Class: Miscellaneous,
        HCI Version: 4.1 (0x7)  Revision: 0x168
        LMP Version: 4.1 (0x7)  Subversion: 0x2209
        Manufacturer: Broadcom Corporation (15)

--- Results (P3) -

hci0:   Type: Primary  Bus: UART
        BD Address: B8:27:EB:2B:A2:A3  ACL MTU: 1021:8  SCO MTU: 64:1
        UP RUNNING
        RX bytes:10995 acl:0 sco:0 events:390 errors:0
        TX bytes:2145 acl:0 sco:0 commands:91 errors:0
        Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87
        Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
        Link policy: RSWITCH SNIFF
        Link mode: SLAVE ACCEPT
        Name: 'HubPi02'
        Class: 0x000000
        Service Classes: Unspecified
        Device Class: Miscellaneous,
        HCI Version: 4.1 (0x7)  Revision: 0x168
        LMP Version: 4.1 (0x7)  Subversion: 0x2209
        Manufacturer: Broadcom Corporation (15)

Below is a scan covering about 20 seconds (editing out all unrelated packets),
where I'm pressing down the button on the sensor about every 2 seconds and then
holding it down for another 2 seconds before letting it up. The first chunk
is from bluetoothctl, the second from "hcidump --raw" (on a second raspberry pi). The first four bytes
in the bluetoothctl packet data is a little endian packet seq number
incremented by the sensor for each new packet. The next byte indicates a
button up/down action. You can see bluetoothctl reported packets numbered 05df,
05e5, 05e9. In the raw dump the seq number is at the end of the top line. There
you can see all packets are in order, reported 1 to 3 times (I assume it is
reporting all advertising channels it catches). All packets are present 05df to
05e9 in the hcidump scan. Lastly is the output from "hcitool lescan --duplicates",
which I'm not really sure how it maps...

------ bluetoothctl
                                .
[NEW] Device E2:15:00:01:73:96 E2-15-00-01-73-96

[CHG] Device E2:15:00:01:73:96 RSSI: -46
[CHG] Device E2:15:00:01:73:96 ManufacturerData Key: 0x03da
[CHG] Device E2:15:00:01:73:96 ManufacturerData Value:
  df 05 00 00 10 a1 ac 8a b4                       .........

[CHG] Device E2:15:00:01:73:96 RSSI: -45
[CHG] Device E2:15:00:01:73:96 ManufacturerData Key: 0x03da
[CHG] Device E2:15:00:01:73:96 ManufacturerData Value:
  e5 05 00 00 10 e7 4f 67 6e                       ......Ogn
                                             .
[CHG] Device E2:15:00:01:73:96 RSSI: -65
[CHG] Device E2:15:00:01:73:96 ManufacturerData Key: 0x03da
[CHG] Device E2:15:00:01:73:96 ManufacturerData Value:
  e9 05 00 00 10 f4 f9 f8 7d                       ........}

---------- hcidump --raw

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 DF 05
  00 00 10 A1 AC 8A B4 C3
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 DF 05
  00 00 10 A1 AC 8A B4 BE

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E0 05
  00 00 11 11 0F 3E 24 B6

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E1 05
  00 00 10 F7 68 07 50 BE
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E1 05
  00 00 10 F7 68 07 50 CF
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E1 05
  00 00 10 F7 68 07 50 BA

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E2 05
  00 00 11 1D 18 A8 2A BF
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E2 05
  00 00 11 1D 18 A8 2A C0
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E2 05
  00 00 11 1D 18 A8 2A B8

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E3 05
  00 00 10 E2 29 C7 F7 BB

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E4 05
  00 00 11 57 F0 5C 76 BD
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E4 05
  00 00 11 57 F0 5C 76 C1

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E5 05
  00 00 10 E7 4F 67 6E CA

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E6 05
  00 00 11 77 63 92 CE C0
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E6 05
  00 00 11 77 63 92 CE BA
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E6 05
  00 00 11 77 63 92 CE BE

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E7 05
  00 00 10 2D 52 48 C2 BD

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E8 05
  00 00 11 EE 32 20 9D BD
> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E8 05
  00 00 11 EE 32 20 9D C1

> 04 3E 19 02 01 03 01 96 73 01 00 15 E2 0D 0C FF DA 03 E9 05
  00 00 10 F4 F9 F8 7D BC

------- hcitool lescan --duplicates

E2:15:00:01:73:96 (unknown)
E2:15:00:01:73:96 (unknown)
E2:15:00:01:73:96 (unknown)

E2:15:00:01:73:96 (unknown)

E2:15:00:01:73:96 (unknown)
E2:15:00:01:73:96 (unknown)

E2:15:00:01:73:96 (unknown)

Body:
Have you tried downloading the latest bluez (5.53) https://git.kernel.org/pub/scm/bluetooth/bluez.git ?

Are you using hcitool scan or sudo hcitool lescan? If you are running hcitool scan, you are picking up bluetooth classic (not low energy packets). hcitool is a deprecated tool. I've found that sudo hcitool lescan only works with BLE 4.x controllers. The function fails on 5.x controller.

Have you tried running sudo btmon to see all of the HCI communication during scanning?

Can you provide code for your use of bluetoothctl, ie:

$bluetoothctl
[bluetooth]# menu scan
[bluetooth]# clear
[bluetooth]# transport le
[bluetooth]# duplicated-data on
[bluetooth]# back
[bluetooth]# scan on

Could you also provide the results of hciconfig -a


问:
Add variable in XPath in Python
While doing automation, I have to check that email which I am entering is correct one or not. Unfortunately, while creating XPath, UIAutomator is showing me the text of my email address. I want to make XPath dynamic, so, that every time, I use that XPath, It gets the text.
Let us suppose:

```<code>email = 'testqatp@gmail.com'
</code>```

and XPath is:

```<code>[@text='email']
</code>```

How is that gonna work?

答:
The Xpath language normally lets you define variables in the expression's static context (this has been a thing since XPath 1.0), which some xpath libraries support:

```<code>>>> expr = "//*[local-name() = $name]"

>>> print(root.xpath(expr, name = "foo")[0].tag)
foo

>>> print(root.xpath(expr, name = "bar")[0].tag)
bar
</code>```

(this is the lxml python library, based on libxml2, which only supports XPath 1.0)

Unfortunately, Selenium's use of XPath only goes as far as the browser's internal XPath engine does, and unfortunately, the DOM API for XPath does not expose these functionalities. You'll have to stick with the old string concatenation trick and remembering to escape all those variables to make sure they don't break your xpath expression.

ContentLicense: CC BY-SA 3.0

Title: Add variable in XPath in Python

Body:
While doing automation, I have to check that email which I am entering is correct one or not. Unfortunately, while creating XPath, UIAutomator is showing me the text of my email address. I want to make XPath dynamic, so, that every time, I use that XPath, It gets the text.
Let us suppose:

email = 'testqatp@gmail.com'

and XPath is:

[@text='email']

How is that gonna work?

Body:
The Xpath language normally lets you define variables in the expression's static context (this has been a thing since XPath 1.0), which some xpath libraries support:

>>> expr = "//*[local-name() = $name]"

>>> print(root.xpath(expr, name = "foo")[0].tag)
foo

>>> print(root.xpath(expr, name = "bar")[0].tag)
bar

(this is the lxml python library, based on libxml2, which only supports XPath 1.0)

Unfortunately, Selenium's use of XPath only goes as far as the browser's internal XPath engine does, and unfortunately, the DOM API for XPath does not expose these functionalities. You'll have to stick with the old string concatenation trick and remembering to escape all those variables to make sure they don't break your xpath expression.


问:
How to exclude some data on a SQL query depending on it's different values?
I have the following 2 tables:

```<code>create table Director (

    id_director int,
    name varchar(255),
    primary key (id_director)
);

create table Movies (

    id_movie int,
    id_director int,
    title varchar(255),
    year int,
    primary key (id_movie),
    foreign key (id_director) references Director (id_director)
);
</code>```

Some data has been already inserted on this tables. Imagine the data is:

Table Director

```<code>id_director       name
-------------------------
   1               Charles
   2               Jack
   3               Katia
   4               David
</code>```

Table Movies

```<code>id_movie      id_director     title        year
------------------------------------------------
   1              2            title1      1999
   2              1            title2      2011
   3              1            title3      2019
   4              3            title4      2019
   5              4            title5      1968
   6              3            title6      2020
   7              2            title7      1977
   8              4            title8      2004
   9              1            title9      2020
</code>```

I want to execute a SELECT clause in order to filter the directors that it's first movie its from 2019. Note from the example that only the director with the id_director = 3 meets the requirement as has made 2 films, one on 2019 and the other one on 2020.

How can I do this?

The output I would like to get is:

```<code>id_director          name
------------------------------
    3                Katia
</code>```

I have tried this, but it's obviously wrong because some directors that made films before 2019, have also made films after 2019.

```<code>select director.id_director, director.name from director, movies
where director.id_director = movie.id_director and year = 2019
group by (name);
</code>```

I'm using MySQL and I'm supposing I can do this with an IN / NOT IN subquery (but how)?

答:
dbfiddle</p>

```<code>SELECT id_director, name
FROM Director
WHERE 2019 = (SELECT MIN(year)
              FROM Movies
              WHERE Movies.id_director=Director.id_director);
</code>```

Body:
I have the following 2 tables:

create table Director (

    id_director int,
    name varchar(255),
    primary key (id_director)
);

create table Movies (

    id_movie int,
    id_director int,
    title varchar(255),
    year int,
    primary key (id_movie),
    foreign key (id_director) references Director (id_director)
);

Some data has been already inserted on this tables. Imagine the data is:

Table Director

id_director       name
-------------------------
   1               Charles
   2               Jack
   3               Katia
   4               David

Table Movies

id_movie      id_director     title        year
------------------------------------------------
   1              2            title1      1999
   2              1            title2      2011
   3              1            title3      2019
   4              3            title4      2019
   5              4            title5      1968
   6              3            title6      2020
   7              2            title7      1977
   8              4            title8      2004
   9              1            title9      2020

I want to execute a SELECT clause in order to filter the directors that it's first movie its from 2019. Note from the example that only the director with the id_director = 3 meets the requirement as has made 2 films, one on 2019 and the other one on 2020.

How can I do this?

The output I would like to get is:

id_director          name
------------------------------
    3                Katia

I have tried this, but it's obviously wrong because some directors that made films before 2019, have also made films after 2019.

select director.id_director, director.name from director, movies
where director.id_director = movie.id_director and year = 2019
group by (name);

I'm using MySQL and I'm supposing I can do this with an IN / NOT IN subquery (but how)?

Body:
dbfiddle

SELECT id_director, name
FROM Director
WHERE 2019 = (SELECT MIN(year)
              FROM Movies
              WHERE Movies.id_director=Director.id_director);


问:
random number generator without doing refresh
Hello
I want to create a web page which can continually sending random value to data base without doing refresh .

For example

```<code><html>
  <HEAD>
    <TITLE>HTML Title</TITLE>
  </HEAD>
  <BODY>

    <H3 ALIGN="CENTER">
      Ramdom number from 0 to 10 :
      <FONT COLOR="RED">
        <%= (int) (Math.random() * 10) %>
      </FONT>
    </H3>
    <H4 ALIGN="CENTER">Refresh the page to see if the number changes...</H4>
  </BODY>
</HTML>
</code>```

in which direction i should go either of using applets or something which can easily be adopted . Thanks

答: You could create a div in which is displayed the random value, and modifiy the value in the  div using javascript function.</p>

Body:
Hello
I want to create a web page which can continually sending random value to data base without doing refresh .

For example

    <TITLE>HTML Title</TITLE>

      Ramdom number from 0 to 10 :

        <%= (int) (Math.random() * 10) %>

Refresh the page to see if the number changes...

in which direction i should go either of using applets or something which can easily be adopted . Thanks


问:
How to Connect several Google Spreadsheets tabs to BigQuery
It may seem that Google Spreadsheets only exposes the first tab (you can reorder them though) to BigQuery.

I have several tables, taking data ones from the others making several calculations already, being configured by params, in the same Spreadsheet but different tabs.

How can I read other tabs than the first one from Google Spreadsheets to BigQuery?

答:
You can now specify the sheet and/or range of a Google Sheet in the new BigQuery UI which you would like to use as your federated data source.
To Quote from documentation:

Optionally indicate which sheet and cell range in the Google Sheets
  spreadsheet to create a table from. You can specifiy: [sheet_title]
  for the whole sheet, or
  [sheet_title]![top_left_cell_id]:[bottom_right_cell_id]for a
  rectangular cell range in a sheet, such as "Sheet1!A1:B20". When this
  is not specified, the first sheet in the spreadsheet is used.

or You can use CLI as:

```<code>{   "autodetect": false,   "sourceFormat": "GOOGLE_SHEETS",    "sourceUris": [     "https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxx"   ],   "maxBadRecords": 1,   "googleSheetsOptions":   {     "range": "test_sheet!A1:B20",     "skipLeadingRows": 0   } }
</code>```

Body:
You can now specify the sheet and/or range of a Google Sheet in the new BigQuery UI which you would like to use as your federated data source.
To Quote from documentation:

Optionally indicate which sheet and cell range in the Google Sheets
  spreadsheet to create a table from. You can specifiy: [sheet_title]
  for the whole sheet, or
  [sheet_title]![top_left_cell_id]:[bottom_right_cell_id]for a
  rectangular cell range in a sheet, such as "Sheet1!A1:B20". When this
  is not specified, the first sheet in the spreadsheet is used.

or You can use CLI as:

{   "autodetect": false,   "sourceFormat": "GOOGLE_SHEETS",    "sourceUris": [     "https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxx"   ],   "maxBadRecords": 1,   "googleSheetsOptions":   {     "range": "test_sheet!A1:B20",     "skipLeadingRows": 0   } }


问:
Blocked by CORS policy in Chrome after enabling CORS for Lambda Function?
I've enabled CORS in the console for a Lambda function following these instructions.

The API is also an express server that enables CORS for all methods:

```<code>// Enable CORS for all methods
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
});

</code>```

However the browser is still blocking the request because it is not receiving the Access-Control-Allow-Origin header.  This is the complete message:

home:1 Access to XMLHttpRequest at 'https://szxjza7hz5.execute-api.us-east-1.amazonaws.com/loco/myendpoint' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How do we trouble shoot this?

The testing approach in the instructions provide a curl command like this:

```<code>curl -v -X OPTIONS -H "Access-Control-Request-Method: POST" -H "Origin: http://localhost:4200" https://szxjza7hz5.execute-api.us-east-1.amazonaws.com/loco
</code>```

However this fails due to a missing authentication token:

```<code>* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 403
< content-type: application/json
< content-length: 42
< date: Wed, 19 Feb 2020 01:45:47 GMT
< x-amzn-requestid: a529894d-19ff-4c95-915b-45c4098d30ea
< x-amzn-errortype: MissingAuthenticationTokenException
< x-amz-apigw-id: IHvz3Fp_IAMF43g=
< x-cache: Error from cloudfront
< via: 1.1 58e86c1faaee1b15c90e95d794e240dd.cloudfront.net (CloudFront)
< x-amz-cf-pop: ORD51-C3
< x-amz-cf-id: jyTAo6OUrhUWWVNOSdk6M0384K515YzE0V9Vgg-WhfXXkLDzLofr9Q==
<
* Connection #0 to host szxjza7hz5.execute-api.us-east-1.amazonaws.com left intact
{"message":"Missing Authentication Token"}

</code>```

答:
I made a mistake in running an update to the API.  I thought that if I added another endpoint to the express server amplify push would pick it up and deploy it.

We need to run amplify update API in order to create a new endpoint.  So when I was making the API call against the endpoint I thought was there, it was not passing the preflight check because there was not endpoint ...

Body:
I've enabled CORS in the console for a Lambda function following these instructions.

The API is also an express server that enables CORS for all methods:

// Enable CORS for all methods
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
});

However the browser is still blocking the request because it is not receiving the Access-Control-Allow-Origin header.  This is the complete message:

home:1 Access to XMLHttpRequest at 'https://szxjza7hz5.execute-api.us-east-1.amazonaws.com/loco/myendpoint' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How do we trouble shoot this?

The testing approach in the instructions provide a curl command like this:

curl -v -X OPTIONS -H "Access-Control-Request-Method: POST" -H "Origin: http://localhost:4200" https://szxjza7hz5.execute-api.us-east-1.amazonaws.com/loco

However this fails due to a missing authentication token:

* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 403
< content-type: application/json
< content-length: 42
< date: Wed, 19 Feb 2020 01:45:47 GMT
< x-amzn-requestid: a529894d-19ff-4c95-915b-45c4098d30ea
< x-amzn-errortype: MissingAuthenticationTokenException
< x-amz-apigw-id: IHvz3Fp_IAMF43g=
< x-cache: Error from cloudfront
< via: 1.1 58e86c1faaee1b15c90e95d794e240dd.cloudfront.net (CloudFront)
< x-amz-cf-pop: ORD51-C3
< x-amz-cf-id: jyTAo6OUrhUWWVNOSdk6M0384K515YzE0V9Vgg-WhfXXkLDzLofr9Q==
<
* Connection #0 to host szxjza7hz5.execute-api.us-east-1.amazonaws.com left intact
{"message":"Missing Authentication Token"}


问:
How i can run method from child component vuejs
I have parent and chidl component... I need to run child method, when i click on button in parent.
Example code:

Parent

```<code><template>
 <child-component></child-component>
 <button>Open Modal in child Component (set modal = true in child component)</button>
</template>
</code>```

Child:

```<code><template>
<div v-if="modal">
 <button @click="modal = false">Close</button>
</div>
</template>
<script>
export default {
  data() {
    return {
     modal: false
    }
  }
}
</script>
</code>```

答:
In vue you can pass a function as a prop. So you could add a function to alternate model within your parent component then pass it into your child so it can be used normally. I'll put a simple example below.

small edit, you can bind a class like a hidden/reveal class using the status which is bound to the modal state

```<code>// Html
<div id="app">
     <child v-bind:on-click="toggleModal" v-bind:status="modal" />
</div>

// Parent Component
var sample = new Vue({
     el: '#app',
     data: {
        modal: false
     },
     methods: {
        toggleModal() {
           this.modal = !this.modal
        }
     }
});

// Child component with function prop
Vue.component('child', {
     props: {
        onClick: Function,
        status: Boolean
     }
     template: '<button v-on:click="onClick()">Press Me</div>'
});
</code>```

Body:
I have parent and chidl component... I need to run child method, when i click on button in parent.
Example code:

Parent

<template>
 <child-component></child-component>
 <button>Open Modal in child Component (set modal = true in child component)</button>
</template>

Child:

<template>

 <button @click="modal = false">Close</button>

</template>

Body:
In vue you can pass a function as a prop. So you could add a function to alternate model within your parent component then pass it into your child so it can be used normally. I'll put a simple example below.

small edit, you can bind a class like a hidden/reveal class using the status which is bound to the modal state

// Html
<div id="app">
     <child v-bind:on-click="toggleModal" v-bind:status="modal" />
</div>

// Parent Component
var sample = new Vue({
     el: '#app',
     data: {
        modal: false
     },
     methods: {
        toggleModal() {
           this.modal = !this.modal
        }
     }
});

// Child component with function prop
Vue.component('child', {
     props: {
        onClick: Function,
        status: Boolean
     }
     template: '<button v-on:click="onClick()">Press Me</div>'
});


问:
Whenever gem to trigger Rails' ActiveJob vs rake task to run regularly scheduled task | Rails 5
I'm working on a Rails 5.2 project that requires a scheduled asynchronous task to run nightly. I've been looking at the differences between using the whenever gem to trigger an ActiveJob job, and using whenever to trigger an old-style rake task (/lib/tasks/some_task.rake) - I'm struggling to find much in the way of notable pros and/or cons either way. Taking the two basic example implementations below, what are the differences between the two strategies?

The differences that I can see, are that with ActiveJob, you get the added flexibility of selecting a queue for the job to run in, and triggering callbacks around the job, wheres with the rake task, you're limited to the single thread, and no callbacks are available.

Are there any other differences worth looking at?

ActiveJob

app/jobs/subscription_reminder_job.rb:

class SubscriptionReminderJob < ApplicationJob
  queue_as :default

  def perform
    Subscription.overdue.find_each do |overdue_subscription|
      UserMailer.subscription_reminder(overdue_subscription.user, overdue_subscription).deliver_later

      overdue_subscription.touch(:last_subscription_reminder_sent_at)
    end
  end
end
```

<p><code>config/schedule.rb</code>:</p>

<pre class="lang-rb prettyprint-override"><code>every :day, at: '12:00am' do
  runner "SubscriptionReminderJob.perform"
end
</code>```

Rails Task

lib/tasks/send_subscription_reminders.rake:

task send_subscription_reminders: :environment do
  Subscription.overdue.find_each do |overdue_subscription|
    UserMailer.subscription_reminder(overdue_subscription.user, overdue_subscription).deliver_later

    overdue_subscription.touch(:last_subscription_reminder_sent_at)
  end
end
```

<p><code>config/schedule.rb</code>:</p>

<pre class="lang-rb prettyprint-override"><code>every :day, at: '12:00am' do
  rake "send_subscription_reminders"
end
</code>```

答:
What will peak load look like?

What about average load?

How reliable does it need to be?

Information like that is essential when judging what route to go down.

Answering based on what info is provided so far

You're wanting to send X emails daily, during presumably low usage periods of your system. Based on what you've provided so far this looks to be a simple use case really.

There isn't any major difference between the two approaches you've suggested. Rails is all about convention over configuration. Unless you've a very good reason not to, you should use the ActiveJob framework. It serves as an API for job infrastructure, allowing you to easily swap the queuing backend implementation whenever requirements change.

You've not suggested any requirement which would indicate breaking from convention would be useful here. Keep it simple and leverage what makes Rails so good, it's conventions do a lot of the work for you.

Intro to ActiveJob, snippet below taken from it.

The main point is to ensure that all Rails apps will have a job infrastructure in place. We can then have framework features and other gems build on top of that, without having to worry about API differences between various job runners such as Delayed Job and Resque. Picking your queuing backend becomes more of an operational concern, then. And you'll be able to switch between them without having to rewrite your jobs.

Which queue backend should you use? Start simple with sidekiq and go from there. Build iteratively. If you reach a stage where sidekiq is limiting you, ActiveJob makes switching it for another queue tool easy. Good times!

Body:
I'm working on a Rails 5.2 project that requires a scheduled asynchronous task to run nightly. I've been looking at the differences between using the whenever gem to trigger an ActiveJob job, and using whenever to trigger an old-style rake task (/lib/tasks/some_task.rake) - I'm struggling to find much in the way of notable pros and/or cons either way. Taking the two basic example implementations below, what are the differences between the two strategies?

The differences that I can see, are that with ActiveJob, you get the added flexibility of selecting a queue for the job to run in, and triggering callbacks around the job, wheres with the rake task, you're limited to the single thread, and no callbacks are available.

Are there any other differences worth looking at?

ActiveJob

app/jobs/subscription_reminder_job.rb:

class SubscriptionReminderJob < ApplicationJob
  queue_as :default

  def perform
    Subscription.overdue.find_each do |overdue_subscription|
      UserMailer.subscription_reminder(overdue_subscription.user, overdue_subscription).deliver_later

      overdue_subscription.touch(:last_subscription_reminder_sent_at)
    end
  end
end

config/schedule.rb:

every :day, at: '12:00am' do
  runner "SubscriptionReminderJob.perform"
end

Rails Task

lib/tasks/send_subscription_reminders.rake:

task send_subscription_reminders: :environment do
  Subscription.overdue.find_each do |overdue_subscription|
    UserMailer.subscription_reminder(overdue_subscription.user, overdue_subscription).deliver_later

    overdue_subscription.touch(:last_subscription_reminder_sent_at)
  end
end

config/schedule.rb:

every :day, at: '12:00am' do
  rake "send_subscription_reminders"
end


问:
Dialogflow connect to MQTT broker using Firebase?
I'm trying to use the Cloud Functions for Firebase to make a Dialogflow intent result in an MQTT message being published. I've managed to get the data I needed and all I still am not able to accomplish is:

Establishing a connection to the MQTT broker;

Publishing to said broker.

As the second one requires the former, it is not my concern yet.

The way I see it is: either my code is wrong or MQTT is included in what Firebase calls "external network". And I'm here, mainly, to make sure I don't upgrade to a paid plan for nothing.

index.js:

'use strict';

const functions = require('firebase-functions');
const { WebhookClient, Card, Suggestion } = require('dialogflow-fulfillment');

var mqtt = require('mqtt');

process.env.DEBUG = 'dialogflow:debug';
const HOST = 'broker.mqttdashboard.com';
const PORT = 1883;
const TOPIC = 'topic/voice_recog';

exports.dialogflowFirebaseFulfillment = functions.region('europe-west1').https.onRequest((request, response) => {

  const agent = new WebhookClient({ request, response });

  try {

    function publishParameter(agent) {

      let message = agent.parameters.param_test;

      return publishToMqtt(message).then((output) => {
        agent.add(output);
      }).catch(error => {
        agent.add('error from publishToMqtt');
      });
    }

    let intentMap = new Map();
    intentMap.set('Repeat parameter', publishParameter);
    agent.handleRequest(intentMap);

  }

  catch (err) {
    console.error(err);
    agent.add(err.message);
    agent.send_();
  }
});

function publishToMqtt(message) {

   console.log("------------------------------");
   console.log("Topic: \""+TOPIC+"\"");
   console.log("Message: \""+message+"\"");
   console.log("------------------------------");

   return new Promise((resolve, reject) => {

      var options = {
         port: PORT,
         host: HOST,
         clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
         keepalive: 60,
         reconnectPeriod: 1000,
         protocolId: 'MQIsdp',
         protocolVersion: 3,
         clean: true,
         encoding: 'utf8'
      };

      var client = mqtt.connect("mqtt://"+HOST, {port: PORT});

      // is not executed
      client.on('connect', function () {
         console.log('client connected');
      });

      // is not executed
      client.publish(TOPIC, message, {}, function (err) {
         console.log("Tried publishing \""+message+"\" to \""+TOPIC+"\".");
         if (err) {
            console.log("But the future refused to change:" + err);
            reject();
         }
         else {
            resolve(message);
            client.end();
            clearTimeout(noResp);
         }
      });

      let noResp = setTimeout(() => {
         console.log("No connection"); // always gives this result
         reject();
         client.end();
      }, 5000);

   });
}
```

<p><code>package.json</code>:</p>

```{
  "name": "assistant-to-mqtt",
  "description": "publishes intent parameter to MQTT broker",
  "engines": {
    "node": "8"
  },
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "firebase serve --only functions:publish_mqtt",
    "deploy": "firebase deploy --only functions:publish_mqtt"
  },
  "dependencies": {
    "actions-on-google": "^2.1.3",
    "dialogflow-fulfillment": "^0.4.1",
    "firebase-admin": "^5.12.1",
    "firebase-functions": "^2.2.1",
    "mqtt": "^2.13.0"
  }
}
```

All help is appreciated. Thank you.

EDIT: The log.

答: You are actually using a MQTT Broker which is treated as an external access URL by Firebase. Try enabling the billing as described here.</p>

Body:
I'm trying to use the Cloud Functions for Firebase to make a Dialogflow intent result in an MQTT message being published. I've managed to get the data I needed and all I still am not able to accomplish is:

Establishing a connection to the MQTT broker;

Publishing to said broker.

As the second one requires the former, it is not my concern yet.

The way I see it is: either my code is wrong or MQTT is included in what Firebase calls "external network". And I'm here, mainly, to make sure I don't upgrade to a paid plan for nothing.

index.js:

'use strict';

const functions = require('firebase-functions');
const { WebhookClient, Card, Suggestion } = require('dialogflow-fulfillment');

var mqtt = require('mqtt');

process.env.DEBUG = 'dialogflow:debug';
const HOST = 'broker.mqttdashboard.com';
const PORT = 1883;
const TOPIC = 'topic/voice_recog';

exports.dialogflowFirebaseFulfillment = functions.region('europe-west1').https.onRequest((request, response) => {

  const agent = new WebhookClient({ request, response });

  try {

    function publishParameter(agent) {

      let message = agent.parameters.param_test;

      return publishToMqtt(message).then((output) => {
        agent.add(output);
      }).catch(error => {
        agent.add('error from publishToMqtt');
      });
    }

    let intentMap = new Map();
    intentMap.set('Repeat parameter', publishParameter);
    agent.handleRequest(intentMap);

  }

  catch (err) {
    console.error(err);
    agent.add(err.message);
    agent.send_();
  }
});

function publishToMqtt(message) {

   console.log("------------------------------");
   console.log("Topic: \""+TOPIC+"\"");
   console.log("Message: \""+message+"\"");
   console.log("------------------------------");

   return new Promise((resolve, reject) => {

      var options = {
         port: PORT,
         host: HOST,
         clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
         keepalive: 60,
         reconnectPeriod: 1000,
         protocolId: 'MQIsdp',
         protocolVersion: 3,
         clean: true,
         encoding: 'utf8'
      };

      var client = mqtt.connect("mqtt://"+HOST, {port: PORT});

      // is not executed
      client.on('connect', function () {
         console.log('client connected');
      });

      // is not executed
      client.publish(TOPIC, message, {}, function (err) {
         console.log("Tried publishing \""+message+"\" to \""+TOPIC+"\".");
         if (err) {
            console.log("But the future refused to change:" + err);
            reject();
         }
         else {
            resolve(message);
            client.end();
            clearTimeout(noResp);
         }
      });

      let noResp = setTimeout(() => {
         console.log("No connection"); // always gives this result
         reject();
         client.end();
      }, 5000);

   });
}

package.json:

{
  "name": "assistant-to-mqtt",
  "description": "publishes intent parameter to MQTT broker",
  "engines": {
    "node": "8"
  },
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "firebase serve --only functions:publish_mqtt",
    "deploy": "firebase deploy --only functions:publish_mqtt"
  },
  "dependencies": {
    "actions-on-google": "^2.1.3",
    "dialogflow-fulfillment": "^0.4.1",
    "firebase-admin": "^5.12.1",
    "firebase-functions": "^2.2.1",
    "mqtt": "^2.13.0"
  }
}

All help is appreciated. Thank you.

EDIT: The log.


问:
insertBefore - if element doesnt exists
if the index is larger than the actual number of rows nothing is i appended?</p>

```<code>var elm = $('tr', tbl).eq(index);
if(elm){
    row.insertBefore(elm);
}
else{
    row.appendTo(tbl);
}
</code>```

答:
```<code>if($('tr', tbl).length > index){
    row.insertBefore($('tr', tbl).eq(index));
}
else{
    row.appendTo(tbl);
}
</code>```

Title: insertBefore - if element doesnt exists

Body:
if the index is larger than the actual number of rows nothing is i appended?

var elm = $('tr', tbl).eq(index);
if(elm){
    row.insertBefore(elm);
}
else{
    row.appendTo(tbl);
}


Title: PI nth digit after decimal

Body:
I want to make a program which will return a nth number of digits after decimal in PI number.
It works good as long as I don't put n higher than 50. Can I fix it or Python don't allow that?

Here's my code:

pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428

def nth_pi_digit(n=input("How many digits after decimal you would like to see?(PI number):  ")):
    try:
        n = int(n)
        if n <= 204:
            return print(format(pi, f".{n}f"))
        else:
            print("Sorry, we have pi with 204 digits after decimal, so we'll print that")
            return print(format(pi, ".204f"))
    except:
        print("You need to put a integer digit")

nth_pi_digit()

Body:
Instantiate PI as a string object:

pi = '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428'

And then you can perform slicing to show as many decimals you want:

n = 10    # 10 decimals
print(pi[:2+n])


Title: PI nth digit after decimal

Body:
The float datatype has a limit on how precise you can get. 50 digits is around that.

I recommend using a Decimal instead to represent numbers with such high precision:

>>> from decimal import Decimal
>>> d = Decimal('3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428')
>>> format(d, ".50f")
'3.14159265358979323846264338327950288419716939937511'
>>> format(d, ".204f")
'3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102709385211055596446229489549303819644280'

This way you can do math on it without losing precision, which "treating it as a string" doesn't let you do.


问:
Get index of searchresult in array
I have the following code:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
     //HERE I NEED TO GET THE INDEX OF MEMBER_DATA_LIST[?]
     //EXAMPLE: if (exists(member_data_list, "franz")) => RESULT => 2 (MEMBER_DATA_LIST[2])
     console.log("NAME IS IN ARRAY AT INDEX " + "?");
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}```

How to get the index of the name in this array?

答:
You could also use Array.prototype.findIndex() (not working on Internet Explorer)

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
     var index = findIndex(member_data_list, 'franz');
     console.log("NAME IS IN ARRAY AT INDEX " + index);
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}

function findIndex(arr, search) {
   return arr.findIndex(row => row.includes(search));
}```

Title: Get index of searchresult in array

Body:
I have the following code:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
     //HERE I NEED TO GET THE INDEX OF MEMBER_DATA_LIST[?]
     //EXAMPLE: if (exists(member_data_list, "franz")) => RESULT => 2 (MEMBER_DATA_LIST[2])
     console.log("NAME IS IN ARRAY AT INDEX " + "?");
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}

How to get the index of the name in this array?


答:
You can achieve this via different implementations. The most common one is via emit (another alternative is via dispatching actions if you are using the Redux pattern)

First, you want to catch the even on the parent component and emit an event. So this should be your template.

```<code><template>
 <child-component></child-component>
 <button @click="click">Open Modal in child Component (set modal = true in child component)</button>
</template>
</code>```

Then you have to emit an event (from the parent component) on the function called when a click was made.
Something like:

```<code>click: function() {
  this.$emit('update');
}
</code>```

Lastly, your child component needs to "hear" that event. You can achieve that with something like that on the created function of the child component:

```<code>this.$parent.$on('update', this.updateModal);
</code>```

this.updateModal is a function on your child component which just flips the value of the boolean.

Title: How i can run method from child component vuejs

Body:
You can achieve this via different implementations. The most common one is via emit (another alternative is via dispatching actions if you are using the Redux pattern)

First, you want to catch the even on the parent component and emit an event. So this should be your template.

<template>
 <child-component></child-component>
 <button @click="click">Open Modal in child Component (set modal = true in child component)</button>
</template>

Then you have to emit an event (from the parent component) on the function called when a click was made.
Something like:

click: function() {
  this.$emit('update');
}

Lastly, your child component needs to "hear" that event. You can achieve that with something like that on the created function of the child component:

this.$parent.$on('update', this.updateModal);

this.updateModal is a function on your child component which just flips the value of the boolean.


问:
ASP.NET Core Web App DI Error - Some services are not able to be constructed (Error while validating the service descriptor
I am creating a ASP.NET Core web application. I am using a Repository through a library project. I reference it in the web application project.

The repository interface is as below:

```<code>public interface IPushNotificationRepository
{
    IQueryable<PushNotification> Notifications
    {
        get;
    }
    IQueryable<Client> Clients
    {
        get;
    }

    void Add(PushNotification notification);
    void Add(Client client);
    void AddRange(IList<PushNotification> notifications);
    bool AddIfNotAlreadySent(PushNotification notification);
    void UpdateDelivery(PushNotification notification);
    bool CheckIfClientExists(string client);
    Client FindClient(int? id);
    void Update(Client client);
    void Delete(Client client);
}
</code>```

Within the repository I inject the db context

```<code>    public class PushNotificationRepository : IPushNotificationRepository
    {
        private readonly PushNotificationsContext _context;

        public PushNotificationRepository(PushNotificationsContext context)
        {
            _context = context;
        }
}
</code>```

The configure services of the start up class is as below:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddSingleton<IPushNotificationRepository, PushNotificationRepository>();
    services.AddDbContextPool<PushNotificationsContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("PushNotificationsConnection")));
}
</code>```

In the controller class I consume the repository:

```<code>    public class ClientsController : Controller
    {
        //private readonly PushNotificationsContext _context;
        private readonly IPushNotificationRepository _pushNotificationRepository;

        public ClientsController(IPushNotificationRepository pushNotificationRepository)
        {
            _pushNotificationRepository = pushNotificationRepository;
        }
}
</code>```

The repository classes are in a separate library project which is referenced by the web application project. The error I receive is:

System.AggregateException: 'Some services are not able to be
  constructed (Error while validating the service descriptor
  'ServiceType:
  Services.Messaging.Data.Abstract.IPushNotificationRepository Lifetime:
  Singleton ImplementationType:
  Services.Messaging.Data.PushNotificationRepository': Cannot consume
  scoped service 'Services.Messaging.Data.PushNotificationsContext' from
  singleton
  'Services.Messaging.Data.Abstract.IPushNotificationRepository'.)'

Would really appreciate some advise on this

答:
A singleton cannot reference a Scoped instance. The error message is clear.

Cannot consume scoped service
  'Services.Messaging.Data.PushNotificationsContext' from singleton

PushNotificationsContext is considered as a scoped service. You should almost never consume scoped service or transient service from a singleton. You should also avoid consuming transient service from a scoped service. Consuming scoped services it's a good practice to inject what you need, it gets cleaned up after the request automatically.

Either

services.AddTransient < IPushNotificationRepository, PushNotificationRepository>();

or

services.AddScoped< IPushNotificationRepository, PushNotificationRepository>();

will work fine, but check your design. Maybe this is not the behaviour you are looking for.

Body:
I am creating a ASP.NET Core web application. I am using a Repository through a library project. I reference it in the web application project.

The repository interface is as below:

public interface IPushNotificationRepository
{
    IQueryable<PushNotification> Notifications
    {
        get;
    }
    IQueryable<Client> Clients
    {
        get;
    }

    void Add(PushNotification notification);
    void Add(Client client);
    void AddRange(IList<PushNotification> notifications);
    bool AddIfNotAlreadySent(PushNotification notification);
    void UpdateDelivery(PushNotification notification);
    bool CheckIfClientExists(string client);
    Client FindClient(int? id);
    void Update(Client client);
    void Delete(Client client);
}

Within the repository I inject the db context

    public class PushNotificationRepository : IPushNotificationRepository
    {
        private readonly PushNotificationsContext _context;

        public PushNotificationRepository(PushNotificationsContext context)
        {
            _context = context;
        }
}

The configure services of the start up class is as below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddSingleton<IPushNotificationRepository, PushNotificationRepository>();
    services.AddDbContextPool<PushNotificationsContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("PushNotificationsConnection")));
}

In the controller class I consume the repository:

    public class ClientsController : Controller
    {
        //private readonly PushNotificationsContext _context;
        private readonly IPushNotificationRepository _pushNotificationRepository;

        public ClientsController(IPushNotificationRepository pushNotificationRepository)
        {
            _pushNotificationRepository = pushNotificationRepository;
        }
}

The repository classes are in a separate library project which is referenced by the web application project. The error I receive is:

System.AggregateException: 'Some services are not able to be
  constructed (Error while validating the service descriptor
  'ServiceType:
  Services.Messaging.Data.Abstract.IPushNotificationRepository Lifetime:
  Singleton ImplementationType:
  Services.Messaging.Data.PushNotificationRepository': Cannot consume
  scoped service 'Services.Messaging.Data.PushNotificationsContext' from
  singleton
  'Services.Messaging.Data.Abstract.IPushNotificationRepository'.)'

Would really appreciate some advise on this


问:
Dynamic named field names
I want to create a JSON response where the field name of the parent object has a dynamic name.

It is better explained with an example.

Right now, my response looks like this:

```<code>{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
</code>```

For that I created a struct -> populate it -> return it.

My struct looks like this:

```<code>type Placeholder struct {
    userId    int    `json:"userId"`
    id        int    `json:"id"`
    title     string `json:"title"`
    completed bool   `json:"completed"`
}
//...
res := Placeholder{
  userId: 1,
  id: 1,
  title: "delectus aut autem",
  completed: false,
}
</code>```

Now I want to use the userId as the field name. So I want to have this result:

```<code>{
  "1": {
     "id": 1,
     "title": "delectus aut autem",
     "completed": false
  }
}
</code>```

Is there any possibility to do this in Go?

答:
You can embed a struct with json:",inline".

NOTE: do not omit errors in real code!

type Placeholder struct {
    ID        int    `json:"id"`
    Title     string `json:"title"`
    Completed bool   `json:"completed"`
}

type PlaceholderWithUserID struct {
    UserID      int `json:"userId"`
    Placeholder `json:",inline"`
}

type PlaceholderMap map[int]Placeholder

func main() {
    var res PlaceholderWithUserID
    _ = json.Unmarshal([]byte(`{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}`), &res)
    mapping := PlaceholderMap{
        res.UserID: res.Placeholder,
    }
    out, _ := json.Marshal(mapping)
    fmt.Println(string(out))
}
```

Playgorund

Title: Dynamic named field names

Body:
I want to create a JSON response where the field name of the parent object has a dynamic name.

It is better explained with an example.

Right now, my response looks like this:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

For that I created a struct -> populate it -> return it.

My struct looks like this:

type Placeholder struct {
    userId    int    `json:"userId"`
    id        int    `json:"id"`
    title     string `json:"title"`
    completed bool   `json:"completed"`
}
//...
res := Placeholder{
  userId: 1,
  id: 1,
  title: "delectus aut autem",
  completed: false,
}

Now I want to use the userId as the field name. So I want to have this result:

{
  "1": {
     "id": 1,
     "title": "delectus aut autem",
     "completed": false
  }
}

Is there any possibility to do this in Go?

Body:
You can embed a struct with json:",inline".

NOTE: do not omit errors in real code!

type Placeholder struct {
    ID        int    `json:"id"`
    Title     string `json:"title"`
    Completed bool   `json:"completed"`
}

type PlaceholderWithUserID struct {
    UserID      int `json:"userId"`
    Placeholder `json:",inline"`
}

type PlaceholderMap map[int]Placeholder

func main() {
    var res PlaceholderWithUserID
    _ = json.Unmarshal([]byte(`{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}`), &res)
    mapping := PlaceholderMap{
        res.UserID: res.Placeholder,
    }
    out, _ := json.Marshal(mapping)
    fmt.Println(string(out))
}

Playgorund


问:
Why "Confirm your choices" pops up twice using cordova google-plus plugin?
```<code>let params;
    if(this.platform.is('android')){
      params = {
        'webClientId': '77852...client id stuff..',
        'offline': true
      }
    }
    else{
      params={}
    }

this.googlePlus.login(params)
    .then(res => {
      console.log(res);
}
)
.catch(err => console.error(err));
</code>```

this is the whole code I am using, If I call this code the following happens:

Firstly I have to decide which google Account I want to use, next it asks me to confirm my choice and press allow, after I pressed the button, the same menu pops up again and only after a second "allow" click I get the iDToken.

Why does the same menu pop up twice with the same content?

答:
if you are just using for login (doesnt required any serverAuthCode ) then pass 'offline': false

let params;
      if(this.platform.is('android')){
        params = {
          'webClientId': '77852...client id stuff..',
          'offline': false
        }
      }
      else{
        params={}
      }

this.googlePlus.login(params)
      .then(res => {
        console.log(res); } ) .catch(err => console.error(err));

Body:
let params;
    if(this.platform.is('android')){
      params = {
        'webClientId': '77852...client id stuff..',
        'offline': true
      }
    }
    else{
      params={}
    }

this.googlePlus.login(params)
    .then(res => {
      console.log(res);
}
)
.catch(err => console.error(err));

this is the whole code I am using, If I call this code the following happens:

Firstly I have to decide which google Account I want to use, next it asks me to confirm my choice and press allow, after I pressed the button, the same menu pops up again and only after a second "allow" click I get the iDToken.

Why does the same menu pop up twice with the same content?


问:
Summing up selected row duplicates
I have data that looks like this.

I wish to sum up the value column for rows that have the same name, time, and site. In this case, rows 3 and 4 would be summed, and rows 5 and 7 would be summed up.

I wish for the resulting data frame to look like this.

example data:

```<code>    name = c('a', 'a', 'b' , 'b', 'c', 'c', 'c', 'd')
    time = c(1,2,1,1,3,3,3,4)
    site = c('A', 'A', 'A', 'A','B', 'D','B', 'E')
    value = c(5,8,1,0,7,0,8,10)

mock = data.frame(name, time,site,value)
</code>```

答:
Here's a tidyverse answer:</p>

```<code>mock <- mock %>%
  group_by(name, time, site) %>%
  summarize(value = sum(value))
</code>```

```<code>  name   time site  value
  <fct> <dbl> <fct> <dbl>
1 a         1 A         5
2 a         2 A         8
3 b         1 A         1
4 c         3 B        15
5 c         3 D         0
6 d         4 E        10
</code>```

Title: Summing up selected row duplicates

Body:
I have data that looks like this.

I wish to sum up the value column for rows that have the same name, time, and site. In this case, rows 3 and 4 would be summed, and rows 5 and 7 would be summed up.

I wish for the resulting data frame to look like this.

example data:

    name = c('a', 'a', 'b' , 'b', 'c', 'c', 'c', 'd')
    time = c(1,2,1,1,3,3,3,4)
    site = c('A', 'A', 'A', 'A','B', 'D','B', 'E')
    value = c(5,8,1,0,7,0,8,10)

mock = data.frame(name, time,site,value)

Body:
Here's a tidyverse answer:

mock <- mock %>%
  group_by(name, time, site) %>%
  summarize(value = sum(value))

  name   time site  value
  <fct> <dbl> <fct> <dbl>
1 a         1 A         5
2 a         2 A         8
3 b         1 A         1
4 c         3 B        15
5 c         3 D         0
6 d         4 E        10


问:
lock keyword in C#
I understand the main function of the lock key word from MSDN

lock Statement (C# Reference)

The lock keyword marks a statement
  block as a critical section by
  obtaining the mutual-exclusion lock
  for a given object, executing a
  statement, and then releasing the
  lock.

When should the lock be used?

For instance it makes sense with multi-threaded applications because it protects the data.  But is it necessary when the application does not spin off any other threads?

Is there performance issues with using lock?

I have just inherited an application that is using lock everywhere, and it is single threaded and I want to know should I leave them in, are they even necessary?

Please note this is more of a general knowledge question, the application speed is fine, I want to know if that is a good design pattern to follow in the future or should this be avoided unless absolutely needed.

答:
All the answers here seem right: locks' usefulness is to block threads from acessing locked code concurrently. However, there are many subtleties in this field, one of which is that locked blocks of code are automatically marked as critical regions by the Common Language Runtime.

The effect of code being marked as critical is that, if the entire region cannot be entirely executed, the runtime may consider that your entire Application Domain is potentially jeopardized and, therefore, unload it from memory. To quote MSDN:

For example, consider a task that attempts to allocate memory while holding a lock. If the memory allocation fails, aborting the current task is not sufficient to ensure stability of the AppDomain, because there can be other tasks in the domain waiting for the same lock. If the current task is terminated, other tasks could be deadlocked.

Therefore, even though your application is single-threaded, this may be a hazard for you. Consider that one method in a locked block throws an exception that is eventually not handled within the block. Even if the exception is dealt as it bubbles up through the call stack, your critical region of code didn't finish normally. And who knows how the CLR will react?

For more info, read this article on the perils of Thread.Abort().

ContentLicense: CC BY-SA 2.5

Title: lock keyword in C#

LastEditorDisplayName: Chris

OwnerDisplayName: André Neves

LastEditorDisplayName: André Neves


问:
slice(which.max()) with condition
I have the following dataset:

```<code>ID, diff

1  -40

1  -21

1  -5

1  1

1  6

1  7

...
</code>```

ID variable has values 1,2,3,4,5,... while diff is a numeric variable. Now, from the dataset, for each ID I want to extract the row with a diff that is closest to zero AND is negative. So, I want the row with the highest negative value of diff. In the dataset above, for ID 1 I want to extract 3 rows with values (1 -5).

The following code can extract rows where the absolute value is closest to 0:

```<code>library(dplyr)

dataset22 = dataset1 %>%  group_by(ID) %>% slice(which.min(abs(diff)))
</code>```

How can I extract the row with a negative number that is closest to zero?

Thanks in advance!

答:
This works:</p>

```<code>library(dplyr)

df <- data.frame(ID = c(1, 1, 1, 1, 1, 1),
                 diff = c(-40, -21, -5, 1, 6, 7))

df %>%
  group_by(ID) %>%
  filter(diff < 0) %>%
  summarise(min_negative_diff = max(diff))

#> # A tibble: 1 x 2
#>      ID min_negative_diff
#>   <dbl>             <dbl>
#> 1     1                -5
</code>```

Title: slice(which.max()) with condition

Body:
I have the following dataset:

ID, diff

1  -40

1  -21

1  -5

1  1

1  6

1  7

...

ID variable has values 1,2,3,4,5,... while diff is a numeric variable. Now, from the dataset, for each ID I want to extract the row with a diff that is closest to zero AND is negative. So, I want the row with the highest negative value of diff. In the dataset above, for ID 1 I want to extract 3 rows with values (1 -5).

The following code can extract rows where the absolute value is closest to 0:

library(dplyr)

dataset22 = dataset1 %>%  group_by(ID) %>% slice(which.min(abs(diff)))

How can I extract the row with a negative number that is closest to zero?

Thanks in advance!

Body:
This works:

library(dplyr)

df <- data.frame(ID = c(1, 1, 1, 1, 1, 1),
                 diff = c(-40, -21, -5, 1, 6, 7))

df %>%
  group_by(ID) %>%
  filter(diff < 0) %>%
  summarise(min_negative_diff = max(diff))

#> # A tibble: 1 x 2
#>      ID min_negative_diff
#>   <dbl>             <dbl>
#> 1     1                -5


问:
How do I unit test "HttpContext.Current.Request.LogonUserIdentity.Name"?
I am unable to unit test one of my functions that contains HttpContext.Current.Request.LogonUserIdentity.Name

The error that I get is because LogonUserIdentity is null.

I added this in my unit test in order to set a value for HttpContext.Current because that was also null:

```<code>HttpContext.Current = new HttpContext(
            new HttpRequest("", "http://localhost:8609", ""),
            new HttpResponse(new StringWriter())
            );
</code>```

How can I assign a value to LogonUserIdentity so that I can test my function?

答:
Not really the best mock, but sometimes you're trapped.

In this solution you must handle locally logged user (johndoe) on controller and/or
in your db.

But works.

```<code>            var mockRequest = new HttpRequest("", "http://tempuri.org", "");
            HttpContext.Current = new HttpContext(
                mockRequest,
                new HttpResponse(new StringWriter())
            );

            mockRequest.GetType().InvokeMember(
                "_logonUserIdentity",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetField | System.Reflection.BindingFlags.Instance,
                System.Type.DefaultBinder,
                mockRequest,
                new object[] { WindowsIdentity.GetCurrent() }
            );
</code>```

Body:
I am unable to unit test one of my functions that contains HttpContext.Current.Request.LogonUserIdentity.Name

The error that I get is because LogonUserIdentity is null.

I added this in my unit test in order to set a value for HttpContext.Current because that was also null:

HttpContext.Current = new HttpContext(
            new HttpRequest("", "http://localhost:8609", ""),
            new HttpResponse(new StringWriter())
            );

How can I assign a value to LogonUserIdentity so that I can test my function?

Body:
Not really the best mock, but sometimes you're trapped.

In this solution you must handle locally logged user (johndoe) on controller and/or
in your db.

But works.

            var mockRequest = new HttpRequest("", "http://tempuri.org", "");
            HttpContext.Current = new HttpContext(
                mockRequest,
                new HttpResponse(new StringWriter())
            );

            mockRequest.GetType().InvokeMember(
                "_logonUserIdentity",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetField | System.Reflection.BindingFlags.Instance,
                System.Type.DefaultBinder,
                mockRequest,
                new object[] { WindowsIdentity.GetCurrent() }
            );


问:
Disable Spartacus component styles
The documentation states that that component styles can be skipped

Skipping Specific Component Styles
  Component styles are optional, because they are pulled in from the style library. Therefore, you might want to disable some standard component styles entirely. To disable standard component styles, you can add the component selectors to the $skipComponentStyles list. The following is an example that demonstrates skipping two standard components from the style library:

$skipComponentStyles: (cx-product-carousel, cx-searchbox);

$skipComponentStyles: (cx-product-carousel, cx-searchbox);
  Skipping specific component styles might be beneficial if you need to create styles from scratch and do not want to override specific style rules coming from the Spartacus style library.

Where should this be done? I can't get that from the documentation. My first guess should be the global style.scss but for example the following does not work:

```<code>@import '~@spartacus/styles/index';
$skipComponentStyles: (header, cx-media, cx-banner, cx-category-navigation);

</code>```

答:
You're almost right, you just need to swap the 2 lines. The sass variable will be used inside the import of the Spartacus styles, otherwise the variable defaults to an empty var. so, the following will work: </p>

```<code>$skipComponentStyles: (header, cx-media, cx-banner, cx-category-navigation);
@import '~@spartacus/styles/index';

</code>```

Title: Disable Spartacus component styles

Body:
The documentation states that that component styles can be skipped

Skipping Specific Component Styles
  Component styles are optional, because they are pulled in from the style library. Therefore, you might want to disable some standard component styles entirely. To disable standard component styles, you can add the component selectors to the $skipComponentStyles list. The following is an example that demonstrates skipping two standard components from the style library:

$skipComponentStyles: (cx-product-carousel, cx-searchbox);

$skipComponentStyles: (cx-product-carousel, cx-searchbox);
  Skipping specific component styles might be beneficial if you need to create styles from scratch and do not want to override specific style rules coming from the Spartacus style library.

Where should this be done? I can't get that from the documentation. My first guess should be the global style.scss but for example the following does not work:

@import '~@spartacus/styles/index';
$skipComponentStyles: (header, cx-media, cx-banner, cx-category-navigation);

Body:
You're almost right, you just need to swap the 2 lines. The sass variable will be used inside the import of the Spartacus styles, otherwise the variable defaults to an empty var. so, the following will work:

$skipComponentStyles: (header, cx-media, cx-banner, cx-category-navigation);
@import '~@spartacus/styles/index';


问:
TypeError with Validation decorator in class method
I am trying to use a simple validation decorator inside a class:

```<code>import numpy as np

def validate_decorator(func):
    def func_wrapper(value):
        if value < 0:
            raise Exception("Not valid!")
        return func(value)
    return func_wrapper

class MyClass:
    def __init__(self):
        self.my_array = np.zeros(shape=(10,))
        self.idx = 0

    @validate_decorator
    def insert_value(self, value):
        self.my_array[self.idx] = value
        self.idx += 1

    def __str__(self):
        return f"{self.my_array[:self.idx]}"

a = MyClass()
a.insert_value(3.14)
</code>```

This gives

TypeError: func_wrapper() takes 1 positional argument but 2 were given

I do not understand this error.

If I modify the func_wrapper to also take a self argument and return self (instead of func(value)) then there is no TypeError but, as expected, the insert_value is not executed.

Can someone help me understand how to use this simple decorator inside my class?

答:
I've added self argument to func_wrapper and changed func_wrapper's return value to func(self, value). It works now, insert_value is executed.

Class instance method always has this required self attribute unless converted to class method or static method: What is the purpose of the word 'self', in Python?

```<code>import numpy as np

def validate_decorator(func):
    def func_wrapper(self, value):
        if value < 0:
            raise Exception("Not valid!")
        return func(self, value)
    return func_wrapper

class MyClass:
    def __init__(self):
        self.my_array = np.zeros(shape=(10,))
        self.idx = 0

    @validate_decorator
    def insert_value(self, value):
        self.my_array[self.idx] = value
        self.idx += 1
        print('EXECUTED!')

    def __str__(self):
        return f"{self.my_array[:self.idx]}"

a = MyClass()
a.insert_value(3.14)
</code>```

Body:
I am trying to use a simple validation decorator inside a class:

import numpy as np

def validate_decorator(func):
    def func_wrapper(value):
        if value < 0:
            raise Exception("Not valid!")
        return func(value)
    return func_wrapper

class MyClass:
    def __init__(self):
        self.my_array = np.zeros(shape=(10,))
        self.idx = 0

    @validate_decorator
    def insert_value(self, value):
        self.my_array[self.idx] = value
        self.idx += 1

    def __str__(self):
        return f"{self.my_array[:self.idx]}"

a = MyClass()
a.insert_value(3.14)

This gives

TypeError: func_wrapper() takes 1 positional argument but 2 were given

I do not understand this error.

If I modify the func_wrapper to also take a self argument and return self (instead of func(value)) then there is no TypeError but, as expected, the insert_value is not executed.

Can someone help me understand how to use this simple decorator inside my class?

Body:
I've added self argument to func_wrapper and changed func_wrapper's return value to func(self, value). It works now, insert_value is executed.

Class instance method always has this required self attribute unless converted to class method or static method: What is the purpose of the word 'self', in Python?

import numpy as np

def validate_decorator(func):
    def func_wrapper(self, value):
        if value < 0:
            raise Exception("Not valid!")
        return func(self, value)
    return func_wrapper

class MyClass:
    def __init__(self):
        self.my_array = np.zeros(shape=(10,))
        self.idx = 0

    @validate_decorator
    def insert_value(self, value):
        self.my_array[self.idx] = value
        self.idx += 1
        print('EXECUTED!')

    def __str__(self):
        return f"{self.my_array[:self.idx]}"

a = MyClass()
a.insert_value(3.14)


问:
Is Java breaking its own rules with setter methods that have non-void return types?
I was given to understand that the standard convention was for setters not to return anything. However, the NIO.2 API has a few methods like setOwner, setLastModifiedTime and setAttribute that return Path instances. Are these methods not true setters, or else do not all setters have to have void return types?</p>

答:
The obsolete JavaBean standard (which was meant to help with tooling so that JavaBeans could be automatically handled) may have said something about void setters, but Fluent Builder is aimed at making things easier.

Allowing method chaining makes for nicer code, and as there's no good reason for requiring a void return type from setters, they've chosen to get with the program (no they haven't see comments):

```<code>path.setOwner(foo).setLastModifiedTime(bar).setAttribute(baz);
</code>```

The JDK does have examples of fluent interface in classes like StringBuilder and ProcessBuilder, but they avoid using the setXXX nomenclature (possibly to avoid confusion) even when it would make sense. StringBuilder.append() obviously wouldn't be named setMoreText(), but ProcessBuilder.directory(File) is less obvious than setWorkingDirectory(File) IMHO.

Body:
The obsolete JavaBean standard (which was meant to help with tooling so that JavaBeans could be automatically handled) may have said something about void setters, but Fluent Builder is aimed at making things easier.

Allowing method chaining makes for nicer code, and as there's no good reason for requiring a void return type from setters, they've chosen to get with the program (no they haven't see comments):

path.setOwner(foo).setLastModifiedTime(bar).setAttribute(baz);

The JDK does have examples of fluent interface in classes like StringBuilder and ProcessBuilder, but they avoid using the setXXX nomenclature (possibly to avoid confusion) even when it would make sense. StringBuilder.append() obviously wouldn't be named setMoreText(), but ProcessBuilder.directory(File) is less obvious than setWorkingDirectory(File) IMHO.


问:
Upgrading to Spring Boot 2.2.2.RELEASE + Thymeleaf 3.0.11.RELEASE, thymeleaf/layout stopped working
After migrating Spring-Boot from 1.5.3.RELEASE to 2.2.2.RELEASE, Thymeleaf stopped working.

pom.xml

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

...

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
</code>```

I've followed Thymeleaf 3 migration guide + read Spring-Boot release, but no success...

Template fragment (Thymeleaf 3.0 layout:decorate)

```<code><!DOCTYPE html>
<html th:lang="${#locale}" xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="https://www.thymeleaf.org"
    xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
    xmlns:layout="https://www.ultraq.net.nz/thymeleaf/layout"
    layout:decorate="layout">
<head>
<title></title>
</head>
<body>
    <div layout:fragment="content">
</code>```

http://localhost/index path comparison:

Code fragment (1.5.3.RELEASE)

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">

<head>

    <title>APLLICATION</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'/><![endif]-->
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1" />
    <meta name="description" content="Application description" />
    <meta name="fragment" content="text" />

    <link rel="stylesheet" href="css/vendor/bootstrap.min.css" />
    <link rel="stylesheet" href="css/vendor/jquery-ui.min.css" />
    ...
</code>```

Code fragment (2.2.2.RELEASE)

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:layout="https://www.ultraq.net.nz/thymeleaf/layout"
    layout:decorate="layout">
<head>
<title></title>
</head>
<body>
    <div layout:fragment="content">
...
</code>```

Any help appreciated. Thanks

EDIT:

@Marged, Models are set:

```<code>@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
        ...
    }

}
</code>```

Context-path is by default (/)

```<code>@SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class })
@EnableConfigurationProperties({ AppConfig.class })
@EnableScheduling
@EnableJpaRepositories
@EnableAutoConfiguration
@ComponentScan("foo.bar")
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}
</code>```

答:
Your issue seems to be related to Thymeleaf Layout Dialect (see #4). Spring-Boot 1.5.3.RELEASE supports it out of the box but 2.2.2.RELEASE doesn't. This is even stated in dialect's documentation:

The layout dialect is already included as part of the Thymeleaf starter pack in Spring Boot 1.x, but has been removed in Spring Boot 2, hence the additional config step for Spring Boot 2 users above.

Following installation steps from above link should be helpful, i.a.:

Add maven dependency:

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>2.4.1</version>
</dependency>
```

<ul>
<li>Add Extra <code>@Bean</code> to you configuration:</li>
</ul>

<pre class="lang-java prettyprint-override"><code>@Bean
public LayoutDialect layoutDialect() {
    return new LayoutDialect();
}
</code>```

Body:
After migrating Spring-Boot from 1.5.3.RELEASE to 2.2.2.RELEASE, Thymeleaf stopped working.

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
    <relativePath />
</parent>

...

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

I've followed Thymeleaf 3 migration guide + read Spring-Boot release, but no success...

Template fragment (Thymeleaf 3.0 layout:decorate)

<!DOCTYPE html>

<title></title>

http://localhost/index path comparison:

Code fragment (1.5.3.RELEASE)

<!DOCTYPE html>

    <title>APLLICATION</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1" />
    <meta name="description" content="Application description" />
    <meta name="fragment" content="text" />

    <link rel="stylesheet" href="css/vendor/bootstrap.min.css" />
    <link rel="stylesheet" href="css/vendor/jquery-ui.min.css" />
    ...

Code fragment (2.2.2.RELEASE)

<!DOCTYPE html>

<title></title>

...

Any help appreciated. Thanks

EDIT:

@Marged, Models are set:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
        ...
    }

}

Context-path is by default (/)

@SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class })
@EnableConfigurationProperties({ AppConfig.class })
@EnableScheduling
@EnableJpaRepositories
@EnableAutoConfiguration
@ComponentScan("foo.bar")
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

Body:
Your issue seems to be related to Thymeleaf Layout Dialect (see #4). Spring-Boot 1.5.3.RELEASE supports it out of the box but 2.2.2.RELEASE doesn't. This is even stated in dialect's documentation:

The layout dialect is already included as part of the Thymeleaf starter pack in Spring Boot 1.x, but has been removed in Spring Boot 2, hence the additional config step for Spring Boot 2 users above.

Following installation steps from above link should be helpful, i.a.:

Add maven dependency:

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>2.4.1</version>
</dependency>

Add Extra @Bean to you configuration:

@Bean
public LayoutDialect layoutDialect() {
    return new LayoutDialect();
}


问:
Php split / chunk Excel with Maatwebsite Laravel-Excel v.3
I have very big xlsx 1000000 rows, but for testing I use Excel with 999 rows. So, to save memory I want to take chunks of data from this file and handle them. I found this https://docs.laravel-excel.com/3.1/imports/chunk-reading.html

```<code>namespace App\Imports;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithChunkReading;
class ProducttestImport implements ToArray,WithChunkReading
{
    public function array(array $row): array
    { return $row ; }
    public function chunkSize(): int
    { return 100; }
}
</code>```

in controller

```<code>myFunc(){
$rows = Excel::toArray(new ProducttestImport(), $path.$excelName)[0];
return  $rows;
}
</code>```

but seems I'm missing something, because $rows is having array with 999 arrays. I need array with 10 arrays (when chunking 999 rows).

Where I can access/get those chunks?

答:
Workaround..

```<code>namespace App\Exports;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
class ProducttestExport implements FromArray
{use Exportable;
    public $inputArr;

    public function __construct(array $inputArr = [])
    { $this->inputArr = $inputArr; }

    public function array() :array
    {
        if(count($this->inputArr) >0) return $this->inputArr;
        return [];
    }
}
</code>```

In foreach

```<code>...
Excel::store( new ProducttestExport($array), $key.'_file.xlsx', 'my_disk' );
...
</code>```

Then handle files one by one..

But anyway I hope someone knows how to get chunks and will post an answer.

Body:
I have very big xlsx 1000000 rows, but for testing I use Excel with 999 rows. So, to save memory I want to take chunks of data from this file and handle them. I found this https://docs.laravel-excel.com/3.1/imports/chunk-reading.html

namespace App\Imports;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithChunkReading;
class ProducttestImport implements ToArray,WithChunkReading
{
    public function array(array $row): array
    { return $row ; }
    public function chunkSize(): int
    { return 100; }
}

in controller

myFunc(){
$rows = Excel::toArray(new ProducttestImport(), $path.$excelName)[0];
return  $rows;
}

but seems I'm missing something, because $rows is having array with 999 arrays. I need array with 10 arrays (when chunking 999 rows).

Where I can access/get those chunks?

Body:
Workaround..

namespace App\Exports;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
class ProducttestExport implements FromArray
{use Exportable;
    public $inputArr;

    public function __construct(array $inputArr = [])
    { $this->inputArr = $inputArr; }

    public function array() :array
    {
        if(count($this->inputArr) >0) return $this->inputArr;
        return [];
    }
}

In foreach

...
Excel::store( new ProducttestExport($array), $key.'_file.xlsx', 'my_disk' );
...

Then handle files one by one..

But anyway I hope someone knows how to get chunks and will post an answer.