问:
Cached Docker images on Hosted Linux Preview agent
We are building docker image on VSTS by using VSTS Hosted Linux Preview agent. microsoft/aspnetcore-build image is used to build asp.net core application. Each time build is triggered, an agent is pulling microsoft/aspnetcore-build image from registry and it takes some time. We would like to avoid this, by specifying specific image pre-cached on agents.

Is there a list of container images that have been cached on Hosted Linux Preview agent? Such information is available for Hosted VS2017 agent, but not for Linux one.

答:
According to this documentation the complete list can be found in the following documents:

Details of Ubuntu 18.04 agent image *

Details of Ubuntu 20.04 agent image *

(*) The above are permalinks to a specific snapshot of code (dated 2022-03-26). For the most current data, switch to the "main" branch in GitHub. Note that files may disappear from the 'main' branch when image gets deprecated.

As of 2022-03-26, both images include the same set of pre-cached docker images which are:

```<code>alpine:3.12
alpine:3.13
alpine:3.14
buildpack-deps:bullseye
buildpack-deps:buster
buildpack-deps:stretch
debian:10
debian:11
debian:9
moby/buildkit:latest
node:12
node:12-alpine
node:14
node:14-alpine
node:16
node:16-alpine
ubuntu:16.04
ubuntu:18.04
ubuntu:20.04
</code>```

This can also be confirmed by adding a simple task to the pipeline that runs docker image list. Here's an example of the command's output ran on Ubuntu-16.04 agent (before it was deprecated):

```<code>/usr/bin/docker image list
REPOSITORY                                           TAG                 IMAGE ID            CREATED             SIZE
node                                                 10-alpine           955e0e1f1a41        11 days ago         80.5MB
node                                                 10                  bb78c02ca3bf        11 days ago         908MB
node                                                 12-alpine           afd897e3184b        11 days ago         85.2MB
node                                                 12                  b6f455933a97        11 days ago         913MB
buildpack-deps                                       stretch             c82dad0a8baf        2 weeks ago         835MB
debian                                               9                   92416e205014        2 weeks ago         101MB
debian                                               8                   955c8f8160c2        2 weeks ago         129MB
alpine                                               3.8                 c8bccc0af957        3 weeks ago         4.41MB
alpine                                               3.9                 82f67be598eb        3 weeks ago         5.53MB
alpine                                               3.10                af341ccd2df8        3 weeks ago         5.56MB
jekyll/builder                                       latest              4605d94a6b36        4 months ago        564MB
alpine                                               3.7                 6d1ef012b567        11 months ago       4.21MB
mcr.microsoft.com/azure-pipelines/node8-typescript   latest              9a948d360778        16 months ago       595MB
</code>```

Body:
According to this documentation the complete list can be found in the following documents:

Details of Ubuntu 18.04 agent image *

Details of Ubuntu 20.04 agent image *

(*) The above are permalinks to a specific snapshot of code (dated 2022-03-26). For the most current data, switch to the "main" branch in GitHub. Note that files may disappear from the 'main' branch when image gets deprecated.

As of 2022-03-26, both images include the same set of pre-cached docker images which are:

alpine:3.12
alpine:3.13
alpine:3.14
buildpack-deps:bullseye
buildpack-deps:buster
buildpack-deps:stretch
debian:10
debian:11
debian:9
moby/buildkit:latest
node:12
node:12-alpine
node:14
node:14-alpine
node:16
node:16-alpine
ubuntu:16.04
ubuntu:18.04
ubuntu:20.04

This can also be confirmed by adding a simple task to the pipeline that runs docker image list. Here's an example of the command's output ran on Ubuntu-16.04 agent (before it was deprecated):

/usr/bin/docker image list
REPOSITORY                                           TAG                 IMAGE ID            CREATED             SIZE
node                                                 10-alpine           955e0e1f1a41        11 days ago         80.5MB
node                                                 10                  bb78c02ca3bf        11 days ago         908MB
node                                                 12-alpine           afd897e3184b        11 days ago         85.2MB
node                                                 12                  b6f455933a97        11 days ago         913MB
buildpack-deps                                       stretch             c82dad0a8baf        2 weeks ago         835MB
debian                                               9                   92416e205014        2 weeks ago         101MB
debian                                               8                   955c8f8160c2        2 weeks ago         129MB
alpine                                               3.8                 c8bccc0af957        3 weeks ago         4.41MB
alpine                                               3.9                 82f67be598eb        3 weeks ago         5.53MB
alpine                                               3.10                af341ccd2df8        3 weeks ago         5.56MB
jekyll/builder                                       latest              4605d94a6b36        4 months ago        564MB
alpine                                               3.7                 6d1ef012b567        11 months ago       4.21MB
mcr.microsoft.com/azure-pipelines/node8-typescript   latest              9a948d360778        16 months ago       595MB


来源: stackexchange

问:
Since flutter 1.9 : how to run flutter app in a browser ? Flutter run -d chrome not working
Since flutter 1.9 flutter_web is merged inside flutter. I'm trying to run the initial flutter app in a chrome browser but it fails. OS is ubuntu 19.04

The command I used with success:
flutter upgrade

flutter create test_1_9

cd test_1_9

flutter run

The command not working:

flutter run -d chrome

=> No devices found with name or id matching 'chrome'

I tried with google-chrome as device name with same result

```<code>[✓] Flutter (Channel master, v1.10.2-pre.38, on Linux, locale fr_FR.UTF-8)
    • Flutter version 1.10.2-pre.38 at /home/rbarbe/programes/flutter
    • Framework revision e6ae95c4ce (il y a 18 heures), 2019-09-11 07:46:57 -0700
    • Engine revision 7ea9884ab0
    • Dart version 2.5.0 (build 2.5.0-dev.4.0 be66176534)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /home/rbarbe/Android/Sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /home/rbarbe/programes/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] Android Studio (version 3.3)
    • Android Studio at /home/rbarbe/programes/android-studio
    • Flutter plugin version 33.3.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] IntelliJ IDEA Community Edition (version 2019.1)
    • IntelliJ at /home/rbarbe/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/191.6183.87
    • Flutter plugin version 35.2.2
    • Dart plugin version 191.6183.88

[✓] IntelliJ IDEA Community Edition (version 2019.2)
    • IntelliJ at /home/rbarbe/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/192.6603.28
    • Flutter plugin version 39.0.5
    • Dart plugin version 192.6603.23

[✓] VS Code (version 1.38.0)
    • VS Code at /usr/share/code
    • Flutter extension version 3.4.1

[✓] Connected device (1 available)
    • CLT L29 • WCR0218315003400 • android-arm64 • Android 9 (API 28)

• No issues found!
</code>```

答:
https://flutter.dev/docs/get-started/web</p>

```<code>$ flutter channel master
$ flutter upgrade
$ flutter config --enable-web

$ flutter devices  //downloads sky_engine and sdk tools then shows a list of devices including chrome

$ flutter create test_app
$ flutter run -d chrome  //local host will run chrome
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Since flutter 1.9 flutter_web is merged inside flutter. I'm trying to run the initial flutter app in a chrome browser but it fails. OS is ubuntu 19.04

The command I used with success:
flutter upgrade

flutter create test_1_9

cd test_1_9

flutter run

The command not working:

flutter run -d chrome

=> No devices found with name or id matching 'chrome'

I tried with google-chrome as device name with same result

[✓] Flutter (Channel master, v1.10.2-pre.38, on Linux, locale fr_FR.UTF-8)
    • Flutter version 1.10.2-pre.38 at /home/rbarbe/programes/flutter
    • Framework revision e6ae95c4ce (il y a 18 heures), 2019-09-11 07:46:57 -0700
    • Engine revision 7ea9884ab0
    • Dart version 2.5.0 (build 2.5.0-dev.4.0 be66176534)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /home/rbarbe/Android/Sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /home/rbarbe/programes/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] Android Studio (version 3.3)
    • Android Studio at /home/rbarbe/programes/android-studio
    • Flutter plugin version 33.3.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] IntelliJ IDEA Community Edition (version 2019.1)
    • IntelliJ at /home/rbarbe/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/191.6183.87
    • Flutter plugin version 35.2.2
    • Dart plugin version 191.6183.88

[✓] IntelliJ IDEA Community Edition (version 2019.2)
    • IntelliJ at /home/rbarbe/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/192.6603.28
    • Flutter plugin version 39.0.5
    • Dart plugin version 192.6603.23

[✓] VS Code (version 1.38.0)
    • VS Code at /usr/share/code
    • Flutter extension version 3.4.1

[✓] Connected device (1 available)
    • CLT L29 • WCR0218315003400 • android-arm64 • Android 9 (API 28)

• No issues found!

Body:
https://flutter.dev/docs/get-started/web

$ flutter channel master
$ flutter upgrade
$ flutter config --enable-web

$ flutter devices  //downloads sky_engine and sdk tools then shows a list of devices including chrome

$ flutter create test_app
$ flutter run -d chrome  //local host will run chrome


问:
Apache Kafka : Can be used to push data to IoT devices?
I have some IoT devices which need to be updated sometimes, based on configuration done in web or mobile clients. So I need to give capability to be updated based on a configuration.

I have the following architecture when Clients communicates over HTTPS to an API Gateway. This Gateway is responsible to fetch data from several micro-services that interact with Kafka and some databases.

In this context, it is a good idea to create a Kafka consumer in IoT devices that will consumes messages from a Kafka Configuration Topic ?

Based on each new message received on this topic, the IoT device will be responsible to apply the change on the configuration.

Any advise ?

答:
Usually, IoT devices have strong CPU/RAM and/or battery restrictions. The most widely used solution for messaging over IoT is MQTT and https://mosquitto.org/ the currently most widespread MQTT broker, so I would try to use https://mosquitto.org/ on the IoT devices and link it with Kafka through a "Confluent MQTT Proxy", you have more information at https://www.confluent.io/confluent-mqtt-proxy/
It is also not difficult to create your own "MQTT proxy" in python (or the language you prefer)</p>


问:
How variable gets created and destroy in python?
If we create 2 variables a followed by b, then how these variable gets destroy in python heap.
We want to understand the memory management done by python interpreter.</p>

答:
Order is undefined as python has a garbage collector. To trace the order you may add a __del__ method which is known as a destructor method in Python. It is called when there are no  references to the object and object is garbage collected.

See What is the __del__ method, How to call it?


问:
What's the difference between a POST and a PUT HTTP REQUEST?
They both seem to be sending data to the server inside the body, so what makes them different?</p>

答:
It should be pretty straightforward when to use one or the other, but complex wordings are a source of confusion for many of us.

When to use them:

Use PUT when you want to modify a singular resource that is already a part of resource collection. PUT replaces the resource in its entirety. Example: PUT /resources/:resourceId

Sidenote: Use PATCH if you want to update a part of the resource.

Use POST when you want to add a child resource under a collection of resources.

Example: POST => /resources

In general:

Generally, in practice, always use PUT for UPDATE operations.

Always use POST for CREATE operations.

Example:

GET     /company/reports      => Get all reports

GET     /company/reports/{id} => Get the report information identified by "id"

POST    /company/reports      => Create a new report

PUT     /company/reports/{id} => Update the report information identified by "id"

PATCH     /company/reports/{id} => Update a part of the report information identified by "id"

DELETE    /company/reports/{id} => Delete report by "id"

OwnerDisplayName: fuentesjr

ContentLicense: CC BY-SA 2.5


问:
Zend Tool create action does not recognise controller in module
I created a module and controller using:

```<code>$ zf create module api
$ zf create controller auth index-action-included=1 api
</code>```

This works fine, and I get the index action when I request http://localhost/api/auth.

I want to create a new action called validate:

```<code>$ zf create action validate auth view-included=1 api
</code>```

But I get told that:

```<code>An Error Has Occurred
Controller auth was not found.
</code>```

Edit:

I have directly added the action in the controller, and created the view file - but I hope I don't miss anything else I need here that the command line should have created.

答:
The command should be like this:

```<code>$ zf create action validate -c auth
</code>```

For details zend commands

ContentLicense: CC BY-SA 3.0

Body:
I created a module and controller using:

$ zf create module api
$ zf create controller auth index-action-included=1 api

This works fine, and I get the index action when I request http://localhost/api/auth.

I want to create a new action called validate:

$ zf create action validate auth view-included=1 api

But I get told that:

An Error Has Occurred
Controller auth was not found.

Edit:

I have directly added the action in the controller, and created the view file - but I hope I don't miss anything else I need here that the command line should have created.

Body:
The command should be like this:

$ zf create action validate -c auth

For details zend commands


问:
Differentiate between audio start and audio play(after a pause) in HTML5 <audio>
How to add a listener on audio/video start?

I can do it like:

```<code>$audio.on("play", function() {
    console.log("audio played");
});
</code>```

where $audio is a jQuery object representing the single DOM audio element.

but it will also run when we resume the video. I want it to run on start only.

One way I can do it is:

```<code>$audio.on("play", function() {
  if(this.currentTime === 0) {
      console.log("audio started);
  }
});
</code>```

but this will run multiple times when we play/pause the audio on the start.

Is there any better way to do this? The listener should only work on audio start and audio replayed, not when the user manually drags the seek bar to the beginning of the source.

答:
Store a flag into the data-* attribute of the targeted element:

const $audio = $('.audio');
$audio.on("play", function() {

  if ($(this).data('once-played')) return; // Do nothing if data exists.

  // Your code here
  console.log("Audio started for the first time");

  // Finally, add a flag.
  $(this).data('once-played', true);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><audio class="audio" src="http://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg" autoplay controls loop></audio>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Body:
How to add a listener on audio/video start?

I can do it like:

$audio.on("play", function() {
    console.log("audio played");
});

where $audio is a jQuery object representing the single DOM audio element.

but it will also run when we resume the video. I want it to run on start only.

One way I can do it is:

$audio.on("play", function() {
  if(this.currentTime === 0) {
      console.log("audio started);
  }
});

but this will run multiple times when we play/pause the audio on the start.

Is there any better way to do this? The listener should only work on audio start and audio replayed, not when the user manually drags the seek bar to the beginning of the source.

Body:
Store a flag into the data-* attribute of the targeted element:

const $audio = $('.audio');
$audio.on("play", function() {

  if ($(this).data('once-played')) return; // Do nothing if data exists.

  // Your code here
  console.log("Audio started for the first time");

  // Finally, add a flag.
  $(this).data('once-played', true);
});

<audio class="audio" src="http://upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg" autoplay controls loop></audio>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Array filter is not returning correct for Zero?

function zeroCount(arr){
   const zero = arr.filter(el=>{
            if(el===0){
                return el ;
            }
        });
    return zero.length ; // but it returns 0. I want it to return 3.
}

console.log(zeroCount([2,3,0,5,0,2,0]));```

I want to return the no. of zero present in the array using filter.

答:
The handler for the function filter should return a boolean

The following approach assumes there are only numbers.

function zeroCount(arr) {
  return arr.filter(el => !el).length;
}

console.log(zeroCount([2, 3, 0, 5, 0, 2, 0]));```
</div>
</div>
</p>

<p>The previous approach generates an unnecessary array, so, as you want to count, a better approach is using the function <code>reduce</code> as follow:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function zeroCount(arr) {
  return arr.reduce((r, el) => r + !el, 0);
}

console.log(zeroCount([2, 3, 0, 5, 0, 2, 0]));</code>```

Body:
function zeroCount(arr){
   const zero = arr.filter(el=>{
            if(el===0){
                return el ;
            }
        });
    return zero.length ; // but it returns 0. I want it to return 3.
}

console.log(zeroCount([2,3,0,5,0,2,0]));

I want to return the no. of zero present in the array using filter.

Body:
The handler for the function filter should return a boolean

The following approach assumes there are only numbers.

function zeroCount(arr) {
  return arr.filter(el => !el).length;
}

console.log(zeroCount([2, 3, 0, 5, 0, 2, 0]));

The previous approach generates an unnecessary array, so, as you want to count, a better approach is using the function reduce as follow:

function zeroCount(arr) {
  return arr.reduce((r, el) => r + !el, 0);
}

console.log(zeroCount([2, 3, 0, 5, 0, 2, 0]));


问:
How to install hyperledger explorer and integrate it to iroha?
hello and seen the repository documentation to install the explorer and is based on the  installation on fabric.

https://github.com/hyperledger/blockchain-explorer

This resource exists but gives little information about the installation process.

https://github.com/turuslan/iroha-explorer-backend

I am very grateful if there is any more detailed documentation.

答: Here is the link to the instructions with Iroha. The links will soon be public on the main README of Explorer. </p>


问:
Numpy Selecting Elements given row and column index arrays
I have row indices as a 1d numpy array and a list of numpy arrays (list as same length as the size of the row indices array. I want to extract values corresponding to these indices. How can I do it ?

This is an example of what I want as output given the input

```<code>A = np.array([[2, 1, 1, 0, 0],
              [3, 0, 2, 1, 1],
              [0, 0, 2, 1, 0],
              [0, 3, 3, 3, 0],
              [0, 1, 2, 1, 0],
              [0, 1, 3, 1, 0],
              [2, 1, 3, 0, 1],
              [2, 0, 2, 0, 2],
              [3, 0, 3, 1, 2]])

row_ind = np.array([0,2,4])
col_ind = [np.array([0, 1, 2]), np.array([2, 3]), np.array([1, 2, 3])]
</code>```

Now, I want my output as a list of numpy arrays or list of lists as

```<code>[np.array([2, 1, 1]), np.array([2, 1]), np.array([1, 2, 1])]
</code>```

My biggest concern is the efficiency.  My array A is of dimension 20K x 10K.

答:
As @hpaulj commented, likely, you won't be able to avoid looping - e.g.

```<code>import numpy as np

A = np.array([[2, 1, 1, 0, 0],
              [3, 0, 2, 1, 1],
              [0, 0, 2, 1, 0],
              [0, 3, 3, 3, 0],
              [0, 1, 2, 1, 0],
              [0, 1, 3, 1, 0],
              [2, 1, 3, 0, 1],
              [2, 0, 2, 0, 2],
              [3, 0, 3, 1, 2]])

row_ind = np.array([0,2,4])
col_ind = [np.array([0, 1, 2]), np.array([2, 3]), np.array([1, 2, 3])]

# make sure the following code is safe...
assert row_ind.shape[0] == len(col_ind)

# 1) select row (A[r, :]), then select elements (cols) [col_ind[i]]:
output = [A[r, :][col_ind[i]] for i, r in enumerate(row_ind)]

# output
# [array([2, 1, 1]), array([2, 1]), array([1, 2, 1])]
</code>```

Another way to do this could be to use np.ix_ (still requires looping). Use with caution though for very large arrays; np.ix_ uses advanced indexing - in contrast to basic slicing, it creates a copy of the data instead of a view - see the docs.

Body:
I have row indices as a 1d numpy array and a list of numpy arrays (list as same length as the size of the row indices array. I want to extract values corresponding to these indices. How can I do it ?

This is an example of what I want as output given the input

A = np.array([[2, 1, 1, 0, 0],
              [3, 0, 2, 1, 1],
              [0, 0, 2, 1, 0],
              [0, 3, 3, 3, 0],
              [0, 1, 2, 1, 0],
              [0, 1, 3, 1, 0],
              [2, 1, 3, 0, 1],
              [2, 0, 2, 0, 2],
              [3, 0, 3, 1, 2]])

row_ind = np.array([0,2,4])
col_ind = [np.array([0, 1, 2]), np.array([2, 3]), np.array([1, 2, 3])]

Now, I want my output as a list of numpy arrays or list of lists as

[np.array([2, 1, 1]), np.array([2, 1]), np.array([1, 2, 1])]

My biggest concern is the efficiency.  My array A is of dimension 20K x 10K.

Body:
As @hpaulj commented, likely, you won't be able to avoid looping - e.g.

import numpy as np

A = np.array([[2, 1, 1, 0, 0],
              [3, 0, 2, 1, 1],
              [0, 0, 2, 1, 0],
              [0, 3, 3, 3, 0],
              [0, 1, 2, 1, 0],
              [0, 1, 3, 1, 0],
              [2, 1, 3, 0, 1],
              [2, 0, 2, 0, 2],
              [3, 0, 3, 1, 2]])

row_ind = np.array([0,2,4])
col_ind = [np.array([0, 1, 2]), np.array([2, 3]), np.array([1, 2, 3])]

# make sure the following code is safe...
assert row_ind.shape[0] == len(col_ind)

# 1) select row (A[r, :]), then select elements (cols) [col_ind[i]]:
output = [A[r, :][col_ind[i]] for i, r in enumerate(row_ind)]

# output
# [array([2, 1, 1]), array([2, 1]), array([1, 2, 1])]

Another way to do this could be to use np.ix_ (still requires looping). Use with caution though for very large arrays; np.ix_ uses advanced indexing - in contrast to basic slicing, it creates a copy of the data instead of a view - see the docs.


问:
Regex start with exactly two alphabetic characters and than followed by any digits
I'm trying to create a very simple regex that accepts strings:

starts with two [A-Za-z] characters

ends with any number of digits

my code is:

Regex.IsMatch("AA00000000000", $"^[A-Za-z]{2}[0-9]*$")
```

but it returns False. Where am I wrong? I've already tested the same regex with the same input on regexstorm.net and it works.

答: You put a "$" in front of your regular expression, because of that the "{2}" part will be interpreted as just "2", so the regex that gets evaluated looks like this: "^[A-Za-z]2[0-9]*$".</p>

Body:
I'm trying to create a very simple regex that accepts strings:

starts with two [A-Za-z] characters

ends with any number of digits

my code is:

Regex.IsMatch("AA00000000000", $"^[A-Za-z]{2}[0-9]*$")

but it returns False. Where am I wrong? I've already tested the same regex with the same input on regexstorm.net and it works.


问:
how can I wait the http request to finish in angular 8?
this is my service

```<code>existWayBillByRsBillNumber(billNumber: string){
    return  this.http.get<boolean>(this.baseUrl + 'Common/ExistWayBillByRsBillNumber/'+billNumber);
  }
</code>```

this is service call

```<code>this.commonService.existWayBillByRsBillNumber(this.buyerWaybill.waybillNumber).subscribe(
  response => {
    let exist = <Boolean>response;
    if (exist) {
      console.log(1);
      this.toastService.error('ზედდებული ნომრით ' + this.buyerWaybill.waybillNumber + " უკვე არსებობს!");
      return false;
    }
  }
);
console.log(2);
    }
  }
);
</code>```

in console is printed 2 and after 1
enter image description here

how i can wait a service response

答:
Your code is working as expected.

If we were to step through your code, it would go something like:

Call service

Make http request

Wait for response, return observable

console.log(2)

...

HTTP response is returned

Execute callback of subscriber

console.log(1) [inside if condition]

So the fact is, you are already waiting for your service response - it's where you are checking the response and conditionally logging 1 to the console.

You have some issues with how you are making your request and handling the response, but your question effectively asks why 2 is logged before 1.

Edit:

This is a physical version of the steps above from the component's point of view:

```<code>
console.log('1. Call service);

this.commonService
  .existWayBillByRsBillNumber(this.buyerWaybill.waybillNumber)
  .subscribe(response => {
    console.log('7. Execute callback of subscriber');

    if (response === true) {
      // handle true
    } else {
      // handle false
    }
  });

console.log(2);

</code>```

Body:
this is my service

existWayBillByRsBillNumber(billNumber: string){
    return  this.http.get<boolean>(this.baseUrl + 'Common/ExistWayBillByRsBillNumber/'+billNumber);
  }

this is service call

this.commonService.existWayBillByRsBillNumber(this.buyerWaybill.waybillNumber).subscribe(
  response => {
    let exist = <Boolean>response;
    if (exist) {
      console.log(1);
      this.toastService.error('ზედდებული ნომრით ' + this.buyerWaybill.waybillNumber + " უკვე არსებობს!");
      return false;
    }
  }
);
console.log(2);
    }
  }
);

in console is printed 2 and after 1
enter image description here

how i can wait a service response

Body:
Your code is working as expected.

If we were to step through your code, it would go something like:

Call service

Make http request

Wait for response, return observable

console.log(2)

...

HTTP response is returned

Execute callback of subscriber

console.log(1) [inside if condition]

So the fact is, you are already waiting for your service response - it's where you are checking the response and conditionally logging 1 to the console.

You have some issues with how you are making your request and handling the response, but your question effectively asks why 2 is logged before 1.

Edit:

This is a physical version of the steps above from the component's point of view:

console.log('1. Call service);

this.commonService
  .existWayBillByRsBillNumber(this.buyerWaybill.waybillNumber)
  .subscribe(response => {
    console.log('7. Execute callback of subscriber');

    if (response === true) {
      // handle true
    } else {
      // handle false
    }
  });

console.log(2);


问:
Wait until all the files are copied?
I am trying to find a way to wait until xcopy cmd finished copying files from a disk. I tried 2 ways. First way is basically waiting for hprocess from the created process.

But this waitForSingleObject never resolves.

```<code>void copyFileWait(){

  STARTinfP777.cb = sizeof(STARTinfP777);
  char allCmd[MAX_PATH] = "C:\\Windows\\System32\\cmd.exe /k copy /y \""; // = drive letter; xcopy working fine
  printf("%s\n", allCmd);

  DWORD safsdkasf = 0;
  if(CreateProcess(NULL, allCmd, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, NULL, NULL, &STARTinfP777, &procInf7777) == 0){

    printf("%d\n", GetLastError());
    MessageBox(0, "Hata", "Dikkat!", MB_OK);
    exit(0);
  }
  WaitForSingleObject( procInf7777.hProcess, INFINITE );
  CloseHandle( procInf7777.hProcess );
  CloseHandle( procInf7777.hThread );

}
</code>```

In this function, i check the exitcode of the process after ran with GetExitCodeProcess() and also set a timer on the code. But it always equals to 259 i dont notice any change after even the files are completely written.

```<code> void copyFileWait();
void gggPaths();
DWORD WINAPI GetDirsSEVENthreadFunc ();

//void cpyToPES(char fromWhereToCopy[MAX_PATH]);

char *WndCmpath = "C:\\Windows\\System32\\cmd.exe ";

HANDLE fileCopierHandle;
int Nprocess = 0;

STARTUPINFO STARTinfP777 = {0};
PROCESS_INFORMATION procInf7777 = {0};
DWORD exitcode;

int main(){

    gggPaths();

    //copyFileWait();

    DWORD threadCPYFilesID;
    fileCopierHandle=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)GetDirsSEVENthreadFunc,(LPVOID)10,0,&threadCPYFilesID); //updating 0 olana kadar bekler
    WaitForSingleObject(fileCopierHandle,INFINITE);

    printf("done.");
    return 0;
}

void copyFileWait(){

  STARTinfP777.cb = sizeof(STARTinfP777);
    char allCmd[MAX_PATH] = "C:\\Windows\\System32\\cmd.exe /k copy /y \""; // = drive letter; //xcopy files  bla bla works fine
    printf("%s\n", allCmd);

  DWORD safsdkasf = 0;
  if(exitcode != 259){
      if(CreateProcess(NULL, allCmd, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, NULL, NULL, &STARTinfP777, &procInf7777) == 0){

        printf("%d\n", GetLastError());
        MessageBox(0, "Hata", "Dikkat!", MB_OK);
        exit(0);
      }
  }

  BOOL result = GetExitCodeProcess(procInf7777.hProcess, &exitcode);
  if(!result){
      memset( &STARTinfP777, '\0', sizeof STARTinfP777 );
      memset( &procInf7777, '\0', sizeof procInf7777 );
      printf("damn..\n");
      printf("%d\n", GetLastError());
  }else{

  }
  printf("exitcode => %d", exitcode);
  //if() exıtcode TASK_COMPLETE forexample... kill timer etc.
}

DWORD WINAPI GetDirsSEVENthreadFunc (){
  HWND tempHW;
  SetTimer(tempHW, 0, 5500,(TIMERPROC) &copyFileWait);
  MSG msg;
  while(GetMessage(&msg, NULL, 0, 0)){
   TranslateMessage(&msg);
   DispatchMessage(&msg);
 }
}
</code>```

What would be a way to accomplish this task ?

I tried CopyFile() But it didnt find the path when i linked other volume letters, or external devices. Which I am working on.

答: Switching /k to /c solved the problem.

Title: Wait until all the files are copied?

Body:
I am trying to find a way to wait until xcopy cmd finished copying files from a disk. I tried 2 ways. First way is basically waiting for hprocess from the created process.

But this waitForSingleObject never resolves.

void copyFileWait(){

  STARTinfP777.cb = sizeof(STARTinfP777);
  char allCmd[MAX_PATH] = "C:\\Windows\\System32\\cmd.exe /k copy /y \""; // = drive letter; xcopy working fine
  printf("%s\n", allCmd);

  DWORD safsdkasf = 0;
  if(CreateProcess(NULL, allCmd, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, NULL, NULL, &STARTinfP777, &procInf7777) == 0){

    printf("%d\n", GetLastError());
    MessageBox(0, "Hata", "Dikkat!", MB_OK);
    exit(0);
  }
  WaitForSingleObject( procInf7777.hProcess, INFINITE );
  CloseHandle( procInf7777.hProcess );
  CloseHandle( procInf7777.hThread );

}

In this function, i check the exitcode of the process after ran with GetExitCodeProcess() and also set a timer on the code. But it always equals to 259 i dont notice any change after even the files are completely written.

 void copyFileWait();
void gggPaths();
DWORD WINAPI GetDirsSEVENthreadFunc ();

//void cpyToPES(char fromWhereToCopy[MAX_PATH]);

char *WndCmpath = "C:\\Windows\\System32\\cmd.exe ";

HANDLE fileCopierHandle;
int Nprocess = 0;

STARTUPINFO STARTinfP777 = {0};
PROCESS_INFORMATION procInf7777 = {0};
DWORD exitcode;

int main(){

    gggPaths();

    //copyFileWait();

    DWORD threadCPYFilesID;
    fileCopierHandle=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)GetDirsSEVENthreadFunc,(LPVOID)10,0,&threadCPYFilesID); //updating 0 olana kadar bekler
    WaitForSingleObject(fileCopierHandle,INFINITE);

    printf("done.");
    return 0;
}

void copyFileWait(){

  STARTinfP777.cb = sizeof(STARTinfP777);
    char allCmd[MAX_PATH] = "C:\\Windows\\System32\\cmd.exe /k copy /y \""; // = drive letter; //xcopy files  bla bla works fine
    printf("%s\n", allCmd);

  DWORD safsdkasf = 0;
  if(exitcode != 259){
      if(CreateProcess(NULL, allCmd, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, NULL, NULL, &STARTinfP777, &procInf7777) == 0){

        printf("%d\n", GetLastError());
        MessageBox(0, "Hata", "Dikkat!", MB_OK);
        exit(0);
      }
  }

  BOOL result = GetExitCodeProcess(procInf7777.hProcess, &exitcode);
  if(!result){
      memset( &STARTinfP777, '\0', sizeof STARTinfP777 );
      memset( &procInf7777, '\0', sizeof procInf7777 );
      printf("damn..\n");
      printf("%d\n", GetLastError());
  }else{

  }
  printf("exitcode => %d", exitcode);
  //if() exıtcode TASK_COMPLETE forexample... kill timer etc.
}

DWORD WINAPI GetDirsSEVENthreadFunc (){
  HWND tempHW;
  SetTimer(tempHW, 0, 5500,(TIMERPROC) &copyFileWait);
  MSG msg;
  while(GetMessage(&msg, NULL, 0, 0)){
   TranslateMessage(&msg);
   DispatchMessage(&msg);
 }
}

What would be a way to accomplish this task ?

I tried CopyFile() But it didnt find the path when i linked other volume letters, or external devices. Which I am working on.

Body: Switching /k to /c solved the problem.


问:
Parquet Writer to buffer or byte stream
I have a java application that converts json messages to parquet format. Is there any parquet writer which writes to buffer or byte stream in java? Most of the examples, I have seen write to files.</p>

答:
TLDR; you will need to implement OutputFile, e.g. something along the line of:

```<code>import org.apache.parquet.io.OutputFile;
import org.apache.parquet.io.PositionOutputStream;

import java.io.BufferedOutputStream;
import java.io.IOException;

public class ParquetBufferedWriter implements OutputFile {

    private final BufferedOutputStream out;

    public ParquetBufferedWriter(BufferedOutputStream out) {
        this.out = out;
    }

    @Override
    public PositionOutputStream create(long blockSizeHint) throws IOException {
        return createPositionOutputstream();
    }

    private PositionOutputStream createPositionOutputstream() {
        return new PositionOutputStream() {
            @Override
            public long getPos() throws IOException {
                return 0;
            }

            @Override
            public void write(int b) throws IOException {
                out.write(b);
            }
        };
    }

    @Override
    public PositionOutputStream createOrOverwrite(long blockSizeHint) throws IOException {
        return createPositionOutputstream();
    }

    @Override
    public boolean supportsBlockSize() {
        return false;
    }

    @Override
    public long defaultBlockSize() {
        return 0;
    }

}
</code>```

And your writer would be something like:

```<code>    ParquetBufferedWriter out = new ParquetBufferedWriter();
        try (ParquetWriter<Record> writer = AvroParquetWriter.
                <Record>builder(out)
                .withRowGroupSize(DEFAULT_BLOCK_SIZE)
                .withPageSize(DEFAULT_PAGE_SIZE)
                .withSchema(SCHEMA)
                .build()) {

            for (Record record : records) {
                writer.write(record);
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
</code>```

Title: Parquet Writer to buffer or byte stream

Body:
TLDR; you will need to implement OutputFile, e.g. something along the line of:

import org.apache.parquet.io.OutputFile;
import org.apache.parquet.io.PositionOutputStream;

import java.io.BufferedOutputStream;
import java.io.IOException;

public class ParquetBufferedWriter implements OutputFile {

    private final BufferedOutputStream out;

    public ParquetBufferedWriter(BufferedOutputStream out) {
        this.out = out;
    }

    @Override
    public PositionOutputStream create(long blockSizeHint) throws IOException {
        return createPositionOutputstream();
    }

    private PositionOutputStream createPositionOutputstream() {
        return new PositionOutputStream() {
            @Override
            public long getPos() throws IOException {
                return 0;
            }

            @Override
            public void write(int b) throws IOException {
                out.write(b);
            }
        };
    }

    @Override
    public PositionOutputStream createOrOverwrite(long blockSizeHint) throws IOException {
        return createPositionOutputstream();
    }

    @Override
    public boolean supportsBlockSize() {
        return false;
    }

    @Override
    public long defaultBlockSize() {
        return 0;
    }

}

And your writer would be something like:

    ParquetBufferedWriter out = new ParquetBufferedWriter();
        try (ParquetWriter<Record> writer = AvroParquetWriter.
                <Record>builder(out)
                .withRowGroupSize(DEFAULT_BLOCK_SIZE)
                .withPageSize(DEFAULT_PAGE_SIZE)
                .withSchema(SCHEMA)
                .build()) {

            for (Record record : records) {
                writer.write(record);
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }


问:
How To Return The Right of An Either
I have a value of this type:

List[Either[Error, Files]]
```

<p>and I have a function which checks if there are any errors like this:</p>

<pre class="lang-scala prettyprint-override"><code>  private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
    if(result.exists(p => p.isLeft)){
      Left(Error("some downloads failed"))
    }else{
      Right(
      Right(
        result.collect {
          case Right(value) => value
        }
      )

    }

  }
</code>```

Is this the best way to return the List of files if there are no errors in result?

答:
There's a cats libarary which has sequence extension method for doing such thing
https://gist.github.com/gbersac/14114f8bf8d0b1c6ea455aacdee0fcd8.

Title: How To Return The Right of An Either

Body:
I have a value of this type:

List[Either[Error, Files]]

and I have a function which checks if there are any errors like this:

  private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
    if(result.exists(p => p.isLeft)){
      Left(Error("some downloads failed"))
    }else{
      Right(
      Right(
        result.collect {
          case Right(value) => value
        }
      )

    }

  }

Is this the best way to return the List of files if there are no errors in result?


问:
Negative lookahead in strsplit puzzling behaviour
I am confused by a simple lookahead behaviour in strsplit in R v3.6.2: when I try to match a space () not followed by a forward-slash (/) the regex behaves oddly.

The below attempt correctly doesn't consume the forward-slash but still splits at the space afterwards. The output is the same with patterns: ' (?!/ )' and ' (?!/ *)', also with other wildcards . and ?.

```<code>strsplit(c("foo1 foo2", "foo1 / foo2", "foo1/foo2"), ' (?!/)', perl = T)
[[1]]
[1] "foo1" "foo2"

[[2]]
[1] "foo1 /" "foo2"

[[3]]
[1] "foo1/foo2"
</code>```

This is all the more confusing because if I negate a positive lookahead, strsplit simply won't split anything. This persists with different patterns as above.

```<code>strsplit(c("foo1 foo2", "foo1 / foo2", "foo1/foo2"), ' ^(?=/)', perl = T)
[[1]]
[1] "foo1 foo2"

[[2]]
[1] "foo1 / foo2"

[[3]]
[1] "foo1/foo2"
</code>```

Escaping the forward-slash (that shouldn't be a special character anyways) yields the same results.

The desired output should look like this:

```<code>[[1]]
[1] "foo1" "foo2"

[[2]]
[1] "foo1 / foo2"

[[3]]
[1] "foo1/foo2"
</code>```

Apologies if this is very basic, but I couldn't find an explanation for this specific behaviour.

答:
Your original regex does not work for you because the spaces after / are still matched.  (?!/) matches any space that is not directly followed with a /, but not if it is preceded with /.

You might try (?<!/) (?!/) - see this regex demo, but this will still match on spaces that are before  / or after / .

In order to match any 1+ whitespace chars but the cases when the whitespaces enclose a / char, you may use

```<code>strsplit(c("foo1 foo2", "foo1 / foo2", "foo1/foo2"), '\\s*/\\s*(*SKIP)(*F)|\\s+', perl=TRUE)
</code>```

The \s*/\s*(*SKIP)(*F)|\s+ (see its online demo) pattern matches

\s*/\s*(*SKIP)(*F)  - consumes 1+ whitespaces, / and then 1+ whitespaces and discards the match

| - or

\s+ - consumes 1+ whitespaces

Body:
I am confused by a simple lookahead behaviour in strsplit in R v3.6.2: when I try to match a space () not followed by a forward-slash (/) the regex behaves oddly.

The below attempt correctly doesn't consume the forward-slash but still splits at the space afterwards. The output is the same with patterns: ' (?!/ )' and ' (?!/ *)', also with other wildcards . and ?.

strsplit(c("foo1 foo2", "foo1 / foo2", "foo1/foo2"), ' (?!/)', perl = T)
[[1]]
[1] "foo1" "foo2"

[[2]]
[1] "foo1 /" "foo2"

[[3]]
[1] "foo1/foo2"

This is all the more confusing because if I negate a positive lookahead, strsplit simply won't split anything. This persists with different patterns as above.

strsplit(c("foo1 foo2", "foo1 / foo2", "foo1/foo2"), ' ^(?=/)', perl = T)
[[1]]
[1] "foo1 foo2"

[[2]]
[1] "foo1 / foo2"

[[3]]
[1] "foo1/foo2"

Escaping the forward-slash (that shouldn't be a special character anyways) yields the same results.

The desired output should look like this:

[[1]]
[1] "foo1" "foo2"

[[2]]
[1] "foo1 / foo2"

[[3]]
[1] "foo1/foo2"

Apologies if this is very basic, but I couldn't find an explanation for this specific behaviour.

Body:
Your original regex does not work for you because the spaces after / are still matched.  (?!/) matches any space that is not directly followed with a /, but not if it is preceded with /.

You might try (?<!/) (?!/) - see this regex demo, but this will still match on spaces that are before  / or after / .

In order to match any 1+ whitespace chars but the cases when the whitespaces enclose a / char, you may use

strsplit(c("foo1 foo2", "foo1 / foo2", "foo1/foo2"), '\\s*/\\s*(*SKIP)(*F)|\\s+', perl=TRUE)

The \s*/\s*(*SKIP)(*F)|\s+ (see its online demo) pattern matches

\s*/\s*(*SKIP)(*F)  - consumes 1+ whitespaces, / and then 1+ whitespaces and discards the match

| - or

\s+ - consumes 1+ whitespaces


问:
useState does not update the state
I'm trying to update a state using useState hook, however the state won't update. I've checked how to fix it but really have no idea about it what cause this point. This is the whole code I didnt include the urls and import files...

When onchange method trigger ilceZoom  function event has value so ı can get it evt.value example values is "1234" but I can not set it using useState future

```<code>const ilceUrl = 'URL';

const AddressSearchMaks = (props) => {
    useEffect(() => {
        ilceLoad();
    }, []);

    const [ ilceler, setIlceler ] = useState([]);
    const [ selectedIlce, setSelectedIlce ] = useState(null);

    let queryTask;
    let query;
    let sfs;
    let lineSymbol;
    let polygon;
    let polyline;
    let graphic;
    let extent;
    let point;
    let wMercatorUtils;
    let rfConverter;

    loadModules([
        'esri/tasks/query',
        'esri/tasks/QueryTask',
        'esri/symbols/SimpleFillSymbol',
        'esri/symbols/SimpleLineSymbol',
        'esri/geometry/Polygon',
        'esri/geometry/Polyline',
        'esri/geometry/webMercatorUtils',
        'esri/geometry/Extent',
        'esri/geometry/Point',
        'esri/graphic',
        'esri/Color',
        'libs/ReferenceConverter'
    ]).then(
        (
            [
                Query,
                QueryTask,
                SimpleFillSymbol,
                SimpleLineSymbol,
                Polygon,
                Polyline,
                webMercatorUtils,
                Extent,
                Point,
                Graphic,
                Color,
                referenceConverter
            ]
        ) => {
            queryTask = QueryTask;
            query = Query;
            polygon = Polygon;
            polyline = Polyline;
            graphic = Graphic;
            extent = Extent;
            point = Point;
            wMercatorUtils = webMercatorUtils;
            rfConverter = referenceConverter;
            sfs = new SimpleFillSymbol(
                SimpleFillSymbol.STYLE_SOLID,
                new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0, 255, 255 ]), 4),
                new Color([ 140, 140, 140, 0.25 ])
            );
            lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0, 255, 255 ]), 4).setWidth(4);
        }
    );

    const getAdres = async (url) => {
        let response = await fetch(url);
        let data = await response.json();
        let list = [];
        data.AdresList.Adresler.Adres.forEach((item) => {
            list.push({
                label: item.ADI,
                value: item.ID,
                lat: item.LAT,
                lon: item.LON
            });
        });
        return list;
    };

    async function ilceLoad() {
        let ilceList = await getAdres(ilceUrl);
        setIlceler(ilceList);
    }

    const convertExtent = (lat, lon) => {
        let p;
        let ext;
        const sr = props.map.spatialReference;
        if (sr.wkid == 102100) {
            const _p = wMercatorUtils.lngLatToXY(lon, lat);
            ext = extent({
                xmin: _p[0],
                ymin: _p[1],
                xmax: _p[0],
                ymax: _p[1],
                spatialReference: props.map.spatialReference
            });
        } else {
            const res = rfConverter.WgsToItrf(lat, lon);
            ext = extent({
                xmin: res.x,
                ymin: res.y,
                xmax: res.x,
                ymax: res.y,
                spatialReference: props.map.spatialReference
            });
            p = point(res.x, res.y);
        }
        p.spatialReference = sr;
        return ext;
    };

    const ilceZoom = (evt) => {
        setSelectedIlce(evt.value);
        console.log('selectedIlce', selectedIlce);
        setError(false);
        console.log('error', error);
        const qTask = queryTask(maksIlce);
        const q = query();
        q.returnGeometry = true;
        q.outFields = [ '*' ];
        q.outSpatialReference = { wkid: 5254 };
        q.where = `KIMLIKNO=${evt.value}`;
        qTask.execute(q, (evt) => {
            const polyGon = polygon({
                rings: evt.features[0].geometry.rings
            });
            props.map.graphics.add(graphic(polyGon, sfs));
        });
        const extent = convertExtent(evt.lat, evt.lon);
        props.map.setExtent(extent);
        mahalleLoad();
    };

    return (

            <Select name='adresSelect' options={ilceler} onChange={(e) => ilceZoom(e)} placeholder='İlçe Seçiniz' />

    );
};

const mapStateToProps = (state) => ({
    map: state.map.map
});

export default connect(mapStateToProps, null)(AddressSearchMaks);

</code>```

答:
Can you try like this. Because, in your code, you setting the data in selectedIlce, but before it re-render, your trying to checking the value in the console, so better use your console outside the event function, so that when it get updated, it will reflect in the console.</p>

```<code>    console.log('selectedIlce', selectedIlce);
    const ilceZoom = (evt) => {
       setSelectedIlce(evt.value);
       ....
    }

</code>```

Title: useState does not update the state

Body:
I'm trying to update a state using useState hook, however the state won't update. I've checked how to fix it but really have no idea about it what cause this point. This is the whole code I didnt include the urls and import files...

When onchange method trigger ilceZoom  function event has value so ı can get it evt.value example values is "1234" but I can not set it using useState future

const ilceUrl = 'URL';

const AddressSearchMaks = (props) => {
    useEffect(() => {
        ilceLoad();
    }, []);

    const [ ilceler, setIlceler ] = useState([]);
    const [ selectedIlce, setSelectedIlce ] = useState(null);

    let queryTask;
    let query;
    let sfs;
    let lineSymbol;
    let polygon;
    let polyline;
    let graphic;
    let extent;
    let point;
    let wMercatorUtils;
    let rfConverter;

    loadModules([
        'esri/tasks/query',
        'esri/tasks/QueryTask',
        'esri/symbols/SimpleFillSymbol',
        'esri/symbols/SimpleLineSymbol',
        'esri/geometry/Polygon',
        'esri/geometry/Polyline',
        'esri/geometry/webMercatorUtils',
        'esri/geometry/Extent',
        'esri/geometry/Point',
        'esri/graphic',
        'esri/Color',
        'libs/ReferenceConverter'
    ]).then(
        (
            [
                Query,
                QueryTask,
                SimpleFillSymbol,
                SimpleLineSymbol,
                Polygon,
                Polyline,
                webMercatorUtils,
                Extent,
                Point,
                Graphic,
                Color,
                referenceConverter
            ]
        ) => {
            queryTask = QueryTask;
            query = Query;
            polygon = Polygon;
            polyline = Polyline;
            graphic = Graphic;
            extent = Extent;
            point = Point;
            wMercatorUtils = webMercatorUtils;
            rfConverter = referenceConverter;
            sfs = new SimpleFillSymbol(
                SimpleFillSymbol.STYLE_SOLID,
                new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0, 255, 255 ]), 4),
                new Color([ 140, 140, 140, 0.25 ])
            );
            lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0, 255, 255 ]), 4).setWidth(4);
        }
    );

    const getAdres = async (url) => {
        let response = await fetch(url);
        let data = await response.json();
        let list = [];
        data.AdresList.Adresler.Adres.forEach((item) => {
            list.push({
                label: item.ADI,
                value: item.ID,
                lat: item.LAT,
                lon: item.LON
            });
        });
        return list;
    };

    async function ilceLoad() {
        let ilceList = await getAdres(ilceUrl);
        setIlceler(ilceList);
    }

    const convertExtent = (lat, lon) => {
        let p;
        let ext;
        const sr = props.map.spatialReference;
        if (sr.wkid == 102100) {
            const _p = wMercatorUtils.lngLatToXY(lon, lat);
            ext = extent({
                xmin: _p[0],
                ymin: _p[1],
                xmax: _p[0],
                ymax: _p[1],
                spatialReference: props.map.spatialReference
            });
        } else {
            const res = rfConverter.WgsToItrf(lat, lon);
            ext = extent({
                xmin: res.x,
                ymin: res.y,
                xmax: res.x,
                ymax: res.y,
                spatialReference: props.map.spatialReference
            });
            p = point(res.x, res.y);
        }
        p.spatialReference = sr;
        return ext;
    };

    const ilceZoom = (evt) => {
        setSelectedIlce(evt.value);
        console.log('selectedIlce', selectedIlce);
        setError(false);
        console.log('error', error);
        const qTask = queryTask(maksIlce);
        const q = query();
        q.returnGeometry = true;
        q.outFields = [ '*' ];
        q.outSpatialReference = { wkid: 5254 };
        q.where = `KIMLIKNO=${evt.value}`;
        qTask.execute(q, (evt) => {
            const polyGon = polygon({
                rings: evt.features[0].geometry.rings
            });
            props.map.graphics.add(graphic(polyGon, sfs));
        });
        const extent = convertExtent(evt.lat, evt.lon);
        props.map.setExtent(extent);
        mahalleLoad();
    };

    return (

            <Select name='adresSelect' options={ilceler} onChange={(e) => ilceZoom(e)} placeholder='İlçe Seçiniz' />

    );
};

const mapStateToProps = (state) => ({
    map: state.map.map
});

export default connect(mapStateToProps, null)(AddressSearchMaks);

Body:
Can you try like this. Because, in your code, you setting the data in selectedIlce, but before it re-render, your trying to checking the value in the console, so better use your console outside the event function, so that when it get updated, it will reflect in the console.

    console.log('selectedIlce', selectedIlce);
    const ilceZoom = (evt) => {
       setSelectedIlce(evt.value);
       ....
    }


问:
jQuery Drag And Drop Using Live Events
I have an application with a long list that changes frequently, and I need the items of that list to be draggable.

I've been using the jQuery UI draggable plugin, but it is slow to add to 400+ list items, and has to be re-added every time new list items are added.

Does anyone know of a plugin similar to the jQuery UI draggable plugin that uses jQuery 1.3's .live() events? This would solve both problems.

答:
Stldoug's code worked for me, but there's no need to keep checking the element's .data("init") on every mouseover event. Also, it's better to use "mousemove", as "mouseover" doesn't always get triggered if your mouse is already over the element when the .live function kicks in.

```<code>(function ($) {
    $.fn.liveDraggable = function (opts) {
        this.live("mousemove", function() {
            $(this).draggable(opts);
        });
    };
}(jQuery));
</code>```

Here's how you use it:

```<code>$('.thing:not(.ui-draggable)').liveDraggable();
</code>```

The trick is to add ":not(.ui-draggable)" to your selector. Since jQuery will automatically add the "ui-draggable" class to your element when it becomes draggable, the .live function will no longer target it. In other words, it only triggers once, unlike the other solution which triggers over and over as you move stuff around.

Ideally, you could just .unbind the "mousemove", but that doesn't work with .live, unfortunately.

Title: jQuery Drag And Drop Using Live Events

Body:
Stldoug's code worked for me, but there's no need to keep checking the element's .data("init") on every mouseover event. Also, it's better to use "mousemove", as "mouseover" doesn't always get triggered if your mouse is already over the element when the .live function kicks in.

(function ($) {
    $.fn.liveDraggable = function (opts) {
        this.live("mousemove", function() {
            $(this).draggable(opts);
        });
    };
}(jQuery));

Here's how you use it:

$('.thing:not(.ui-draggable)').liveDraggable();

The trick is to add ":not(.ui-draggable)" to your selector. Since jQuery will automatically add the "ui-draggable" class to your element when it becomes draggable, the .live function will no longer target it. In other words, it only triggers once, unlike the other solution which triggers over and over as you move stuff around.

Ideally, you could just .unbind the "mousemove", but that doesn't work with .live, unfortunately.


问:
Why is taking a slice of a list which is assigned to another list not changing the original?
I have a class that is a representation of a mathematical tensor. The tensor in the class, is stored as a single list, not lists inside another list. That means [[1, 2, 3], [4, 5, 6]] would be stored as [1, 2, 3, 4, 5, 6].

I've made a __setitem__() function and a function to handle taking slices of this tensor while it's in single list format. For example slice(1, None, None) would become slice(3, None, None) for the list mentioned above. However when I assign this slice a new value, the original tensor isn't updated.

Here is what the simplified code looks like

class Tensor:
    def __init__(self, tensor):
        self.tensor = tensor # Here I would flatten it, but for now imagine it's already flattened.

    def __setitem__(self, slices, value):
        slices = [slices]
        temp_tensor = self.tensor # any changes to temp_tensor should also change self.tensor.

        for s in slices: # Here I would call self.slices_to_index(), but this is to keep the code simple.
            temp_tensor = temp_tensor[slice]

        temp_tensor = value # In my mind, this should have also changed self.tensor, but it hasn't.

```

Maybe i'm just being stupid and can't see why this isn't working. Maybe my actual questions isn't just ' why doesn't this work?' but also 'is there a better way to do this?'. Thanks for any help you can give me.

NOTES:

Each 'dimension' of the list must have the same shape, so [[1, 2, 3], [4, 5]] isn't allowed.

This code is massively simplified as there are many other helper functions and stuff like that.

in __init__() I would flatten the list but as I just said to keep things simple I left that out, along with self.slice_to_index().

答:
You should not think of python variables as in c++ or java. Think of them as labels you place on values. Check this example:

```<code>>>> l = []
>>> l.append
<built-in method append of list object at 0x7fbb0d40cf88>
>>> l.append(10)
>>> l
[10]
>>> ll = l
>>> ll.append(10)
>>> l
[10, 10]
>>> ll
[10, 10]
>>> ll = ["foo"]
>>> l
[10, 10]
</code>```

As you can see, ll variable first points to the same l list but later we just make it point to another list. Modifying the later ll won't modify the original list pointed by l.

So, in your case if you want self.tensor to point to a new value, just do it:

```<code>class Tensor:
    def __init__(self, tensor):
        self.tensor = tensor # Here I would flatten it, but for now imagine it's already flattened.

    def __setitem__(self, slices, value):
        slices = [slices]
        temp_tensor = self.tensor # any changes to the list pointed by temp_tensor will be reflected in self.tensor since it is the same list

        for s in slices:
            temp_tensor = temp_tensor[slice]

        self.tensor = value
</code>```

Body:
I have a class that is a representation of a mathematical tensor. The tensor in the class, is stored as a single list, not lists inside another list. That means [[1, 2, 3], [4, 5, 6]] would be stored as [1, 2, 3, 4, 5, 6].

I've made a __setitem__() function and a function to handle taking slices of this tensor while it's in single list format. For example slice(1, None, None) would become slice(3, None, None) for the list mentioned above. However when I assign this slice a new value, the original tensor isn't updated.

Here is what the simplified code looks like

class Tensor:
    def __init__(self, tensor):
        self.tensor = tensor # Here I would flatten it, but for now imagine it's already flattened.

    def __setitem__(self, slices, value):
        slices = [slices]
        temp_tensor = self.tensor # any changes to temp_tensor should also change self.tensor.

        for s in slices: # Here I would call self.slices_to_index(), but this is to keep the code simple.
            temp_tensor = temp_tensor[slice]

        temp_tensor = value # In my mind, this should have also changed self.tensor, but it hasn't.

Maybe i'm just being stupid and can't see why this isn't working. Maybe my actual questions isn't just ' why doesn't this work?' but also 'is there a better way to do this?'. Thanks for any help you can give me.

NOTES:

Each 'dimension' of the list must have the same shape, so [[1, 2, 3], [4, 5]] isn't allowed.

This code is massively simplified as there are many other helper functions and stuff like that.

in __init__() I would flatten the list but as I just said to keep things simple I left that out, along with self.slice_to_index().

Body:
You should not think of python variables as in c++ or java. Think of them as labels you place on values. Check this example:

>>> l = []
>>> l.append
<built-in method append of list object at 0x7fbb0d40cf88>
>>> l.append(10)
>>> l
[10]
>>> ll = l
>>> ll.append(10)
>>> l
[10, 10]
>>> ll
[10, 10]
>>> ll = ["foo"]
>>> l
[10, 10]

As you can see, ll variable first points to the same l list but later we just make it point to another list. Modifying the later ll won't modify the original list pointed by l.

So, in your case if you want self.tensor to point to a new value, just do it:

class Tensor:
    def __init__(self, tensor):
        self.tensor = tensor # Here I would flatten it, but for now imagine it's already flattened.

    def __setitem__(self, slices, value):
        slices = [slices]
        temp_tensor = self.tensor # any changes to the list pointed by temp_tensor will be reflected in self.tensor since it is the same list

        for s in slices:
            temp_tensor = temp_tensor[slice]

        self.tensor = value


问:
Send Slack notification when API Gateway return error 500
I have some API on API Gateway and i would like to have notification when an API return error 500

I would like to have a slack notification with the name of the API and the returned error. If someone know how to do that, I will be grateful to him

Thanks in advance

答:
Create an alarm on 5XXError metric: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-metrics-and-dimensions.html

You can then use AWS Chatbot to deliver a message to Slack every time the alarm fires: https://aws.amazon.com/blogs/devops/introducing-aws-chatbot-chatops-for-aws/


问:
Runtime warning CLSUserDefaults is implemented twice
I have seen a similar warning to that below for a pod-defined class when using #import  syntax in cocoapod sources, but this is an internal apple class definition (CLSUserDefaults) which I have no control over and am not subclassing.

I don't know if this is really causing a problem, but it shouldn't be happening.

```<code>objc[22040]: Class CLSUserDefaults is implemented in both
/System/Library/PrivateFrameworks/ClassKit.framework/Versions/A/ClassKit (0x7fff9932d2c0) and

/Users/devusrid1/Library/Developer/Xcode/DerivedData/MyApp-cdokjmhxdrnhuodmhtibejxyqmqt/Build/Products/Debug/USR ID MyApp.app/Contents/MacOS/My App (0x10057f340).

One of the two will be used. Which one is undefined.
</code>```

I'm using Xcode 11

答:
In my case same error showed (Just in iOS 13), but used another way to solve this:

I removed Fabric and Crashlytics from project (with uses in app)

Then error message changed! (There was two errors: One for RemoteNotification and one for using statusBar in AppDelegate)

I solved first using this: https://stackoverflow.com/a/45440917/5853262

Then solved second with commenting this line in AppDelegate: UIApplication.statusBarBackgroundColor = navigationBarColor

Then I reverted code to before doing step 1 using git(Before Removing Fabric and Crashlytics)

Then I fixed errors that not shown (Doing step 3 and 4)

After Clean and Build, the app launched successfully.

Notice: In your case maybe another error causes this problem, but when Fabric and Crashlytics exist, Xcode doesn't shows them. as I did, remove them, fix errors, then rollback changes and just fix bugs that you know. This would be work.

Body:
I have seen a similar warning to that below for a pod-defined class when using #import  syntax in cocoapod sources, but this is an internal apple class definition (CLSUserDefaults) which I have no control over and am not subclassing.

I don't know if this is really causing a problem, but it shouldn't be happening.

objc[22040]: Class CLSUserDefaults is implemented in both
/System/Library/PrivateFrameworks/ClassKit.framework/Versions/A/ClassKit (0x7fff9932d2c0) and

/Users/devusrid1/Library/Developer/Xcode/DerivedData/MyApp-cdokjmhxdrnhuodmhtibejxyqmqt/Build/Products/Debug/USR ID MyApp.app/Contents/MacOS/My App (0x10057f340).

One of the two will be used. Which one is undefined.

I'm using Xcode 11


问:
Using a font-awesome icon in jquery ui dialog
```<code>$('.toggle').click(function () {
    $('.d').dialog();
    $('.ui-dialog-titlebar-close').addClass('icon-remove');
});
</code>```

Using above code I have to write $('.ui-dialog-titlebar-close').addClass('icon-remove');
for every dialog. I could also use onload event for adding a class to dynamically created elements. But is there any better solution? Any solution that only use css or scss?

答:
With fontawesome 5, this can be achieved by:

```<code>.ui-icon-closethick {
  text-indent: 0;
}

.ui-icon-closethick::after {
  text-indent: 0;
  font-family: 'Font Awesome 5 Free';
  font-weight: 900;
  content: "\f00d";
}
</code>```

See:
https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements

Body:
$('.toggle').click(function () {
    $('.d').dialog();
    $('.ui-dialog-titlebar-close').addClass('icon-remove');
});

Using above code I have to write $('.ui-dialog-titlebar-close').addClass('icon-remove');
for every dialog. I could also use onload event for adding a class to dynamically created elements. But is there any better solution? Any solution that only use css or scss?

Body:
With fontawesome 5, this can be achieved by:

.ui-icon-closethick {
  text-indent: 0;
}

.ui-icon-closethick::after {
  text-indent: 0;
  font-family: 'Font Awesome 5 Free';
  font-weight: 900;
  content: "\f00d";
}

See:
https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements


问:
AWS Lambda (.NET) + SQS: Error converting the Lambda event JSON payload to a string
i use AWS Lambda (.NET Core 2.1 environment) + SQS as trigger

The problem is that my lambda cannot parse my SQS message.

Error converting the Lambda event JSON payload to a string. JSON
  strings must be quoted, for example "Hello World" in order to be
  converted to a string: Unexpected character encountered while parsing
  value: {. Path '', line 1, position 1.: JsonSerializerException

Here is declaration of my handler:

```<code>public async Task<string> FunctionHandler(DummyMessage message, ILambdaContext context)
</code>```

Model:

```<code>public class DummyMessage {
  public string Label { get; set; }
}
</code>```

SQS input from AWS Console that I tried: {"Label":"qwerty"}, "{"Label":"qwerty"}", "{\"Label\":\"qwerty\"}", but same error occurs.

Could you please help with this issue?

答:
When passing Json try JObject from Newtonsoft.Json.Linq

```<code>FunctionHandler(JObject eventStr, ILambdaContext context)
</code>```

and then you can Deseralize the response where SQSEvent is inherited from Amazon.Lambda.SQSEvents SDK Library.

```<code>var result = eventStr.ToObject<SQSEvent>();
</code>```

Body:
i use AWS Lambda (.NET Core 2.1 environment) + SQS as trigger

The problem is that my lambda cannot parse my SQS message.

Error converting the Lambda event JSON payload to a string. JSON
  strings must be quoted, for example "Hello World" in order to be
  converted to a string: Unexpected character encountered while parsing
  value: {. Path '', line 1, position 1.: JsonSerializerException

Here is declaration of my handler:

public async Task<string> FunctionHandler(DummyMessage message, ILambdaContext context)

Model:

public class DummyMessage {
  public string Label { get; set; }
}

SQS input from AWS Console that I tried: {"Label":"qwerty"}, "{"Label":"qwerty"}", "{\"Label\":\"qwerty\"}", but same error occurs.

Could you please help with this issue?

Body:
When passing Json try JObject from Newtonsoft.Json.Linq

FunctionHandler(JObject eventStr, ILambdaContext context)

and then you can Deseralize the response where SQSEvent is inherited from Amazon.Lambda.SQSEvents SDK Library.

var result = eventStr.ToObject<SQSEvent>();


问:
Dialog box is not closing flutter
Here's my Alert dialog code: I've added Navigator.pop(context); in the tapped method call. But it's not closing.

```<code> showLoginDialog(BuildContext context,
  {TextEditingController usernameController,
  TextEditingController loginController}) {
var textController = new TextEditingController();
var nameTextController = new TextEditingController();
String dateToPost;
Alert(
    context: context,
    title: "Add Profile",
    content: Column(
      children: <Widget>[
        TextField(
          controller: nameTextController,
          decoration: InputDecoration(
            labelText: 'Name',
          ),
        ),
        TextField(
          controller: textController,
          onTap: () async {
            DateTime date = DateTime(1900);
            //FocusScope.of(context).requestFocus(new FocusNode());

            date = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: DateTime(1900),
                lastDate: DateTime.now());

            var formatter = new DateFormat('dd MMM yyyy');
            var formatterToPost = new DateFormat('yyyy-MM-dd');
            String formatted = formatter.format(date);
            dateToPost = formatterToPost.format(date);
            print(formatted);

            textController.text = formatted;
          },
          decoration: InputDecoration(
            labelText: 'Birth Date',
          ),
        ),
      ],
    ),
    buttons: [
      DialogButton(
        onPressed: () {
          Navigator.pop(context);
           _saveData(textController.text, nameTextController.text,
               dateToPost);
        },
        child: Text(
          "Add",
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
      )
    ]).show();
</code>```

}

Also, is shows error on second time click: The method 'call' was called on null.
Receiver: null
Tried calling: call()

答:
You should save the data before you close the application.

And instead of Navigator.pop(context) do Navigator.of(context).pop(true)

```<code>onPressed: () {
    _saveData(textController.text, nameTextController.text,
     dateToPost);
    Navigator.of(context).pop(true);
}
</code>```

Title: Dialog box is not closing flutter

Body:
Here's my Alert dialog code: I've added Navigator.pop(context); in the tapped method call. But it's not closing.

 showLoginDialog(BuildContext context,
  {TextEditingController usernameController,
  TextEditingController loginController}) {
var textController = new TextEditingController();
var nameTextController = new TextEditingController();
String dateToPost;
Alert(
    context: context,
    title: "Add Profile",
    content: Column(
      children: <Widget>[
        TextField(
          controller: nameTextController,
          decoration: InputDecoration(
            labelText: 'Name',
          ),
        ),
        TextField(
          controller: textController,
          onTap: () async {
            DateTime date = DateTime(1900);
            //FocusScope.of(context).requestFocus(new FocusNode());

            date = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: DateTime(1900),
                lastDate: DateTime.now());

            var formatter = new DateFormat('dd MMM yyyy');
            var formatterToPost = new DateFormat('yyyy-MM-dd');
            String formatted = formatter.format(date);
            dateToPost = formatterToPost.format(date);
            print(formatted);

            textController.text = formatted;
          },
          decoration: InputDecoration(
            labelText: 'Birth Date',
          ),
        ),
      ],
    ),
    buttons: [
      DialogButton(
        onPressed: () {
          Navigator.pop(context);
           _saveData(textController.text, nameTextController.text,
               dateToPost);
        },
        child: Text(
          "Add",
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
      )
    ]).show();

}

Also, is shows error on second time click: The method 'call' was called on null.
Receiver: null
Tried calling: call()

Body:
You should save the data before you close the application.

And instead of Navigator.pop(context) do Navigator.of(context).pop(true)

onPressed: () {
    _saveData(textController.text, nameTextController.text,
     dateToPost);
    Navigator.of(context).pop(true);
}


问:
Azure Kusto Data Explorer - convert duration to days
Is there a way to find number of days from timespan?

For example,
time(00:00:00.2000000), time(00:30:30), time(01:00:00), time(413.00:00:00)
should return 0, 0, 0, 413

答:
An alternative way would be to divide the timespan by the a day, for example:</p>

```<code>datatable(t:timespan) [ time(00:00:00.2000000), time(00:30:30), time(01:00:00), time(413.00:00:00)]
| extend Days = tolong(t/1d)
</code>```

Body:
An alternative way would be to divide the timespan by the a day, for example:

datatable(t:timespan) [ time(00:00:00.2000000), time(00:30:30), time(01:00:00), time(413.00:00:00)]
| extend Days = tolong(t/1d)


问:
Wordpress: search users using 'first_name' and 'last_name'?
UPDATE: I mean to search user in the Admin User Dashboard at /wp-admin/users.php

Is there a way to search users using 'first_name' and 'last_name'?

I found this plugin but not working at all: https://wordpress.org/plugins/full-name-search-in-wp-admin/

I also found this function, but neither is working in my site. Do I need to call the function with a hook/action?:

```<code>function search_users($search_term){

    global $wpdb;
    $the_users = $wpdb->get_results("SELECT DISTINCT $wpdb->users.* FROM $wpdb->users INNER JOIN $wpdb->usermeta um1 ON um1.user_id = $wpdb->users.ID JOIN $wpdb->usermeta um2 ON um2.user_id = $wpdb->users.ID WHERE (um1.meta_key = 'uRPhICRS_capabilities' AND um1.meta_value LIKE '%agent%') AND ((um2.meta_key = 'first_name' OR um2.meta_key = 'last_name') AND um2.meta_value LIKE '%".$search_term."%');");

    if(!empty($the_users)){
        return $the_users;
    }
    else{
        return false;
    }

}
</code>```

答:
You can use WP_User_Query.

Example:

```<code>// The search term
$search_term = 'Ross';

// WP_User_Query arguments
$args = array (
    'role' => 'reporter',
    'order' => 'ASC',
    'orderby' => 'display_name',
    'search' => '*'.esc_attr( $search_term ).'*',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'     => 'first_name',
            'value'   => $search_term,
            'compare' => 'LIKE'
        ),
        array(
            'key'     => 'last_name',
            'value'   => $search_term,
            'compare' => 'LIKE'
        ),
        array(
            'key' => 'description',
            'value' => $search_term ,
            'compare' => 'LIKE'
        )
    )
);

// Create the WP_User_Query object
$wp_user_query = new WP_User_Query($args);
</code>```

https://developer.wordpress.org/reference/classes/wp_user_query/

Body:
UPDATE: I mean to search user in the Admin User Dashboard at /wp-admin/users.php

Is there a way to search users using 'first_name' and 'last_name'?

I found this plugin but not working at all: https://wordpress.org/plugins/full-name-search-in-wp-admin/

I also found this function, but neither is working in my site. Do I need to call the function with a hook/action?:

function search_users($search_term){

    global $wpdb;
    $the_users = $wpdb->get_results("SELECT DISTINCT $wpdb->users.* FROM $wpdb->users INNER JOIN $wpdb->usermeta um1 ON um1.user_id = $wpdb->users.ID JOIN $wpdb->usermeta um2 ON um2.user_id = $wpdb->users.ID WHERE (um1.meta_key = 'uRPhICRS_capabilities' AND um1.meta_value LIKE '%agent%') AND ((um2.meta_key = 'first_name' OR um2.meta_key = 'last_name') AND um2.meta_value LIKE '%".$search_term."%');");

    if(!empty($the_users)){
        return $the_users;
    }
    else{
        return false;
    }

}

Body:
You can use WP_User_Query.

Example:

// The search term
$search_term = 'Ross';

// WP_User_Query arguments
$args = array (
    'role' => 'reporter',
    'order' => 'ASC',
    'orderby' => 'display_name',
    'search' => '*'.esc_attr( $search_term ).'*',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'     => 'first_name',
            'value'   => $search_term,
            'compare' => 'LIKE'
        ),
        array(
            'key'     => 'last_name',
            'value'   => $search_term,
            'compare' => 'LIKE'
        ),
        array(
            'key' => 'description',
            'value' => $search_term ,
            'compare' => 'LIKE'
        )
    )
);

// Create the WP_User_Query object
$wp_user_query = new WP_User_Query($args);

https://developer.wordpress.org/reference/classes/wp_user_query/


问:
How to make rounded corner triangle in XAML
How can I make a rounded corner triangle in XAML-Silverlight?</p>

答:
I think the below Path will solve your problem, Only you need to change the points of your triangle according to your requirement. For more idea about Path </p>

```<code> <Path Data="M 300 100 L 500 400 100 400 Z"
            StrokeThickness="48"
            StrokeLineJoin="Round"
            Stroke="Blue"
            Fill="Blue" />
</code>```

Body:
I think the below Path will solve your problem, Only you need to change the points of your triangle according to your requirement. For more idea about Path

 <Path Data="M 300 100 L 500 400 100 400 Z"
            StrokeThickness="48"
            StrokeLineJoin="Round"
            Stroke="Blue"
            Fill="Blue" />


问:
For-loop logic in order to print an inputed character using scanf n number of times
I've been trying to understand the logic behind this for loop but I've been unable to. The problem asks to input an integer n (number of test cases) followed by n number of characters with each characters denoting the day of the week. So I need to output the day n number of times.

```<code>#include <stdio.h>
int main()
{
    int n, i;
    char ch;

    scanf("%d",&n);

    for (i = 0; i < 2 * n; i += 1)
    {
        scanf("%c", &ch);
        switch (ch)
        {
        case 'M':
            printf("Monday\n");
            break;
        case 'T':
            printf("Tuesday\n");
            break;
        case 'W':
            printf("Wednesday\n");
            break;
        case 'H':
            printf("Thursday\n");
            break;
        case 'F':
            printf("Friday\n");
            break;
        case 'S':
            printf("Saturday\n");
            break;
        case 'N':
            printf("Sunday\n");
            break;
        }
    }
    return 0;
}
</code>```

I don't understand the logic for i<2*n. So for example when I input n=2 followed by characters M M, and i is initialized to 0, the condition for 0 < 4 is checked which is true so the first character M is input, and Monday is printed once, now i is incremented to 1 and is checked against 1 < 4 which is true and is printed once again. Now it has already been printed twice, but according to the i < 2 * n logic shouldn't Monday get printed 4 times until 4 < 4 terminates the for loop?

But this logic somehow works correctly.

My logic for i <= n, for some reason does not work and only inputs and prints the character the one time. Where am I going wrong here?

答:
scanf("%c", &ch); scans the character you input but the \n newline character, caused by the enter, remains on the buffer, (the same is true for the previous scanf in your code), this causes the for loop to run 2 times for every input: first, it scans the character itself and then the \n. This is the reason why your for loop needs to run 4 times instead of the 2 it should.

You will need to discard those \n characters. You can use %*c to discard them, then you can replace n*2 with n in the for loop, the advantage is that the loop runs only half of the times you have now.

This works, not only for block input separated by space, but also for one at a time inputs.

Link to live sample

```<code>//...
scanf("%d%*c", &n); //<-- dicard newline character

for (i = 0; i < n ; i += 1) {
    scanf("%c%*c", &ch); //<-- discard newline character
//...
</code>```

Body:
I've been trying to understand the logic behind this for loop but I've been unable to. The problem asks to input an integer n (number of test cases) followed by n number of characters with each characters denoting the day of the week. So I need to output the day n number of times.

#include <stdio.h>
int main()
{
    int n, i;
    char ch;

    scanf("%d",&n);

    for (i = 0; i < 2 * n; i += 1)
    {
        scanf("%c", &ch);
        switch (ch)
        {
        case 'M':
            printf("Monday\n");
            break;
        case 'T':
            printf("Tuesday\n");
            break;
        case 'W':
            printf("Wednesday\n");
            break;
        case 'H':
            printf("Thursday\n");
            break;
        case 'F':
            printf("Friday\n");
            break;
        case 'S':
            printf("Saturday\n");
            break;
        case 'N':
            printf("Sunday\n");
            break;
        }
    }
    return 0;
}

I don't understand the logic for i<2*n. So for example when I input n=2 followed by characters M M, and i is initialized to 0, the condition for 0 < 4 is checked which is true so the first character M is input, and Monday is printed once, now i is incremented to 1 and is checked against 1 < 4 which is true and is printed once again. Now it has already been printed twice, but according to the i < 2 * n logic shouldn't Monday get printed 4 times until 4 < 4 terminates the for loop?

But this logic somehow works correctly.

My logic for i <= n, for some reason does not work and only inputs and prints the character the one time. Where am I going wrong here?

Body:
scanf("%c", &ch); scans the character you input but the \n newline character, caused by the enter, remains on the buffer, (the same is true for the previous scanf in your code), this causes the for loop to run 2 times for every input: first, it scans the character itself and then the \n. This is the reason why your for loop needs to run 4 times instead of the 2 it should.

You will need to discard those \n characters. You can use %*c to discard them, then you can replace n*2 with n in the for loop, the advantage is that the loop runs only half of the times you have now.

This works, not only for block input separated by space, but also for one at a time inputs.

Link to live sample

//...
scanf("%d%*c", &n); //<-- dicard newline character

for (i = 0; i < n ; i += 1) {
    scanf("%c%*c", &ch); //<-- discard newline character
//...


问:
Is it possible to pass an argument to a computed property that is used for class and style bindings?
I have an array of travelers (e.g. [2,0,0] => 2 adults, 0 teens, 0 childs) that I use to build my template

```<code><div v-for="(person, i) in travelers" :key="i" class="uk-width-1-3@m">
    <div class="uk-card-body">
        <button
            class="uk-button uk-button-small uk-margin-right"
            @click="changeTravelers({index: i, value: travelers[i]-1})"
            :class="{
                 'uk-disabled uk-button-default': travelers[i] == 0 || (curOcc !== 1 && curOcc <= minOcc),
                 'uk-button-primary': travelers[i] > 0 && (curOcc > minOcc || curOcc >= minOcc && travelers[i] === 1 && travelers[i+1] !== 1 && travelers[i+2] !== 1 && travelers[i-1] !== 1 && travelers[i-2] !== 1)
             }"
        >-</button>
        <span>{{ travelers[i] }}</span>
        <button
            class="uk-button uk-button-small uk-margin-left"
            @click="changeTravelers({index: i, value: travelers[i]+1})"
            :class="{'uk-disabled uk-button-default': curOcc >= maxOcc, 'uk-button-primary': curOcc < maxOcc}"
        >+</button>
    </div>
</div>
</code>```

I guess it's bad practice to implement so much logic into the template and it look's really awkward. Instead I want to use class and style bindings with an computed property.

```<code>styleMinusButton() {
    return {
        'uk-disabled uk-button-default': this.travelers[i] == 0 || (curOcc !== 1 && curOcc <= minOcc),
        'uk-button-primary': travelers[i] > 0 && (curOcc > minOcc || curOcc >= minOcc && travelers[i] === 1 && travelers[i+1] !== 1 && travelers[i+2] !== 1 && travelers[i-1] !== 1 && travelers[i-2] !== 1)
    }
}
</code>```

But how do I access the i of the v-for? Can I pass it as an argument? Or is there a different and better solution?

Thanks in advance!

答:
If you need arguments then you want to write a method, not a computed property.

<button :class="styleMinusButton(i)">...</button>
```

<pre class="lang-js prettyprint-override"><code>methods: {
  styleMinusButton(i) {
    const { travelers, curOcc, minOcc } = this
    return {
      'uk-disabled uk-button-default': travelers[i] == 0 || (curOcc !== 1 && curOcc <= minOcc),
      'uk-button-primary': travelers[i] > 0 && (curOcc > minOcc || curOcc >= minOcc && travelers[i] === 1 && travelers[i+1] !== 1 && travelers[i+2] !== 1 && travelers[i-1] !== 1 && travelers[i-2] !== 1)
    }
  }
}
</code>```

Body:
I have an array of travelers (e.g. [2,0,0] => 2 adults, 0 teens, 0 childs) that I use to build my template

        <button
            class="uk-button uk-button-small uk-margin-right"
            @click="changeTravelers({index: i, value: travelers[i]-1})"
            :class="{
                 'uk-disabled uk-button-default': travelers[i] == 0 || (curOcc !== 1 && curOcc <= minOcc),
                 'uk-button-primary': travelers[i] > 0 && (curOcc > minOcc || curOcc >= minOcc && travelers[i] === 1 && travelers[i+1] !== 1 && travelers[i+2] !== 1 && travelers[i-1] !== 1 && travelers[i-2] !== 1)
             }"
        >-</button>
        {{ travelers[i] }}
        <button
            class="uk-button uk-button-small uk-margin-left"
            @click="changeTravelers({index: i, value: travelers[i]+1})"
            :class="{'uk-disabled uk-button-default': curOcc >= maxOcc, 'uk-button-primary': curOcc < maxOcc}"
        >+</button>

I guess it's bad practice to implement so much logic into the template and it look's really awkward. Instead I want to use class and style bindings with an computed property.

styleMinusButton() {
    return {
        'uk-disabled uk-button-default': this.travelers[i] == 0 || (curOcc !== 1 && curOcc <= minOcc),
        'uk-button-primary': travelers[i] > 0 && (curOcc > minOcc || curOcc >= minOcc && travelers[i] === 1 && travelers[i+1] !== 1 && travelers[i+2] !== 1 && travelers[i-1] !== 1 && travelers[i-2] !== 1)
    }
}

But how do I access the i of the v-for? Can I pass it as an argument? Or is there a different and better solution?

Thanks in advance!

Body:
If you need arguments then you want to write a method, not a computed property.

<button :class="styleMinusButton(i)">...</button>

methods: {
  styleMinusButton(i) {
    const { travelers, curOcc, minOcc } = this
    return {
      'uk-disabled uk-button-default': travelers[i] == 0 || (curOcc !== 1 && curOcc <= minOcc),
      'uk-button-primary': travelers[i] > 0 && (curOcc > minOcc || curOcc >= minOcc && travelers[i] === 1 && travelers[i+1] !== 1 && travelers[i+2] !== 1 && travelers[i-1] !== 1 && travelers[i-2] !== 1)
    }
  }
}


问:
PHP Jquery Ajax call throws net::ERR_EMPTY_RESPONSE
I have the following JavaScript code in the page. When the ajax call is made, I could see that the browser inspect/debugger section throws net::ERR_EMPTY_RESPONSE error. It works fine in localhost environment but throws above error in production.

In client side code,

```<code><script>
$(document).ready(function(){
    $("#identityLinks a").on("click", function(){
    value = $(this).attr("id");
    if(value != "")
    {
        $.ajax({
            url:  "publish/updateUsersData.php",
            type: "POST",
            data: {receiverId: value},
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            dataType: "json",
            success: function(data) {
              //alert(data["result"]);
              console.log(data["result"]);
            },
            error: function(xhr, textStatus, errorThrown) {
               //alert(xhr +" "+ textStatus +" "+errorThrown);
               console.log(xhr +" "+ textStatus);
            }
        });
    }
    });
</script>
</code>```

In Server-side code (PHP), I have the following code in updateUsersData.php:

```<code><?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 1996 00:00:00 GMT');
header('Content-type: application/json; charset=UTF-8');
if(isset($_POST["receiverId"]))
{
    $receiver_id = trim($_POST["receiverId"]);
    $arr = array("result"=>$receiver_id);
    echo json_encode($arr); die();
    break;
}
else
{
    $arr = array("result"=>"No user data received. Error!");
    echo json_encode($arr); die();
    break;
}
?>
</code>```

Do you think it's due to header with Expire calls or a bug in Jquery 1.9.1 version? I didn't find such errors when we were previous versions. Also, this code has not been updated for 5 months and browser errors creep just some time ago. Thanks for all your help and support.

Edit:

Status : This ISSUE is not resolved so far. Jquery AJAX experts' help needed. Anyone, please promote this question. Also, CORS is not responsible for this issue.

When clicking on the console in which the above error occurred, I was directly taken to this line in

```<code>JQuery 1.9.1 where console error lines point to:

=> xhr.send( ( s.hasContent && s.data ) || null );

Also these ones are shown in console error mark:

=> transport.send( requestHeaders, done );

=> ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle
   || handleObj.handler )
  .apply( matched.elem, args );

=> return typeof jQuery !== core_strundefined &&
(!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined;
</code>```

Is jquery latest version responsible for this PROVISIONAL HEADERS ARE SHOWN error.

答: I had same problem. i tried many solution advice but nothing worked. Finally i was able to fix this issue by using Ajax Get method instead post. But prefer this if you dont send sensitive data.</p>

Body:
I have the following JavaScript code in the page. When the ajax call is made, I could see that the browser inspect/debugger section throws net::ERR_EMPTY_RESPONSE error. It works fine in localhost environment but throws above error in production.

In client side code,

In Server-side code (PHP), I have the following code in updateUsersData.php:

<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 1996 00:00:00 GMT');
header('Content-type: application/json; charset=UTF-8');
if(isset($_POST["receiverId"]))
{
    $receiver_id = trim($_POST["receiverId"]);
    $arr = array("result"=>$receiver_id);
    echo json_encode($arr); die();
    break;
}
else
{
    $arr = array("result"=>"No user data received. Error!");
    echo json_encode($arr); die();
    break;
}
?>

Do you think it's due to header with Expire calls or a bug in Jquery 1.9.1 version? I didn't find such errors when we were previous versions. Also, this code has not been updated for 5 months and browser errors creep just some time ago. Thanks for all your help and support.

Edit:

Status : This ISSUE is not resolved so far. Jquery AJAX experts' help needed. Anyone, please promote this question. Also, CORS is not responsible for this issue.

When clicking on the console in which the above error occurred, I was directly taken to this line in

JQuery 1.9.1 where console error lines point to:

=> xhr.send( ( s.hasContent && s.data ) || null );

Also these ones are shown in console error mark:

=> transport.send( requestHeaders, done );

=> ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle
   || handleObj.handler )
  .apply( matched.elem, args );

=> return typeof jQuery !== core_strundefined &&
(!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined;

Is jquery latest version responsible for this PROVISIONAL HEADERS ARE SHOWN error.


问:
Invoke-AzVMRunCommand log output, error handling
Once we run command "Invoke-AzVMRunCommand" to execute a PS script on a remote VM, it always succeeds even it actually fails. I know remote VM has the log file there:

"C:\Packages\Plugins\Microsoft.CPlat.Core.RunCommandWindows\1.1.3\Status"

The problem:

But how to retrieve the error on a local powershell, try-catch etc. does not show it.
What is a proper error handling using "Invoke-AzVMRunCommand", ideally getting results in .txt, something like:

| Out-File -Filepath xxx.txt

thank you.

答:
Eventually after long testing, I end up with this solution, which throws an error from remote script execution and logs it in .txt file:</p>

```<code>$result = Invoke-AzVMRunCommand -ErrorAction Stop -ResourceGroupName "MyRg" -Name "MyVM" -CommandId 'RunPowerShellScript' -ScriptPath MyScript.ps1
Remove-Item -path script.ps1

if ($result.value.Message -like '*error*')
{

    Write-Output "Failed. An error occurred: `n $($result.value.Message)" | Out-File -Filepath C:\OutputLog.txt -Append
    throw $($result.value.Message)
}
else
{
    Write-Output "Success" | Out-File -Filepath C:\OutputLog.txt -Append
}
</code>```

Body:
Eventually after long testing, I end up with this solution, which throws an error from remote script execution and logs it in .txt file:

$result = Invoke-AzVMRunCommand -ErrorAction Stop -ResourceGroupName "MyRg" -Name "MyVM" -CommandId 'RunPowerShellScript' -ScriptPath MyScript.ps1
Remove-Item -path script.ps1

if ($result.value.Message -like '*error*')
{

    Write-Output "Failed. An error occurred: `n $($result.value.Message)" | Out-File -Filepath C:\OutputLog.txt -Append
    throw $($result.value.Message)
}
else
{
    Write-Output "Success" | Out-File -Filepath C:\OutputLog.txt -Append
}


问:
may COM server reallocate ([in, out] CACLSID * arg)?
With a COM interface method declared as this:

```<code>[ object,
  uuid(....),
]
interface IFoo : IUnknown
{
  HRESULT Foo([in, out] CACLSID * items);
}
</code>```

With regards to marshalling, is the server allowed to reallocate the counted array? (I think it is, but I am not sure anymore)

Its current implementation only replaces the existing ID's, but I'd like to implement a change (that would not break contract) that may return more items without introducing a new interface.

[edit] please note that CACLSID is already an array, containing a count and a pointer.

答: You should give the Count as the second parameter which indicates the space for so many number of elements, using this COM library marshals the elements</p>

OwnerDisplayName: peterchen

Body:
With a COM interface method declared as this:

[ object,
  uuid(....),
]
interface IFoo : IUnknown
{
  HRESULT Foo([in, out] CACLSID * items);
}

With regards to marshalling, is the server allowed to reallocate the counted array? (I think it is, but I am not sure anymore)

Its current implementation only replaces the existing ID's, but I'd like to implement a change (that would not break contract) that may return more items without introducing a new interface.

[edit] please note that CACLSID is already an array, containing a count and a pointer.

LastEditorDisplayName: peterchen

OwnerDisplayName: Vinay


问:
Formula expression to result
In Java, if I have a string:

```<code>String abc = "(5)*(2+2)/(2)";
</code>```

How could I get the result of abc = 10?

答:
It's not straightforward. You should

have a grammar for arithmetic expressions

build a lexer/parser from the grammar

parse your string with the parser, and have the parser perform the semantic actions corresponding to the arithmetic operators of your grammar.

You can find a simple example in ANTLR documentation: section 2.1 Create a simple grammar, has a Java example with a grammar for basic arithmetic expressions.

Title: Formula expression to result

Body:
In Java, if I have a string:

String abc = "(5)*(2+2)/(2)";

How could I get the result of abc = 10?