问:
Emulator doesn't boot properly "ERROR: detected a hanging thread"
I cannot properly start an emulator on my Mac Mini.
When I execute the emulator command, the emulator window appears, the boot animation starts, but after a while I get this error messages:

```<code>ERROR: detected a hanging thread 'QEMU2 CPU0 thread'. No response for 15011 ms
</code>```

And the emulator either quits or becomes completely unresponsive.

The Mac Mini is of late 2012, has 16GB RAM, a 2.5 GHz Intel Core i5 CPU with an HD 4000 graphics card; Not the fastest, but should be able to run the emulator (and has been able to do that without problems in the past)

I tried:

Updating the emulator:

```<code>emulator -version
Android emulator version 28.0.25.0 (build_id 5395263) (CL:77b96786ddf712e1477c6e05cddb09526043faef)
</code>```

Verify Intel Haxm is installed:

```<code> kextstat | grep intel
  102    0 0xffffff7f83833000 0x28000    0x28000    com.intel.kext.intelhaxm (7.3.2) 58DFBE80-E54A-3EFE-B38A-215C5ED8E828 <7 5 4 3 1>
</code>```

Running the emulator without audio and window:

```<code>emulator -no-audio -no-window  -no-boot-anim @avd
</code>```

(same results)

Lowering the resolution of the avd:

```<code>hw.lcd.density = 240
hw.lcd.height = 960
hw.lcd.width = 540
</code>```

in config.ini of the avd

Disabling/Enabling IPv6 doesnt change anything.

Full config.ini:

```<code>PlayStore.enabled = false
abi.type = x86
avd.ini.encoding = UTF-8
hw.accelerometer = yes
hw.audioInput = yes
hw.battery = yes
hw.cpu.arch = x86
hw.dPad = no
hw.device.hash2 = MD5:1c925b9117dd9f33c5128dac289a0d68
hw.device.manufacturer = Google
hw.device.name = Nexus 5
hw.gps = yes
hw.lcd.density = 240
hw.lcd.height = 960
hw.lcd.width = 540
hw.mainKeys = no
hw.sdCard = no
hw.sensors.orientation = yes
hw.sensors.proximity = yes
hw.trackBall = no
image.sysdir.1 = system-images/android-28/google_apis/x86/
tag.display = Google APIs
tag.id = google_apis
hw.gpu.mode = host
hw.gpu.enabled = yes
skin.dynamic = yes
hw.ramSize = 2048
</code>```

Full output of the emulator command:

```<code> emulator @avd
2019-04-05 14:42:46.888 qemu-system-x86_64[72065:9498885] GetInputSourceEnabledPrefs user file path = /Users/dgns/Library/Preferences/com.apple.HIToolbox.plist
2019-04-05 14:42:46.888 qemu-system-x86_64[72065:9498885] GetInputSourceEnabledPrefs effective user id path = 501
2019-04-05 14:42:46.888 qemu-system-x86_64[72065:9498885] GetInputSourceEnabledPrefs user pref content = <CFBasicHash 0x7fa6a164d730 [0x7fffaa5028e0]>{type = immutable dict, count = 1,
entries =>
    0 : <CFString 0x7fa6a1616070 [0x7fffaa5028e0]>{contents = "AppleSavedCurrentInputSource"} = <CFBasicHash 0x7fa6a164d6f0 [0x7fffaa5028e0]>{type = immutable dict, count = 3,
entries =>
    0 : <CFString 0x7fffaa570f68 [0x7fffaa5028e0]>{contents = "InputSourceKind"} = <CFString 0x7fffaa5b64a8 [0x7fffaa5028e0]>{contents = "Keyboard Layout"}
    1 : <CFString 0x7fffaa56bc68 [0x7fffaa5028e0]>{contents = "KeyboardLayout Name"} = Austrian
    2 : <CFString 0x7fffaa5a25e8 [0x7fffaa5028e0]>{contents = "KeyboardLayout ID"} = <CFNumber 0x5c37 [0x7fffaa5028e0]>{value = +92, type = kCFNumberSInt64Type}
}

}
emulator: INFO: boot completed
emulator: ERROR: detected a hanging thread 'QEMU2 CPU0 thread'. No response for 15011 ms
emulator: ERROR: detected a hanging thread 'QEMU2 CPU1 thread'. No response for 15011 ms
emulator: ERROR: detected a hanging thread 'QEMU2 CPU0 thread'. No response for 15011 ms
</code>```

```<code>which emulator
/Users/<user>/Library/Android/sdk/emulator/emulator
</code>```

Expected Result: Emulator Boots and is able to run the automated tests afterwards

Actual Result: Emulator quits or hangs

答:
I had the same issue on a Mac Mini.  This is what worked for me:

Go to Tools->AVD Manager->Edit(The particular emulator)>Show Advanced Settings

Then in the Emulated Performance section, I changed it from Quick Boot to Cold Boot.

Other options if this doesn't work can be found here.

Body:
I cannot properly start an emulator on my Mac Mini.
When I execute the emulator command, the emulator window appears, the boot animation starts, but after a while I get this error messages:

ERROR: detected a hanging thread 'QEMU2 CPU0 thread'. No response for 15011 ms

And the emulator either quits or becomes completely unresponsive.

The Mac Mini is of late 2012, has 16GB RAM, a 2.5 GHz Intel Core i5 CPU with an HD 4000 graphics card; Not the fastest, but should be able to run the emulator (and has been able to do that without problems in the past)

I tried:

Updating the emulator:

emulator -version
Android emulator version 28.0.25.0 (build_id 5395263) (CL:77b96786ddf712e1477c6e05cddb09526043faef)

Verify Intel Haxm is installed:

 kextstat | grep intel
  102    0 0xffffff7f83833000 0x28000    0x28000    com.intel.kext.intelhaxm (7.3.2) 58DFBE80-E54A-3EFE-B38A-215C5ED8E828 <7 5 4 3 1>

Running the emulator without audio and window:

emulator -no-audio -no-window  -no-boot-anim @avd

(same results)

Lowering the resolution of the avd:

hw.lcd.density = 240
hw.lcd.height = 960
hw.lcd.width = 540

in config.ini of the avd

Disabling/Enabling IPv6 doesnt change anything.

Full config.ini:

PlayStore.enabled = false
abi.type = x86
avd.ini.encoding = UTF-8
hw.accelerometer = yes
hw.audioInput = yes
hw.battery = yes
hw.cpu.arch = x86
hw.dPad = no
hw.device.hash2 = MD5:1c925b9117dd9f33c5128dac289a0d68
hw.device.manufacturer = Google
hw.device.name = Nexus 5
hw.gps = yes
hw.lcd.density = 240
hw.lcd.height = 960
hw.lcd.width = 540
hw.mainKeys = no
hw.sdCard = no
hw.sensors.orientation = yes
hw.sensors.proximity = yes
hw.trackBall = no
image.sysdir.1 = system-images/android-28/google_apis/x86/
tag.display = Google APIs
tag.id = google_apis
hw.gpu.mode = host
hw.gpu.enabled = yes
skin.dynamic = yes
hw.ramSize = 2048

Full output of the emulator command:

 emulator @avd
2019-04-05 14:42:46.888 qemu-system-x86_64[72065:9498885] GetInputSourceEnabledPrefs user file path = /Users/dgns/Library/Preferences/com.apple.HIToolbox.plist
2019-04-05 14:42:46.888 qemu-system-x86_64[72065:9498885] GetInputSourceEnabledPrefs effective user id path = 501
2019-04-05 14:42:46.888 qemu-system-x86_64[72065:9498885] GetInputSourceEnabledPrefs user pref content = <CFBasicHash 0x7fa6a164d730 [0x7fffaa5028e0]>{type = immutable dict, count = 1,
entries =>
    0 : <CFString 0x7fa6a1616070 [0x7fffaa5028e0]>{contents = "AppleSavedCurrentInputSource"} = <CFBasicHash 0x7fa6a164d6f0 [0x7fffaa5028e0]>{type = immutable dict, count = 3,
entries =>
    0 : <CFString 0x7fffaa570f68 [0x7fffaa5028e0]>{contents = "InputSourceKind"} = <CFString 0x7fffaa5b64a8 [0x7fffaa5028e0]>{contents = "Keyboard Layout"}
    1 : <CFString 0x7fffaa56bc68 [0x7fffaa5028e0]>{contents = "KeyboardLayout Name"} = Austrian
    2 : <CFString 0x7fffaa5a25e8 [0x7fffaa5028e0]>{contents = "KeyboardLayout ID"} = <CFNumber 0x5c37 [0x7fffaa5028e0]>{value = +92, type = kCFNumberSInt64Type}
}

}
emulator: INFO: boot completed
emulator: ERROR: detected a hanging thread 'QEMU2 CPU0 thread'. No response for 15011 ms
emulator: ERROR: detected a hanging thread 'QEMU2 CPU1 thread'. No response for 15011 ms
emulator: ERROR: detected a hanging thread 'QEMU2 CPU0 thread'. No response for 15011 ms

which emulator
/Users/<user>/Library/Android/sdk/emulator/emulator

Expected Result: Emulator Boots and is able to run the automated tests afterwards

Actual Result: Emulator quits or hangs


来源: stackexchange

问:
Get/Set loadOnDemandBufferSize or loadMoreDataRequested through JavaScript
I have a SearchBar on top of RadListView using loadOnDemandBufferSize="10" and when I submit a search the loadMoreDataRequested property is triggered pushing additional items to the search results.

The searchBar uses a different method to retrieve data. I could update the http.getJSON URL used by onLoadMore method but I believe it would be better to temporarily disable the loadOnDemandMode in RadListView.

I just need to temporarily disable the loadMoreDataRequested or set loadOnDemandBufferSize to zero when submitting the search in order to keep the search results alone.

Is there a way to get/set loadMoreDataRequested or loadOnDemandBufferSize using JavaScript? My project is running on Nativescript-Vue.

```<code>mounted() {
      console.log(this.$refs.listView.nativeView.loadMoreDataRequested)
      console.log(this.$refs.listView.loadMoreDataRequested)
      console.log(this.$refs.listView.nativeView)
      console.log(this.$refs.listView)
}
</code>```

```<code><GridLayout columns="*" rows="auto, *, auto">
    <SearchBar @submit="searchHttp" v-model="search" v-show="searchShow" height="50" row="0" />
    <RadListView
      for="item in items"
      loadOnDemandMode="Auto"
      loadOnDemandBufferSize="10"
      @loadMoreDataRequested="onLoadMore"
      @itemTap="onItemTap"
      ref="listView"
      row="1"
    >
      <v-template>
        <StackLayout :class="$odd ? 'list-group-item list-group-item-odd' : 'list-group-item'" orientation="vertical">
          <Label :text="item.created + ' - ' + item.company_id" />
        </StackLayout>
      </v-template>
    </RadListView>
    <Label v-if="items != null && !activity" :text="'Total ' + items.length" class="search-total" height="30" row="2" />
    <ActivityIndicator :busy="activity" borderRadius="50" color="#6c6aa6" width="50" height="50" rowSpan="3" />
</GridLayout>
</code>```

答:
You may set the loadOnDemandMode property to None.

```<code>import * as RadListViewModule from "nativescript-ui-listview";

this.$refs.listView.nativeView.loadOnDemandMode = RadListViewModule.ListViewLoadOnDemandMode.None;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a SearchBar on top of RadListView using loadOnDemandBufferSize="10" and when I submit a search the loadMoreDataRequested property is triggered pushing additional items to the search results.

The searchBar uses a different method to retrieve data. I could update the http.getJSON URL used by onLoadMore method but I believe it would be better to temporarily disable the loadOnDemandMode in RadListView.

I just need to temporarily disable the loadMoreDataRequested or set loadOnDemandBufferSize to zero when submitting the search in order to keep the search results alone.

Is there a way to get/set loadMoreDataRequested or loadOnDemandBufferSize using JavaScript? My project is running on Nativescript-Vue.

mounted() {
      console.log(this.$refs.listView.nativeView.loadMoreDataRequested)
      console.log(this.$refs.listView.loadMoreDataRequested)
      console.log(this.$refs.listView.nativeView)
      console.log(this.$refs.listView)
}

<GridLayout columns="*" rows="auto, *, auto">
    <SearchBar @submit="searchHttp" v-model="search" v-show="searchShow" height="50" row="0" />
    <RadListView
      for="item in items"
      loadOnDemandMode="Auto"
      loadOnDemandBufferSize="10"
      @loadMoreDataRequested="onLoadMore"
      @itemTap="onItemTap"
      ref="listView"
      row="1"
    >
      <v-template>
        <StackLayout :class="$odd ? 'list-group-item list-group-item-odd' : 'list-group-item'" orientation="vertical">

        </StackLayout>
      </v-template>
    </RadListView>

    <ActivityIndicator :busy="activity" borderRadius="50" color="#6c6aa6" width="50" height="50" rowSpan="3" />
</GridLayout>

Body:
You may set the loadOnDemandMode property to None.

import * as RadListViewModule from "nativescript-ui-listview";

this.$refs.listView.nativeView.loadOnDemandMode = RadListViewModule.ListViewLoadOnDemandMode.None;


问:
Screamwriter outputting to Vietnamese, not ASCII (English)
In a nutshell, creating a ASCII text file that records polling data from a printer under test. The expected output should be US English, but the text file is in Vietnamese.
Example:
the_Maker = "Epson", SubModel = "T88V", serial_num = PD9F393594, error_list = total # of polling errors (a number). - Example if testing a Epson T88V Thermal Printer.

```<code>using (System.IO.StreamWriter file = new System.IO.StreamWriter(output_file, true))
{
    ASCIIEncoding ascii = new ASCIIEncoding();
    file.WriteLine(the_Maker + " ● " + SubModel + " ● " + serial_num + " ● " + error_list + " END Polls " + DateTime.Now.ToString());
}
</code>```

Output from file:
偅体辗䵔吭㠸辗䑐䘹㤳㔳㐹韢䖏䑎倠汯獬㔠㈯⼷〲㤱㔠㌺㨶㈵倠്䔊卐乏辗吠ⵍ㡔嘸辗倠㥄㍆㌹㤵‴韢₏䔠䑎倠汯獬㔠㈯⼷〲㤱㔠㌺㨸㘲倠്

This should be in English

答:
If you intend to use an encoding for the StreamWriter, you have to construct the StreamWriter with the target encoding. You are currently creating an ASCIIEncoding object and not using it.

```<code>ASCIIEncoding ascii = new ASCIIEncoding();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(output_file, true, ascii))
{
    file.WriteLine(the_Maker + " ● " + SubModel + " ● " + serial_num + " ● " + error_list + " END Polls " + DateTime.Now.ToString());
}
</code>```

Body:
In a nutshell, creating a ASCII text file that records polling data from a printer under test. The expected output should be US English, but the text file is in Vietnamese.
Example:
the_Maker = "Epson", SubModel = "T88V", serial_num = PD9F393594, error_list = total # of polling errors (a number). - Example if testing a Epson T88V Thermal Printer.

using (System.IO.StreamWriter file = new System.IO.StreamWriter(output_file, true))
{
    ASCIIEncoding ascii = new ASCIIEncoding();
    file.WriteLine(the_Maker + " ● " + SubModel + " ● " + serial_num + " ● " + error_list + " END Polls " + DateTime.Now.ToString());
}

Output from file:
偅体辗䵔吭㠸辗䑐䘹㤳㔳㐹韢䖏䑎倠汯獬㔠㈯⼷〲㤱㔠㌺㨶㈵倠്䔊卐乏辗吠ⵍ㡔嘸辗倠㥄㍆㌹㤵‴韢₏䔠䑎倠汯獬㔠㈯⼷〲㤱㔠㌺㨸㘲倠്

This should be in English

Body:
If you intend to use an encoding for the StreamWriter, you have to construct the StreamWriter with the target encoding. You are currently creating an ASCIIEncoding object and not using it.

ASCIIEncoding ascii = new ASCIIEncoding();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(output_file, true, ascii))
{
    file.WriteLine(the_Maker + " ● " + SubModel + " ● " + serial_num + " ● " + error_list + " END Polls " + DateTime.Now.ToString());
}


问:
what is alternative solution for GLKView Class? [deprecated in iOS 12]
Apple had been deprecated GLKView class in iOS 12. Anybody share the answer for alternative solution for existing project and new project

答: openGL support is deprecated (iOS 12) so the alternative is to use metal and MTKView</p>


问:
How to remove several elements of a list by the index which can be changed each time?
I have a list like below:

```<code>A =  [1, 2, 3, 4]
</code>```

After using enumerate I have the following list:

```<code>A = [(0, 1), (1, 2), (2, 3), (3, 4)]
</code>```

After checking a condition, I realized that I don't need the elements with index 0 and 2.
It means that my condition returns a list like below which can be different each time:

```<code>condA = [(0, 1), (2, 3)]
</code>```

I know that I can use del or .pop() to remove an element from a list.
However, I was wondering how can I read the numbers like (0) and (2) in my condA list and remove those elements from my original list.
I don't want to enter the 0 and 2 in my code because each time they would be different.

The result would be like this:

```<code>A_reduced = [2, 4]

</code>```

答:
Loop through condA, pop the element off the list A. You need a counter to decrease the indexes, since the size of A is shrinking. Make sure to sort condA:

```<code>A =  [1, 2, 3, 4]
condA = [(0, 1), (2, 3)]

i = 0
for item in condA:
    A.pop(item[0]-i)
    i+=1
#result: [2, 4]
</code>```

Body:
I have a list like below:

A =  [1, 2, 3, 4]

After using enumerate I have the following list:

A = [(0, 1), (1, 2), (2, 3), (3, 4)]

After checking a condition, I realized that I don't need the elements with index 0 and 2.
It means that my condition returns a list like below which can be different each time:

condA = [(0, 1), (2, 3)]

I know that I can use del or .pop() to remove an element from a list.
However, I was wondering how can I read the numbers like (0) and (2) in my condA list and remove those elements from my original list.
I don't want to enter the 0 and 2 in my code because each time they would be different.

The result would be like this:

A_reduced = [2, 4]

Body:
Loop through condA, pop the element off the list A. You need a counter to decrease the indexes, since the size of A is shrinking. Make sure to sort condA:

A =  [1, 2, 3, 4]
condA = [(0, 1), (2, 3)]

i = 0
for item in condA:
    A.pop(item[0]-i)
    i+=1
#result: [2, 4]


问:
How to show category subcategory based on array
I have an array that consists of some data to show the category and subcategories.

```<code>{id: "5", parent_id: "0", lable: "Movie"}
{id: "20", parent_id: "5", lable: "Action"}
{id: "15", parent_id: "43", lable: "J.K Rowling"}
{id: "43", parent_id: "0", lable: "Book"}
{id: "20", parent_id: "2", lable: "James Bond Series"}
{id: "3", parent_id: "0", lable: "Music"}
{id: "39", parent_id: "15", lable: "Harry Potter Series"}
</code>```

I want to sort and show this data something like this :

```<code>> Movie
>> Action
>>>James Bond Series

>Book
>>J.K Rowling
>>>Harry Potter Series
</code>```

答:
You need the tree representation of your data since your data is a self-reference table. So, you need to write a code that will translate your flat structure to a tree. For example, you can use the following code to do this:

```<code>const makeTree = (array, id, parentId, parentValue) =>
  array
    .filter(node => {
      return node[parentId] === parentValue;
    })
    .map(node => {
      node["items"] = makeTree(array, id, parentId, node[id]);
      return node;
    });
</code>```

Where array is your source array, id - the name of the ID field, parentId - the name of the field that holds the parent ID, parentValue - the root node ID.

You can call this function as the follows to make a tree from your array:

```<code>const tree = makeTree(array, "id", "parent_id", "0");
</code>```

Where array is your source array:

```<code>const array = [
  { id: "5", parent_id: "0", lable: "Movie" },
  { id: "20", parent_id: "5", lable: "Action" },
  { id: "15", parent_id: "43", lable: "J.K Rowling" },
  { id: "43", parent_id: "0", lable: "Book" },
  { id: "2", parent_id: "20", lable: "James Bond Series" },
  { id: "3", parent_id: "0", lable: "Music" },
  { id: "39", parent_id: "15", lable: "Harry Potter Series" }
];
</code>```

The resultant array elements will contain the items field that is an array of child nodes.

After this, you can create a recursive function that will render this tree using jQuery. For example:

```<code>const renderLevel = items => {
  return $("<ul>").append(
    items.map(item =>
      $("<li>")
        .html(item.lable)
        .append(renderLevel(item.items))
    )
  );
};
</code>```

Call it and pass the tree variable to it:

```<code>$(() => {
  $("body").append(renderLevel(tree));
});
</code>```

This is a sample.

const array = [
  { id: "5", parent_id: "0", lable: "Movie" },
  { id: "20", parent_id: "5", lable: "Action" },
  { id: "15", parent_id: "43", lable: "J.K Rowling" },
  { id: "43", parent_id: "0", lable: "Book" },
  { id: "2", parent_id: "20", lable: "James Bond Series" },
  { id: "3", parent_id: "0", lable: "Music" },
  { id: "39", parent_id: "15", lable: "Harry Potter Series" }
];

const makeTree = (array, id, parentId, parentValue) =>
  array
    .filter(node => {
      return node[parentId] === parentValue;
    })
    .map(node => {
      node["items"] = makeTree(array, id, parentId, node[id]);
      return node;
    });

const tree = makeTree(array, "id", "parent_id", "0");
console.log(JSON.stringify(tree))

const renderLevel = items => {
  return $("
").append(
    items.map(item =>
      $("
")
        .html(item.lable)
        .append(renderLevel(item.items))
    )
  );
};

$(() => {
  $("body").append(renderLevel(tree));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Body:
I have an array that consists of some data to show the category and subcategories.

{id: "5", parent_id: "0", lable: "Movie"}
{id: "20", parent_id: "5", lable: "Action"}
{id: "15", parent_id: "43", lable: "J.K Rowling"}
{id: "43", parent_id: "0", lable: "Book"}
{id: "20", parent_id: "2", lable: "James Bond Series"}
{id: "3", parent_id: "0", lable: "Music"}
{id: "39", parent_id: "15", lable: "Harry Potter Series"}

I want to sort and show this data something like this :

> Movie
>> Action
>>>James Bond Series

>Book
>>J.K Rowling
>>>Harry Potter Series

Body:
You need the tree representation of your data since your data is a self-reference table. So, you need to write a code that will translate your flat structure to a tree. For example, you can use the following code to do this:

const makeTree = (array, id, parentId, parentValue) =>
  array
    .filter(node => {
      return node[parentId] === parentValue;
    })
    .map(node => {
      node["items"] = makeTree(array, id, parentId, node[id]);
      return node;
    });

Where array is your source array, id - the name of the ID field, parentId - the name of the field that holds the parent ID, parentValue - the root node ID.

You can call this function as the follows to make a tree from your array:

const tree = makeTree(array, "id", "parent_id", "0");

Where array is your source array:

const array = [
  { id: "5", parent_id: "0", lable: "Movie" },
  { id: "20", parent_id: "5", lable: "Action" },
  { id: "15", parent_id: "43", lable: "J.K Rowling" },
  { id: "43", parent_id: "0", lable: "Book" },
  { id: "2", parent_id: "20", lable: "James Bond Series" },
  { id: "3", parent_id: "0", lable: "Music" },
  { id: "39", parent_id: "15", lable: "Harry Potter Series" }
];

The resultant array elements will contain the items field that is an array of child nodes.

After this, you can create a recursive function that will render this tree using jQuery. For example:

const renderLevel = items => {
  return $("<ul>").append(
    items.map(item =>
      $("<li>")
        .html(item.lable)
        .append(renderLevel(item.items))
    )
  );
};

Call it and pass the tree variable to it:

$(() => {
  $("body").append(renderLevel(tree));
});

This is a sample.

const array = [
  { id: "5", parent_id: "0", lable: "Movie" },
  { id: "20", parent_id: "5", lable: "Action" },
  { id: "15", parent_id: "43", lable: "J.K Rowling" },
  { id: "43", parent_id: "0", lable: "Book" },
  { id: "2", parent_id: "20", lable: "James Bond Series" },
  { id: "3", parent_id: "0", lable: "Music" },
  { id: "39", parent_id: "15", lable: "Harry Potter Series" }
];

const makeTree = (array, id, parentId, parentValue) =>
  array
    .filter(node => {
      return node[parentId] === parentValue;
    })
    .map(node => {
      node["items"] = makeTree(array, id, parentId, node[id]);
      return node;
    });

const tree = makeTree(array, "id", "parent_id", "0");
console.log(JSON.stringify(tree))

const renderLevel = items => {
  return $("<ul>").append(
    items.map(item =>
      $("<li>")
        .html(item.lable)
        .append(renderLevel(item.items))
    )
  );
};

$(() => {
  $("body").append(renderLevel(tree));
});

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


问:
JSON.parse(data) causes error
The problem seems to be simple:
The callback function of an AJAX post request receives this json string in parameter 'data':

```<code>{"result":"Torte"}.
</code>```

When I parse it manually like this

```<code>var antwort = JSON.parse('{"result":"Torte"}');
</code>```

it is ok.
But

```<code>var antwort = JSON.parse("'" + data + "'");
</code>```

causes the error

```<code>Uncaught SyntaxError: Unexpected token ' in JSON at position 0
at JSON.parse (<anonymous>)
</code>```

With

```<code>var antwort = JSON.parse(data);
</code>```

a similar error shows up (in the developer tools of Chrome):

```<code>VM1285:2 Uncaught SyntaxError: Unexpected token < in JSON at position 21
at JSON.parse (<anonymous>)
</code>```

So it seems that 'data' contains additional characters.
On the other hand, making the received json-string visible with

```<code>$("#idTest").html(data)
</code>```

just shows

```<code>{"result":"Torte"}
</code>```

No additional characters.

I have been working on this problem for several hours - without success.
Can anybody help, please.

答:
I will call the data of a .map to load them into a matrix using .push, but I cannot put the value of the data in the JSON.parse

The objective of my exercise is what by selecting a () 1 option to be loaded into the () 2 as an option.

To do this .map the data in the select 1 and then with the event onClick load the data I need to an array to read the options in select 2.

```<code>const filtraritems = [{ value: 'test', label: 'Probando la lista' }];

const buscarOpciones = items.map(item => (
      <option
        key={item.id}
        onClick={() => {
          const { value } = item;
          filtraritems.push(
            **JSON.parse('{"value": ${items.value}, "label": ${items.label}}')**
          );
          console.log(filtraritems);
        }}
      >
        {item.nombre}
      </option>
    ));
</code>```

ContentLicense: CC BY-SA 3.0

Title: JSON.parse(data) causes error

Body:
The problem seems to be simple:
The callback function of an AJAX post request receives this json string in parameter 'data':

{"result":"Torte"}.

When I parse it manually like this

var antwort = JSON.parse('{"result":"Torte"}');

it is ok.
But

var antwort = JSON.parse("'" + data + "'");

causes the error

Uncaught SyntaxError: Unexpected token ' in JSON at position 0
at JSON.parse (<anonymous>)

With

var antwort = JSON.parse(data);

a similar error shows up (in the developer tools of Chrome):

VM1285:2 Uncaught SyntaxError: Unexpected token < in JSON at position 21
at JSON.parse (<anonymous>)

So it seems that 'data' contains additional characters.
On the other hand, making the received json-string visible with

$("#idTest").html(data)

just shows

{"result":"Torte"}

No additional characters.

I have been working on this problem for several hours - without success.
Can anybody help, please.

Body:
I will call the data of a .map to load them into a matrix using .push, but I cannot put the value of the data in the JSON.parse

The objective of my exercise is what by selecting a () 1 option to be loaded into the () 2 as an option.

To do this .map the data in the select 1 and then with the event onClick load the data I need to an array to read the options in select 2.

const filtraritems = [{ value: 'test', label: 'Probando la lista' }];

const buscarOpciones = items.map(item => (
      <option
        key={item.id}
        onClick={() => {
          const { value } = item;
          filtraritems.push(
            **JSON.parse('{"value": ${items.value}, "label": ${items.label}}')**
          );
          console.log(filtraritems);
        }}
      >
        {item.nombre}
      </option>
    ));


问:
How to write a random group generator in java using else-if statements?
I have to code a program that allows the user to choose between two task: a random group generator, and a task that parses and counts an input sentence by word. I am really confused on how to go about it.
The instructions are:
Team Maker:
If 1 is entered, the application prompts the user to enter the desired number of teams to make.
If 0 is entered, nothing happens and the application continues on prompting the user to enter 1 or 2. See Fig-3.
If the number of teams is 1 or greater, the application displays the team number, beginning from 1, followed by three full names randomly selected from the 49 students provided in COP2510.txt. See also Fig-3, where 1 and 3 are entered for making one team and three teams, respectively.  Hint: Use the Random class as seen in GetRandom1.java or GR.zip of Quiz 3 to implement this random selection.

All names of each team must be displayed beginning with a 'tab'.
It's very important in this application that no student appears in the same or different teams more than once.
Hint: there are more than one way to "map" a random number (integer) to a specific student name. Using if....else if....else if....else if.... is one possible approach and is recommended here. Storing all names in an array is another way but is not introduced until Chapter 10 .
Counting Words:
If 2 is entered, the application prompts the user to enter one or more sentences.  See Fig-4.
The application uses the space character, " ", to separate and count words in the input. If there are two or more consecutive spaces, they are treated as just one. That is, "AA BB" and "AA             BB" both contains two words.  See Fig-5.
All leading and trailing spaces in the input would be ignored. Hint: use 'trim()' method of String.
The application display two lines of dashes, i.e., "-------------------" to enclose every word it finds. Each word must be displayed together with its length. For example, if "Hi,  John!" is entered, the two lines between dashes should be "Hi, (3)" and "John!(5)".
After the 2nd dashes line, the total number of words is displayed to end the task.
If no words or sentences are entered, a message of "Nothing or only space(s) is entered." is displayed between the two dashes lines and the count is zero. See the last input in Fig-5.
Hint: You may use trim(), indexOf(), length(), substring(), and equals() methods of String to implement the above word count task. Even the same methods are used, there are different approaches to get this task completed.

I got the first part where the program welcomes the user, and shows what the program does. However I don't know how to code the random team generator. I can only use else if statements. Someone told me to assign a random number to each name and then use the else if statements, however I have no idea how to do that. And as for the word counter I just have no clue. If anyone could help that would be great.

```<code>   import java.util.Scanner;
   import java.util.Random;
   public class asssignment3 {
   public static void main (String args[]){
   Scanner sc = new Scanner(System.in);
    //print out a task prompt
    System.out.println("Assignment-3 can perform the following two task:");
    System.out.println();
    System.out.println("\t1-Making 3-member tems from class of COP2510");
    System.out.println("\t2-Parsing and counting an input sentence by word");
    System.out.println();
    System.out.print("Enter 1 or 2 to begin your task or anything else to quit:   ");
    String choiceNumber = sc.nextLine ();

  if (choiceNumber.equalsIgnoreCase("0")) {
      System.out.println("Enter 1 or 2 to begin your task or anything else to quit:  ");
      String optionNumber = sc.nextLine ();
  }
  Random r = new Random();
 if (choiceNumber.equalsIgnoreCase ("1")) {
     String studentName = "";`
</code>```

答:
Personally, I would forego the if-else and do the array. Make an array with every integer from 0-N, where N is the number of the students. Then, shuffle the list around. I believe Java has a prebuilt function for it, but if not the algorithm for one is trivial.

From there, simply read in the student file line by line and assign the corresponding number from the shuffled array.
Example psuedocode:

# >>> Generate the list of numbers of shuffle it. <<< #
N = number of students
numbers = [i for i in range(N)]
random.shuffle(numbers)

# >>> Initialize a list to store number-student pair <<< #
students = []

# >>> Read in the student file line by line <<< #
for line in students.txt:
    randomNumber = numbers.pop()
    students.append((line, randomNumber))
```

<p>Viola, the <code>students</code> list now has all of the students, paired with a random number.</p>

<p>As for counting words, run the input through trim() and then split().</p>

<pre class="lang-py prettyprint-override"><code># >>> Removes whitespace before and after the string ("  A " -> "A") <<< #
input = input.trim()
# >>> Splits input into an array ("AA BB CC" -> ["AA", "BB", "CC"]) <<< #
words = input.split(" ")
numWords = word.length
</code>```

Body:
I have to code a program that allows the user to choose between two task: a random group generator, and a task that parses and counts an input sentence by word. I am really confused on how to go about it.
The instructions are:
Team Maker:
If 1 is entered, the application prompts the user to enter the desired number of teams to make.
If 0 is entered, nothing happens and the application continues on prompting the user to enter 1 or 2. See Fig-3.
If the number of teams is 1 or greater, the application displays the team number, beginning from 1, followed by three full names randomly selected from the 49 students provided in COP2510.txt. See also Fig-3, where 1 and 3 are entered for making one team and three teams, respectively.  Hint: Use the Random class as seen in GetRandom1.java or GR.zip of Quiz 3 to implement this random selection.

All names of each team must be displayed beginning with a 'tab'.
It's very important in this application that no student appears in the same or different teams more than once.
Hint: there are more than one way to "map" a random number (integer) to a specific student name. Using if....else if....else if....else if.... is one possible approach and is recommended here. Storing all names in an array is another way but is not introduced until Chapter 10 .
Counting Words:
If 2 is entered, the application prompts the user to enter one or more sentences.  See Fig-4.
The application uses the space character, " ", to separate and count words in the input. If there are two or more consecutive spaces, they are treated as just one. That is, "AA BB" and "AA             BB" both contains two words.  See Fig-5.
All leading and trailing spaces in the input would be ignored. Hint: use 'trim()' method of String.
The application display two lines of dashes, i.e., "-------------------" to enclose every word it finds. Each word must be displayed together with its length. For example, if "Hi,  John!" is entered, the two lines between dashes should be "Hi, (3)" and "John!(5)".
After the 2nd dashes line, the total number of words is displayed to end the task.
If no words or sentences are entered, a message of "Nothing or only space(s) is entered." is displayed between the two dashes lines and the count is zero. See the last input in Fig-5.
Hint: You may use trim(), indexOf(), length(), substring(), and equals() methods of String to implement the above word count task. Even the same methods are used, there are different approaches to get this task completed.

I got the first part where the program welcomes the user, and shows what the program does. However I don't know how to code the random team generator. I can only use else if statements. Someone told me to assign a random number to each name and then use the else if statements, however I have no idea how to do that. And as for the word counter I just have no clue. If anyone could help that would be great.

   import java.util.Scanner;
   import java.util.Random;
   public class asssignment3 {
   public static void main (String args[]){
   Scanner sc = new Scanner(System.in);
    //print out a task prompt
    System.out.println("Assignment-3 can perform the following two task:");
    System.out.println();
    System.out.println("\t1-Making 3-member tems from class of COP2510");
    System.out.println("\t2-Parsing and counting an input sentence by word");
    System.out.println();
    System.out.print("Enter 1 or 2 to begin your task or anything else to quit:   ");
    String choiceNumber = sc.nextLine ();

  if (choiceNumber.equalsIgnoreCase("0")) {
      System.out.println("Enter 1 or 2 to begin your task or anything else to quit:  ");
      String optionNumber = sc.nextLine ();
  }
  Random r = new Random();
 if (choiceNumber.equalsIgnoreCase ("1")) {
     String studentName = "";`

Body:
Personally, I would forego the if-else and do the array. Make an array with every integer from 0-N, where N is the number of the students. Then, shuffle the list around. I believe Java has a prebuilt function for it, but if not the algorithm for one is trivial.

From there, simply read in the student file line by line and assign the corresponding number from the shuffled array.
Example psuedocode:

# >>> Generate the list of numbers of shuffle it. <<< #
N = number of students
numbers = [i for i in range(N)]
random.shuffle(numbers)

# >>> Initialize a list to store number-student pair <<< #
students = []

# >>> Read in the student file line by line <<< #
for line in students.txt:
    randomNumber = numbers.pop()
    students.append((line, randomNumber))

Viola, the students list now has all of the students, paired with a random number.

As for counting words, run the input through trim() and then split().

# >>> Removes whitespace before and after the string ("  A " -> "A") <<< #
input = input.trim()
# >>> Splits input into an array ("AA BB CC" -> ["AA", "BB", "CC"]) <<< #
words = input.split(" ")
numWords = word.length


问:
Consume Kafka messages from a different container in python
Below is my docker-compose file:

```<code>   version: "3"
    services:
      app:
        image: app
        restart: always
        ports:
          - "8001:8081"
        depends_on:
          - kafka
          - zookeeper
          - consumer
        environment:
          - KAFKA_HOST = kafka

  zookeeper:
    image: "wurstmeister/zookeeper:latest"
    ports:
        - "2181:2181"
    hostname: zookeeper

  kafka:
    image: "wurstmeister/kafka:2.12-2.2.0"
    ports:
      - "9092:9092"
    hostname: kafka
    links:
     - zookeeper:zookeeper
    environment:
      KAFKA_CREATE_TOPICS: "Topic01:2:2" #TOPIC:PARTITON:REPLICATION
      KAFKA_ZOOKEEPER_CONNECTION_TIMEOUT_MS: "60000"
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: "true"
      KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181"
      KAFKA_LISTENERS: 'PLAINTEXT://:9092'
      KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://kafka:9092'

    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

  consumer:
    image: consumer:latest
    build:
      context: ./consumer
    ports:
      - "8283:8283"
</code>```

Text stream is generated using container for app image and is able to produce the messages.

It is verified by navigating inside the kafka container:

docker exec -it <CONTAINER ID of Kafka Image> /bin/bash

when I manually run the below script inside the container

kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic Topic01 --from-beginning

I can see the chunk of text that is being produced.

But when I try to read the same data from the container of the image consumer, It gives me blank,

Method tried:

docker exec inside the consumer container, and ran the below python code:

```<code>from kafka import KafkaConsumer
consumer = KafkaConsumer('Topic01', bootstrap_servers='kafka:9092')
for messages in consumer:
        print(messages)
</code>```

It prints nothing.

Is it because my docker-compose file is wrong or the mistake in the python code?

答:
According to Kafka documentation for listeners:

Listener List - Comma-separated list of URIs we will listen on and the listener names. If the listener name is not a security protocol, listener.security.protocol.map must also be set. Specify hostname as 0.0.0.0 to bind to all interfaces. Leave hostname empty to bind to default interface. Examples of legal listener lists: PLAINTEXT://myhost:9092,SSL://:9091 CLIENT://0.0.0.0:9092,REPLICATION://localhost:9093

You are setting KAFKA_LISTENERS to PLAINTEXT://:9092, so it binds to default interface, which might not be accessible from the outside of your Kafka container (while at the same time it works fine with console consumer using localhost). Give it a try and specify KAFKA_LISTENERS as PLAINTEXT://0.0.0.0:9092, to check if you consumer starts to consume messages.

Body:
Below is my docker-compose file:

   version: "3"
    services:
      app:
        image: app
        restart: always
        ports:
          - "8001:8081"
        depends_on:
          - kafka
          - zookeeper
          - consumer
        environment:
          - KAFKA_HOST = kafka

  zookeeper:
    image: "wurstmeister/zookeeper:latest"
    ports:
        - "2181:2181"
    hostname: zookeeper

  kafka:
    image: "wurstmeister/kafka:2.12-2.2.0"
    ports:
      - "9092:9092"
    hostname: kafka
    links:
     - zookeeper:zookeeper
    environment:
      KAFKA_CREATE_TOPICS: "Topic01:2:2" #TOPIC:PARTITON:REPLICATION
      KAFKA_ZOOKEEPER_CONNECTION_TIMEOUT_MS: "60000"
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: "true"
      KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181"
      KAFKA_LISTENERS: 'PLAINTEXT://:9092'
      KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://kafka:9092'

    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

  consumer:
    image: consumer:latest
    build:
      context: ./consumer
    ports:
      - "8283:8283"

Text stream is generated using container for app image and is able to produce the messages.

It is verified by navigating inside the kafka container:

docker exec -it <CONTAINER ID of Kafka Image> /bin/bash

when I manually run the below script inside the container

kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic Topic01 --from-beginning

I can see the chunk of text that is being produced.

But when I try to read the same data from the container of the image consumer, It gives me blank,

Method tried:

docker exec inside the consumer container, and ran the below python code:

from kafka import KafkaConsumer
consumer = KafkaConsumer('Topic01', bootstrap_servers='kafka:9092')
for messages in consumer:
        print(messages)

It prints nothing.

Is it because my docker-compose file is wrong or the mistake in the python code?


问:
is there a way to examine if an angle is a right angle programmatically?
i plot an angle in python

here is the code

```<code>x = [0,0.5,1]
y = [0,0.5,0]
plt.scatter(x,y)
plt.plot(x,y)
plt.show()
</code>```

is there a way to examine if the angle is a right angle programmatically?

答:
You can compute the angle between the two vectors as following: first, get the two vectors v1 and v2 and then use np.arccos() which returns the angle in radians. Convert it to degrees to check if it is 90 degrees. The formulae for computing angle between two vectors can be found on this Wiki link

```<code>import numpy as np

x = np.array([0,0.5,1])
y = np.array([0,0.5,0])

vecs = np.vstack((x, y))
v1 = vecs[:, 1] - vecs[:, 0]
v2 = vecs[:, 2] - vecs[:, 1]

angle_rad = np.arccos(np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))

angle_deg = np.rad2deg(angle_rad)
# 90.0
</code>```

Body:
i plot an angle in python

here is the code

x = [0,0.5,1]
y = [0,0.5,0]
plt.scatter(x,y)
plt.plot(x,y)
plt.show()

is there a way to examine if the angle is a right angle programmatically?

Body:
You can compute the angle between the two vectors as following: first, get the two vectors v1 and v2 and then use np.arccos() which returns the angle in radians. Convert it to degrees to check if it is 90 degrees. The formulae for computing angle between two vectors can be found on this Wiki link

import numpy as np

x = np.array([0,0.5,1])
y = np.array([0,0.5,0])

vecs = np.vstack((x, y))
v1 = vecs[:, 1] - vecs[:, 0]
v2 = vecs[:, 2] - vecs[:, 1]

angle_rad = np.arccos(np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))

angle_deg = np.rad2deg(angle_rad)
# 90.0


问:
How to concatenate string in _bstr_t and wchar_t?
I have _bstr_t string and I have wchar_t and one unsigned int variables which I want to put to the string...

```<code>_bstr_t strCnn("Driver={SQL Server};Server=some_host,some_port;Database=some_db;User ID=some_user;Password=some_psw;");

wchar_t *host,
unsigned int port,
wchar_t *db_name,
wchar_t *user,
wchar_t *password,
</code>```

These 5 variables I pass to the function which does connection. Can you please guide me how to insert them to connection string.

I tried this way:

```<code>    wstring ws(host);
    string host_str(ws.begin(), ws.end());
    wstring ws_db(db_name);
    string db_str(ws_db.begin(), ws_db.end());
    wstring ws_user(user);
    string user_str(ws_user.begin(), ws_user.end());
    wstring ws_psw(password);
    string psw_str(ws_psw.begin(), ws_psw.end());

    std::string port_str = std::to_string(port);
    _bstr_t strCnn("Driver={SQL Server};Server="+host_str+","+port_str+";Database="+db_str+";User ID="+user_str+";Password="+psw_str+";");
</code>```

But it says:

```<code>Error E0289 no instance of constructor "_bstr_t::_bstr_t" matches the argument list
Error C2664 '_bstr_t::_bstr_t(const _bstr_t &) throw()': cannot convert argument 1 from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'const char *'
</code>```

答:
When you construct the string to pass to strCnn, it is a std::string object.  _bstr_t does not have a constructor that takes a string, but does have one that takes const char * (which is what the error message is telling you.

The simple fix is to construct your string and save that in a local variable, then pass that string (converted to a const char *) to the _bstr_t constructor.

```<code>std::string port_str = std::to_string(port);
std::string connection = "Driver={SQL Server};Server="+host_str+","+port_str+";Database="+db_str+";User ID="+user_str+";Password="+psw_str+";";
_bstr_t strCnn(connection.c_str());
</code>```

This may not be the optimal way to construct a string (std::stringstream may be better).

Since your original parameter strings are wide characters, you can construct the connection string with wide characters (and std::wstring).

Body:
I have _bstr_t string and I have wchar_t and one unsigned int variables which I want to put to the string...

_bstr_t strCnn("Driver={SQL Server};Server=some_host,some_port;Database=some_db;User ID=some_user;Password=some_psw;");

wchar_t *host,
unsigned int port,
wchar_t *db_name,
wchar_t *user,
wchar_t *password,

These 5 variables I pass to the function which does connection. Can you please guide me how to insert them to connection string.

I tried this way:

    wstring ws(host);
    string host_str(ws.begin(), ws.end());
    wstring ws_db(db_name);
    string db_str(ws_db.begin(), ws_db.end());
    wstring ws_user(user);
    string user_str(ws_user.begin(), ws_user.end());
    wstring ws_psw(password);
    string psw_str(ws_psw.begin(), ws_psw.end());

    std::string port_str = std::to_string(port);
    _bstr_t strCnn("Driver={SQL Server};Server="+host_str+","+port_str+";Database="+db_str+";User ID="+user_str+";Password="+psw_str+";");

But it says:

Error E0289 no instance of constructor "_bstr_t::_bstr_t" matches the argument list
Error C2664 '_bstr_t::_bstr_t(const _bstr_t &) throw()': cannot convert argument 1 from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'const char *'

Body:
When you construct the string to pass to strCnn, it is a std::string object.  _bstr_t does not have a constructor that takes a string, but does have one that takes const char * (which is what the error message is telling you.

The simple fix is to construct your string and save that in a local variable, then pass that string (converted to a const char *) to the _bstr_t constructor.

std::string port_str = std::to_string(port);
std::string connection = "Driver={SQL Server};Server="+host_str+","+port_str+";Database="+db_str+";User ID="+user_str+";Password="+psw_str+";";
_bstr_t strCnn(connection.c_str());

This may not be the optimal way to construct a string (std::stringstream may be better).

Since your original parameter strings are wide characters, you can construct the connection string with wide characters (and std::wstring).


答:
This can be achieved with a recursive method.

const arr = [{id: "5", parent_id: "0", lable: "Movie"},
{id: "20", parent_id: "5", lable: "Action"},
{id: "15", parent_id: "43", lable: "J.K Rowling"},
{id: "43", parent_id: "0", lable: "Book"},
{id: "20", parent_id: "2", lable: "James Bond Series"},
{id: "3", parent_id: "0", lable: "Music"},
{id: "39", parent_id: "15", lable: "Harry Potter Series"}];

const render = (arr, id) => {
  const div = document.createElement('div');
  const span = document.createElement('span');
  span.innerText = arr.find(e => e.id === id).lable;
  div.appendChild(span);
  arr.filter(e => e.parent_id === id).forEach(sub => {
    div.appendChild(render(arr, sub.id));
  });
  return div;
}

arr.filter(e => e.parent_id === "0").forEach(main =>    document.querySelector('div').appendChild(render(arr, main.id)));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  margin-left: 5px;
}</code>```

```

Title: How to show category subcategory based on array

Body:
This can be achieved with a recursive method.

const arr = [{id: "5", parent_id: "0", lable: "Movie"},
{id: "20", parent_id: "5", lable: "Action"},
{id: "15", parent_id: "43", lable: "J.K Rowling"},
{id: "43", parent_id: "0", lable: "Book"},
{id: "20", parent_id: "2", lable: "James Bond Series"},
{id: "3", parent_id: "0", lable: "Music"},
{id: "39", parent_id: "15", lable: "Harry Potter Series"}];

const render = (arr, id) => {
  const div = document.createElement('div');
  const span = document.createElement('span');
  span.innerText = arr.find(e => e.id === id).lable;
  div.appendChild(span);
  arr.filter(e => e.parent_id === id).forEach(sub => {
    div.appendChild(render(arr, sub.id));
  });
  return div;
}

arr.filter(e => e.parent_id === "0").forEach(main =>    document.querySelector('div').appendChild(render(arr, main.id)));

div {
  margin-left: 5px;
}

<div></div>


问:
How to validate JWT during websocket request. .net core
I am working on a small .net core app that uses JWT authentication and websockets.

I have succesfully implemented generating and validating tokens for standard web api controllers. However I also want to validate the token for a WebSocket request which of course won't work with the [Authorize] attribute.

I have setup my middleware pipeline like this:

```<code>app.UseWebSockets();
app.Use(async (http, next) => {
      if (http.WebSockets.IsWebSocketRequest == false) {
          await next();
          return;
      }
      /// Handle websocket request here. How to check if token is valid?
});

// secretKey contains a secret passphrase only your server knows
var secretKey = .....;
var signKey = new SigningCredentials (
    new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)),
    SecurityAlgorithms.HmacSha256
);

var tokenValidationParameters = new TokenValidationParameters {
    ValidateIssuer = false,
    ValidateAudience = false,

    // The signing key must match!
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = signKey.Key,

    // Validate the token expiry
    ValidateLifetime = true,

    // If you want to allow a certain amount of clock drift, set that here:
    ClockSkew = TimeSpan.FromMinutes(1),
};

app.UseJwtBearerAuthentication(new JwtBearerOptions {
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = tokenValidationParameters
});
</code>```

答:
I worked this out slightly different way as I was depending on WebSocket() on the client side.

So on the client side first I authenticate user to get token and attach it to the header as subprotocol:

```<code>socket = new WebSocket(connectionPath, ["client",token]);
</code>```

Token is sent within request header under sec-websocket-protocol key.
So before authentication kicks in I extract token and append it to the context.

```<code>        .AddJwtBearer(x =>
        {
          // ....

            x.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    if (context.Request.Headers.ContainsKey("sec-websocket-protocol") && context.HttpContext.WebSockets.IsWebSocketRequest)
                    {
                        var token = context.Request.Headers["sec-websocket-protocol"].ToString();
                        // token arrives as string = "client, xxxxxxxxxxxxxxxxxxxxx"
                        context.Token = token.Substring(token.IndexOf(',') + 1).Trim();
                        context.Request.Headers["sec-websocket-protocol"] = "client";
                    }
                    return Task.CompletedTask;
                }
            };
</code>```

Then on my WebSocket controller I simply stick [Authorize] attribute:

```<code>    [Authorize]
    [Route("api/[controller]")]
    public class WSController : Controller
    {
        [HttpGet]
        public async Task Get()
        {
            var context = ControllerContext.HttpContext;
            WebSocket currentSocket = await context.WebSockets.AcceptWebSocketAsync("client"); // it's important to make sure the response returns the same subprotocol
           // ...
    }
</code>```

Body:
I am working on a small .net core app that uses JWT authentication and websockets.

I have succesfully implemented generating and validating tokens for standard web api controllers. However I also want to validate the token for a WebSocket request which of course won't work with the [Authorize] attribute.

I have setup my middleware pipeline like this:

app.UseWebSockets();
app.Use(async (http, next) => {
      if (http.WebSockets.IsWebSocketRequest == false) {
          await next();
          return;
      }
      /// Handle websocket request here. How to check if token is valid?
});

// secretKey contains a secret passphrase only your server knows
var secretKey = .....;
var signKey = new SigningCredentials (
    new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)),
    SecurityAlgorithms.HmacSha256
);

var tokenValidationParameters = new TokenValidationParameters {
    ValidateIssuer = false,
    ValidateAudience = false,

    // The signing key must match!
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = signKey.Key,

    // Validate the token expiry
    ValidateLifetime = true,

    // If you want to allow a certain amount of clock drift, set that here:
    ClockSkew = TimeSpan.FromMinutes(1),
};

app.UseJwtBearerAuthentication(new JwtBearerOptions {
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = tokenValidationParameters
});

Body:
I worked this out slightly different way as I was depending on WebSocket() on the client side.

So on the client side first I authenticate user to get token and attach it to the header as subprotocol:

socket = new WebSocket(connectionPath, ["client",token]);

Token is sent within request header under sec-websocket-protocol key.
So before authentication kicks in I extract token and append it to the context.

        .AddJwtBearer(x =>
        {
          // ....

            x.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    if (context.Request.Headers.ContainsKey("sec-websocket-protocol") && context.HttpContext.WebSockets.IsWebSocketRequest)
                    {
                        var token = context.Request.Headers["sec-websocket-protocol"].ToString();
                        // token arrives as string = "client, xxxxxxxxxxxxxxxxxxxxx"
                        context.Token = token.Substring(token.IndexOf(',') + 1).Trim();
                        context.Request.Headers["sec-websocket-protocol"] = "client";
                    }
                    return Task.CompletedTask;
                }
            };

Then on my WebSocket controller I simply stick [Authorize] attribute:

    [Authorize]
    [Route("api/[controller]")]
    public class WSController : Controller
    {
        [HttpGet]
        public async Task Get()
        {
            var context = ControllerContext.HttpContext;
            WebSocket currentSocket = await context.WebSockets.AcceptWebSocketAsync("client"); // it's important to make sure the response returns the same subprotocol
           // ...
    }


问:
RegEx for identifying alphanumeric patterns with special chars and boundaries
I am attempting to return one of these strings (depends on input):

```<code>f23/24  /or/  f23-24   /or/  f23+24
</code>```

(Ideally, it would be great if it ALWAYS returned format f23-24), regardless of input

from this type of string:

```<code>build-f23/24 1st pass demo (50:50)   #Should output f23-24 or f23/24
build-f17-22 1st pass demo (50:50)   #Should output f17-22
build-f-1 +14 1st pass demo (50:50)  #Should output f1-14 or f1+14
</code>```

Exception:

Some of the strings will not have the second set of numbers:

```<code>build-f45 1st pass demo (50:50)      #Should output f45
</code>```

Where I am currently at:

Thus far, I have this regex, but it always fails if the separator char is a slash:

```<code>regex = r"(\s?)(\-?)(f)(\s?)([\+\-\/]?)(\d\d*)(-?)(\d?\d*)"
tmp = re.search(regex, val)[0]
</code>```

答:
This is a quite complicated expression, which I'm not sure if I understand the ration, but maybe let's start with an expression to output what is desired, maybe we could solve the problem step by step:

```<code>.+?(-.+?)([a-z][0-9]+?)?\s|(?:[+][0-9])?([0-9]+)?(.+)
</code>```

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r".+?(-.+?)([a-z][0-9]+?)?\s|(?:[+][0-9])?([0-9]+)?(.+)"

test_str = ("build-f23/24 1st pass demo (50:50)\n"
    "build-f17-22 1st pass demo (50:50)\n"
    "build-f-1 +14 1st pass demo (50:50)")

subst = "\\1\\2\\3"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

DEMO

Body:
I am attempting to return one of these strings (depends on input):

f23/24  /or/  f23-24   /or/  f23+24

(Ideally, it would be great if it ALWAYS returned format f23-24), regardless of input

from this type of string:

build-f23/24 1st pass demo (50:50)   #Should output f23-24 or f23/24
build-f17-22 1st pass demo (50:50)   #Should output f17-22
build-f-1 +14 1st pass demo (50:50)  #Should output f1-14 or f1+14

Exception:

Some of the strings will not have the second set of numbers:

build-f45 1st pass demo (50:50)      #Should output f45

Where I am currently at:

Thus far, I have this regex, but it always fails if the separator char is a slash:

regex = r"(\s?)(\-?)(f)(\s?)([\+\-\/]?)(\d\d*)(-?)(\d?\d*)"
tmp = re.search(regex, val)[0]

Body:
This is a quite complicated expression, which I'm not sure if I understand the ration, but maybe let's start with an expression to output what is desired, maybe we could solve the problem step by step:

.+?(-.+?)([a-z][0-9]+?)?\s|(?:[+][0-9])?([0-9]+)?(.+)

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r".+?(-.+?)([a-z][0-9]+?)?\s|(?:[+][0-9])?([0-9]+)?(.+)"

test_str = ("build-f23/24 1st pass demo (50:50)\n"
    "build-f17-22 1st pass demo (50:50)\n"
    "build-f-1 +14 1st pass demo (50:50)")

subst = "\\1\\2\\3"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

DEMO


答: You can try to calculate the angle, but an easier way could be to check whether the Pythagorean Theorem applies. For that you'll need to calculate the size of the three edges and then check whether A^2 + B^2 ~= C^2

Title: is there a way to examine if an angle is a right angle programmatically?


问:
Webtorrent client/player for Ionic 4
I would like to implement Webtorrent into a Ionic 4 app. I already managed to play .m3u8 streams flawlessly. All i need now its the webtorrent part which I'm not too familiar with.

I'm using <video src='url.m3u8'></video> tag for .m3u8 streams, and it seems to work fine in Ionic 4. I want to be able to download torrent video files and stream/play the video on Ionic either using <video> tag or video-player component.

Please I need some help. I've been trying everything that I know and that I can find online, but so far nothing has helped. Any Help would be appreciated.

Thank you in advance.

```<code>edited: Sun, May 26th, 2019 at 7:59:02 PM
</code>```

This is the error I get with the implementation I'm trying. Anyone has any idea what might be the problem.

Here's a snapshot of my code.

Picture Here

tell me what you guys think.

Thank you in advance.

答:
Ok, after a few days trying different methods, I found the Solution. Really easy btw.

here's a
picture

here's the code i used.

```<code>    import { WebTorrent } from 'webtorrent';

    declare var WebTorrent: WebTorrent;

        ....

    playVideo() {

    const client = WebTorrent();
    const magnetURL = 'https://webtorrent.io/torrents/sintel.torrent';

    client.add(magnetURL, function (torrent) {
      // document.getElementById('hash').textContent = 'Client downloading: ' + torrent.infoHash;
      torrent.files.forEach(function (file) {
        torrent.on('download', function (bytes) {
          document.getElementById('download').textContent = 'just downloaded: ' + bytesToSize(bytes);
          document.getElementById('tdownload').textContent = 'total downloaded: ' + bytesToSize(torrent.downloaded);
          document.getElementById('sdownload').textContent = 'download speed: ' + bytesToSize(torrent.downloadSpeed);
          document.getElementById('pdownload').textContent = toPercentage(torrent.progress);
        });
        torrent.files.find(function (file) {
          return file.name.endsWith('.mp4') || file.name.endsWith('.avi') || file.name.endsWith('.mkv') || file.name.endsWith('.mpeg');
        });
        file.renderTo('#video', function (err, element) {
          presentToast(magnetURL);
        });
      });
    });
    function presentToast(text: string) {
      this.presentToast(text);
    }
    function bytesToSize(bytes) {
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      if (bytes === 0) { return '0 Bytes'; }
      const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
      return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
    }

    function toPercentage(dec) {
      dec = dec.toString();
      const a = dec.split('.');
      dec = a[1];
      dec = dec.substr(0, 4);
      return dec = (dec / 100) + '%';
    }
  }
</code>```

I have 2 issues with it though. I can only play the sintel.mp4 once it's reached 99.89%, but I want to be able to stream it while its downloading.
   My second problem is that I can only download and play the Sintel.torrent. I tried using other magnet links and it doesn't do anything. I'm guessing it has something to do with the way the magnet url is generated.

Title: Webtorrent client/player for Ionic 4

Body:
I would like to implement Webtorrent into a Ionic 4 app. I already managed to play .m3u8 streams flawlessly. All i need now its the webtorrent part which I'm not too familiar with.

I'm using <video src='url.m3u8'></video> tag for .m3u8 streams, and it seems to work fine in Ionic 4. I want to be able to download torrent video files and stream/play the video on Ionic either using <video> tag or video-player component.

Please I need some help. I've been trying everything that I know and that I can find online, but so far nothing has helped. Any Help would be appreciated.

Thank you in advance.

edited: Sun, May 26th, 2019 at 7:59:02 PM

This is the error I get with the implementation I'm trying. Anyone has any idea what might be the problem.

Here's a snapshot of my code.

Picture Here

tell me what you guys think.

Thank you in advance.

Body:
Ok, after a few days trying different methods, I found the Solution. Really easy btw.

here's a
picture

here's the code i used.

    import { WebTorrent } from 'webtorrent';

    declare var WebTorrent: WebTorrent;

        ....

    playVideo() {

    const client = WebTorrent();
    const magnetURL = 'https://webtorrent.io/torrents/sintel.torrent';

    client.add(magnetURL, function (torrent) {
      // document.getElementById('hash').textContent = 'Client downloading: ' + torrent.infoHash;
      torrent.files.forEach(function (file) {
        torrent.on('download', function (bytes) {
          document.getElementById('download').textContent = 'just downloaded: ' + bytesToSize(bytes);
          document.getElementById('tdownload').textContent = 'total downloaded: ' + bytesToSize(torrent.downloaded);
          document.getElementById('sdownload').textContent = 'download speed: ' + bytesToSize(torrent.downloadSpeed);
          document.getElementById('pdownload').textContent = toPercentage(torrent.progress);
        });
        torrent.files.find(function (file) {
          return file.name.endsWith('.mp4') || file.name.endsWith('.avi') || file.name.endsWith('.mkv') || file.name.endsWith('.mpeg');
        });
        file.renderTo('#video', function (err, element) {
          presentToast(magnetURL);
        });
      });
    });
    function presentToast(text: string) {
      this.presentToast(text);
    }
    function bytesToSize(bytes) {
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      if (bytes === 0) { return '0 Bytes'; }
      const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
      return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
    }

    function toPercentage(dec) {
      dec = dec.toString();
      const a = dec.split('.');
      dec = a[1];
      dec = dec.substr(0, 4);
      return dec = (dec / 100) + '%';
    }
  }

I have 2 issues with it though. I can only play the sintel.mp4 once it's reached 99.89%, but I want to be able to stream it while its downloading.
   My second problem is that I can only download and play the Sintel.torrent. I tried using other magnet links and it doesn't do anything. I'm guessing it has something to do with the way the magnet url is generated.


问:
init let properties with reference to self in subclass in swift
I'm learning swift and coming across the following problem very often. I will have a class with a property that feels as if it should be a let property as it will only be set once. I'd also like this child object to maintain a reference to its owner, which should also be a let property, as the parent relationship will not change. The problem arises when the parent class subclasses another class and all let properties need to be set before super.init () is run but requires a reference to self to init.

Here's a quick example

```<code>class NodeView: UIView {
    let _nodePlugView: NodePlugView

    init (node: Node) {
        _nodePlugView = NodePlugView (parentView: self)
        super.init ()
    }
}
</code>```

Of course, I could just use var for these _nodePlugView but it doesn't feel quite right. Is there another pattern that people would recommend?

答:
You could use a lazy variable.

```<code>lazy var _nodePlugView: NodePlugView = NodePlugView(parentView: self)
</code>```

Lazy variables are initialized after the object itself is initialized.

If you really need this to be a let constant, an alternative might be to have an initializer for NodePlugView that doesn't take the parentView parameter, and have a method for setting the parentView after it's been initialized.

```<code>let _nodePlugView: NodePlugView

init (node: Node) {
    _nodePlugView = NodePlugView()
    super.init()
    _nodePlugView.setParentView(self)
}
</code>```

Body:
I'm learning swift and coming across the following problem very often. I will have a class with a property that feels as if it should be a let property as it will only be set once. I'd also like this child object to maintain a reference to its owner, which should also be a let property, as the parent relationship will not change. The problem arises when the parent class subclasses another class and all let properties need to be set before super.init () is run but requires a reference to self to init.

Here's a quick example

class NodeView: UIView {
    let _nodePlugView: NodePlugView

    init (node: Node) {
        _nodePlugView = NodePlugView (parentView: self)
        super.init ()
    }
}

Of course, I could just use var for these _nodePlugView but it doesn't feel quite right. Is there another pattern that people would recommend?

Body:
You could use a lazy variable.

lazy var _nodePlugView: NodePlugView = NodePlugView(parentView: self)

Lazy variables are initialized after the object itself is initialized.

If you really need this to be a let constant, an alternative might be to have an initializer for NodePlugView that doesn't take the parentView parameter, and have a method for setting the parentView after it's been initialized.

let _nodePlugView: NodePlugView

init (node: Node) {
    _nodePlugView = NodePlugView()
    super.init()
    _nodePlugView.setParentView(self)
}


问:
Validating reCAPTCHA v3 in Django
In reCAPTCHA V2, I could verify in the views.py itself. However in V3 I don't know how to proceed. Now I'm using it in development with 127.0.0.1.

First I have generated the site key and the secret key.
In settings.py I have added secret key,
GOOGLE_RECAPTCHA_SECRET_KEY = 'my_secret_key_here'

Then in my signup.html I have,

Unlike previous there is no
 tag to add the checkbox. The script itself is rendering the recaptcha symbol in the side of my browser.

My question is,

How can I validate using grecaptcha.execute.

Do I have to add the script with my site key to every page I want to protect from spam or is there any simple way

答:
this article looks help your problem: How to implement google recaptcha v3 on your django.

The summary:

call the execute method, this will return token that you need to verify in your backend.

You can save it somewhere in your form

send the token when submitting form

verify the token in your view

Do I have to add the script with my site key to every page I want to protect from spam or is there any simple way

Exactly, you need to add the script on every page you want to protect from spam.

Title: Validating reCAPTCHA v3 in Django


问:
What's the difference between casting a long to int versus using a bitwise AND in order to get the 4 least significant bytes?
I know that in order to get the 4 least significant bytes of a number of type long I can cast it to int/unsigned int or use a bitwise AND (& 0xFFFFFFFF).

This code produces the following output:

#include <stdio.h>

int main()
{
  long n = 0x8899AABBCCDDEEFF;
  printf("0x%016lX\n", n);
  printf("0x%016X\n", (int)n);
  printf("0x%016X\n", (unsigned int)n);
  printf("0x%016lX\n", n & 0xFFFFFFFF);
}
```

<p>Output:</p>

```0x8899AABBCCDDEEFF
0x00000000CCDDEEFF
0x00000000CCDDEEFF
0x00000000CCDDEEFF
```

Does that mean that the two methods used are equivalent? If so, do they always produce the same output regardless of the platform/compiler?

Also, is there any catch or pitfall while casting to unsigned int rather than int for the purpose of this question?

Finally, why is the output the same if you change the number n to be an unsigned long instead?

答:
The methods are definitely different.

According to integral conversion rules (cf, for example, this online c++11 standard), a conversion (e.g. through an explicit cast) from one integral type to another depends on whether the destination type is signed or unsigned. If the destination type is unsigned, one can rely on a "modulo 2n" truncation, whereas with signed destination types one could tap into implementation defined behaviour:

4.7 Integral conversions [conv.integral]

2 If the destination type is unsigned, the resulting value is the
  least unsigned integer congruent to the source integer (modulo 2n
  where n is the number of bits used to represent the unsigned type). [
  Note: In a two's complement representation, this conversion is
  conceptual and there is no change in the bit pattern (if there is no
  truncation).  — end note ]

3 If the destination type is signed, the value is unchanged if it can
  be represented in the destination type (and bit-field width);
  otherwise, the value is implementation-defined.

Body:
I know that in order to get the 4 least significant bytes of a number of type long I can cast it to int/unsigned int or use a bitwise AND (& 0xFFFFFFFF).

This code produces the following output:

#include <stdio.h>

int main()
{
  long n = 0x8899AABBCCDDEEFF;
  printf("0x%016lX\n", n);
  printf("0x%016X\n", (int)n);
  printf("0x%016X\n", (unsigned int)n);
  printf("0x%016lX\n", n & 0xFFFFFFFF);
}

Output:

0x8899AABBCCDDEEFF
0x00000000CCDDEEFF
0x00000000CCDDEEFF
0x00000000CCDDEEFF

Does that mean that the two methods used are equivalent? If so, do they always produce the same output regardless of the platform/compiler?

Also, is there any catch or pitfall while casting to unsigned int rather than int for the purpose of this question?

Finally, why is the output the same if you change the number n to be an unsigned long instead?


问:
Why does setState in this promise take longer to update than the same code as an async function?
I have 2 versions of the same fetch functions here, the first one uses promises, the second one async-await. To my understanding there should be no difference between those two, so I'd appreciate some clarification to what's actually happening here.

The following version, which uses async-await, sets the state by the time console log runs:

```<code>async fetchPostList(query) {
  const response = await fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
  const data = await response.json()
  this.setState({ postList: data });
  console.log(this.state.postList);
}
</code>```

Console: Array(474) [ ... ]

The version that uses promises sets state after the console log:

```<code>fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
    .then( response => response.json())
    .then( data => this.setState({ postList: data }))
  console.log(this.state.postList);
}
</code>```

Console: Array []

答:
If you want to log the updated state you must wait the Promise to resolve some data, only when you have data you can log the data itself:</p>

```<code>fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
   .then( response => response.json())
   .then( data => {
     this.setState({ postList: data })
     // here you have data
     console.log(this.state.postList);
   })
// here you do not have data
}
</code>```

Body:
I have 2 versions of the same fetch functions here, the first one uses promises, the second one async-await. To my understanding there should be no difference between those two, so I'd appreciate some clarification to what's actually happening here.

The following version, which uses async-await, sets the state by the time console log runs:

async fetchPostList(query) {
  const response = await fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
  const data = await response.json()
  this.setState({ postList: data });
  console.log(this.state.postList);
}

Console: Array(474) [ ... ]

The version that uses promises sets state after the console log:

fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
    .then( response => response.json())
    .then( data => this.setState({ postList: data }))
  console.log(this.state.postList);
}

Console: Array []

Body:
If you want to log the updated state you must wait the Promise to resolve some data, only when you have data you can log the data itself:

fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
   .then( response => response.json())
   .then( data => {
     this.setState({ postList: data })
     // here you have data
     console.log(this.state.postList);
   })
// here you do not have data
}


问:
Batch countdown timer that doesn't clear rest of output?
I am trying to create a batch timer that doesn't clear the output above it.

I have a timer function created, but am looking to improve it so that I can still view the output above it without having lines on lines of a countdown in the output. My current function is:

```<code>@echo off
echo KEEP THIS OUTPUT
CALL :timer 10
rem Do more things...
EXIT

:Timer
set time=%~1

:loop
cls

echo Countdown - [%time%]

set /a time=%time%-1
if %time%==0 goto timesup

ping localhost -n 2 > nul
goto loop

:timesup
echo Timer completed!!
EXIT /B 0
</code>```

Currently, the timer clears the screen, but I would like to make it so that the output above this timer stays.

For example, at 10 seconds, the output should be:

```<code>KEEP THIS OUTPUT
Countdown - [10]
</code>```

And then the output should change to:

```<code>KEEP THIS OUTPUT
Countdown - [9]
</code>```

The output should NOT be:

```<code>KEEP THIS OUTPUT
Countdown - [10]
Countdown - [9]
</code>```

and should NOT be:

```<code>Countdown - [9]
</code>```

Is there any way to do this?

答:
Another way to output any length strings repeatedly to the same line is using Ansi ESC sequences

(which are supported again in the console of Windows 10 >=Treshold2).

As some editors have problems creating/saving this to a batch file, certutil is used to create it.

```<code>:: Q:\Test\2019\05\27\SO_56330510.cmd
@echo off
if not defined ESC call :GetEsc
echo KEEP THIS OUTPUT
CALL :timer 10
rem Do more things...
EXIT /B

:Timer
Echo Countdown - [%1]
For /l %%L in (%1,-1,0) Do Echo %Ansi%Countdown - [%%L]&Timeout /t 1 >Nul
echo %Ansi%Timer completed!!
EXIT /B 0

:GetEsc just in case you can't create and save the ESC[ sequence in your editor
echo 1B 5B>ESC.hex
Del ESC.bin >NUL 2>&1
certutil -decodehex ESC.hex ESC.bin >NUL 2>&1
Set /P ESC=<ESC.bin
set "Ansi=%ESC%1F%ESC%0J"
Del ESC.* >NUL 2>&1
</code>```

Body:
I am trying to create a batch timer that doesn't clear the output above it.

I have a timer function created, but am looking to improve it so that I can still view the output above it without having lines on lines of a countdown in the output. My current function is:

@echo off
echo KEEP THIS OUTPUT
CALL :timer 10
rem Do more things...
EXIT

:Timer
set time=%~1

:loop
cls

echo Countdown - [%time%]

set /a time=%time%-1
if %time%==0 goto timesup

ping localhost -n 2 > nul
goto loop

:timesup
echo Timer completed!!
EXIT /B 0

Currently, the timer clears the screen, but I would like to make it so that the output above this timer stays.

For example, at 10 seconds, the output should be:

KEEP THIS OUTPUT
Countdown - [10]

And then the output should change to:

KEEP THIS OUTPUT
Countdown - [9]

The output should NOT be:

KEEP THIS OUTPUT
Countdown - [10]
Countdown - [9]

and should NOT be:

Countdown - [9]

Is there any way to do this?

Body:
Another way to output any length strings repeatedly to the same line is using Ansi ESC sequences

(which are supported again in the console of Windows 10 >=Treshold2).

As some editors have problems creating/saving this to a batch file, certutil is used to create it.

:: Q:\Test\2019\05\27\SO_56330510.cmd
@echo off
if not defined ESC call :GetEsc
echo KEEP THIS OUTPUT
CALL :timer 10
rem Do more things...
EXIT /B

:Timer
Echo Countdown - [%1]
For /l %%L in (%1,-1,0) Do Echo %Ansi%Countdown - [%%L]&Timeout /t 1 >Nul
echo %Ansi%Timer completed!!
EXIT /B 0

:GetEsc just in case you can't create and save the ESC[ sequence in your editor
echo 1B 5B>ESC.hex
Del ESC.bin >NUL 2>&1
certutil -decodehex ESC.hex ESC.bin >NUL 2>&1
Set /P ESC=<ESC.bin
set "Ansi=%ESC%1F%ESC%0J"
Del ESC.* >NUL 2>&1


问:
unsupported operand type(s) for |: 'str' and 'bool'
Both of the below statements are working fine:

```<code>df_train[df_train['pickup_longitude']<-73]
df_train[df_train['pickup_longitude']>73]
</code>```

Not able to run this:

```<code>df_train = df_train.drop(((df_train[df_train['pickup_longitude']<-73])|(df_train[df_train['pickup_longitude']>73])).index, axis=0)
</code>```

答:
I believe you want only the rows where pickup_longitude is above -73 and below 73. Accordingly, you can do this instead:

```<code>df_train = df_train[(df_train['pickup_longitude'] > -73) & (df_train['pickup_longitude'] < 73)]
</code>```

Body:
Both of the below statements are working fine:

df_train[df_train['pickup_longitude']<-73]
df_train[df_train['pickup_longitude']>73]

Not able to run this:

df_train = df_train.drop(((df_train[df_train['pickup_longitude']<-73])|(df_train[df_train['pickup_longitude']>73])).index, axis=0)

Body:
I believe you want only the rows where pickup_longitude is above -73 and below 73. Accordingly, you can do this instead:

df_train = df_train[(df_train['pickup_longitude'] > -73) & (df_train['pickup_longitude'] < 73)]


问:
How to debug the Citrix ICA error "The session limit has been reached"?
Apologies in advance for somewhat vague information. I am new to Citrix XenApp/XenDesktop technology and am just looking for generic troubleshooting information.

At my place of employment we have kiosks that are configured to connect to a SaaS webapp. These kiosk have either the Citrix XenApp or XenDesktop installed.

One of the icons launches the IE browser that connects to the SaaS app using a preconfigured user account. Sometimes, however, instead of launching the browser, the system displays the "The session limit has been reached. Please contact your system administrator." error shown in below image.

The people administering these kiosks think that this message comes from the SaaS web application but that application does not enforce any limits on how many session are open for a given account under a given time.

Also considering how Citrix XenApp/XenDesktop works I would think (but maybe I am wrong) that if the SaaS app did reject a user login, we would be displayed an error message in Internet Explorer instead of this ICA prompt.

So I think that the issue here could be that the message is not about login sessions made to the background SaaS app but either about Citrix sessions or perhaps previous IE browsers somehow running in the background(?)

However our company's Citrix team looked at this and noticed that "Citrix was still active" when this prompt was displayed. The conclusion was then that Citrix is for that reason not the cause here.

So I wanted here to ask some questions on what things I could consider as causes and where I could look in the hopes of getting started on this issue.

This would be for XenApp / XenDesktop 7.18.

The questions I have:

Does XenApp / XenDesktop have log files that can be consulted for
debugging issues like this?

Is it possible to get XenApp / XenDesktop to run in debug mode (to
output more details to the log files)?

Does Citrix have configuration settings that could lead it to
have an issue like this?

答:
A.    First check the event logs and see when you facing this issue so does any event logs generated.

B.  Also you can check the ICA configuration tool for session settings and checked if session settings are set to NEVER.

C.  The ICA listener configuration tool is located at Start > All Programs > Citrix > Administration Tools > ICA Listener Configuration.


答:
Yes, there is.</p>

```<code>x = [0,0.5,1]
y = [0,0.5,0]
points = [np.array(point) for point in zip(x,y)]
a, b, c = points
ba = a - b
bc = c - b
cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
angle_rad = np.arccos(cosine_angle)
angle_deg = np.rad2deg(angle_rad)
print(angle_deg) # 90.0
</code>```

Body:
i plot an angle in python

here is the code

x = [0,0.5,1]
y = [0,0.5,0]
plt.scatter(x,y)
plt.plot(x,y)
plt.show()

is there a way to examine if the angle is a right angle programmatically?

Body:
Yes, there is.

x = [0,0.5,1]
y = [0,0.5,0]
points = [np.array(point) for point in zip(x,y)]
a, b, c = points
ba = a - b
bc = c - b
cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
angle_rad = np.arccos(cosine_angle)
angle_deg = np.rad2deg(angle_rad)
print(angle_deg) # 90.0


问:
get data from json api but not displaying it in an html table
I am interested in how to retrieve data from a website and display it in html. then I found an example from a website and tried changing some code in it. but then the existing data is not displayed by the browser. this is an example:

</scrypt>
$(document).ready(function() {
        $('#example').DataTable({
            "processing": true,
            "ajax": "https://www.zpool.ca/api/miners",

            column: [{
                "algo"
            }, {
                "version"
            }, {
                "count"
    }]
  });
});</scrypt>```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<script src='https://code.jquery.com/jquery-3.3.1.js'/>
<script src='https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js'/>
    <table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Algo</th>
                <th>Version</th>
                <th>Count</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Algo</th>
                <th>Version</th>
                <th>Count</th>
            </tr>
        </tfoot>
    </table></code>```

can some one fix this ??

答:
Please read the docs before posting a question, there is an exact example there
https://datatables.net/examples/ajax/custom_data_flat.html

fixed code:

```<code>$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": {
            "url": "https://www.zpool.ca/api/miners",
            "dataSrc": ""
        },
        "columns": [
            { "data": "algo" },
            { "data": "version" },
            { "data": "count" }
        ]
    } );
} );
</code>```

Body:
I am interested in how to retrieve data from a website and display it in html. then I found an example from a website and tried changing some code in it. but then the existing data is not displayed by the browser. this is an example:

</scrypt>
$(document).ready(function() {
        $('#example').DataTable({
            "processing": true,
            "ajax": "https://www.zpool.ca/api/miners",

            column: [{
                "algo"
            }, {
                "version"
            }, {
                "count"
    }]
  });
});</scrypt>

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">

Body:
Please read the docs before posting a question, there is an exact example there
https://datatables.net/examples/ajax/custom_data_flat.html

fixed code:

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": {
            "url": "https://www.zpool.ca/api/miners",
            "dataSrc": ""
        },
        "columns": [
            { "data": "algo" },
            { "data": "version" },
            { "data": "count" }
        ]
    } );
} );


问:
MQL4 to C++ dll on microsoft Visual Studio 2017 Community
How can I create a DLL file in Microsoft Visual Studio 2017 Community that can not be decompiled
and transfer functions from my mq4 indicator to the DLL file and connect them together?

I do not know any language other than MQL4

答: Current version of MetaEditor has "MQL5 Cloud Protector" option that adds encryption to already pretty good default anti reverse engineering protection of MLQ4/MQL5 executables making cracking it economically unjustified. It's cheaper to recreate algorithm and code it from scratch than to break into exec.</p>


问:
Android Studio: Hand Gesture Recognition fatal error: 'ext/atomicity.h' file not found
So I am trying this app by Eaglesky in Android Studio:
https://github.com/eaglesky/HandGestureApp
but got an error when using right-clicking and choosing ndk-build.

The Error

I was thinking this might be due to ndk no longer supports gnustl_static so I had to change it to c++_static and eventually got the error.

My Application.mk

```<code>APP_PLATFORM := android-16
APP_ABI := all
APP_CPPFLAGS := -frtti -fexceptions
APP_STL := c++_static
</code>```

My apologize, I'm still quite new to Android Development.

答:
Your problem is using:

APP_STL := c++_static

OpenCV requires gnuc library:

APP_STL := gnustl_shared

Make sure NDK tool chain is also gnu not clang.

Body:
So I am trying this app by Eaglesky in Android Studio:
https://github.com/eaglesky/HandGestureApp
but got an error when using right-clicking and choosing ndk-build.

The Error

I was thinking this might be due to ndk no longer supports gnustl_static so I had to change it to c++_static and eventually got the error.

My Application.mk

APP_PLATFORM := android-16
APP_ABI := all
APP_CPPFLAGS := -frtti -fexceptions
APP_STL := c++_static

My apologize, I'm still quite new to Android Development.


问:
VB6: CDate(some date) returns runtime error 13
HI,

I have this string: "2010-12-27 23:05:36.0". When I parse it with CDate like this: CDate("2010-12-27 23:05:36.0") it returns error 13.
When I remove the '.0' from the string it is working fine.

The date string comes from a database where there is a mixture of dates formatted like this: 'yyyy-mm-dd' and 'yyyy-mm-dd hh-MM-ss.n' What would be the easy way to get rid of the error 13?

答:
The best solution is to NOT store dates as strings. All databases can handle dates and ADO can return date values directly without converting them to strings. If the date data is stored as a date type you probably don't need to use CDate at all. The returned recordset will contain the underlying data as a Date variant.

If the data is stored as a string after all, you could possibly modify your SQL statement to convert the string to a date using your DB's built-in functions. In SQL Server you can do that with the CAST and CONVERT functions, e.g.

```<code>CAST(myDateAsTextField as datetime)
</code>```

SQL Server's DATETIME data type accepts fractional seconds with 1 to 3 digits.

Finally, you can check the contents of the string and convert it to a different form before calling CDate. This should be used as a last resort if you can't fix the data at the database level.

Body:
The best solution is to NOT store dates as strings. All databases can handle dates and ADO can return date values directly without converting them to strings. If the date data is stored as a date type you probably don't need to use CDate at all. The returned recordset will contain the underlying data as a Date variant.

If the data is stored as a string after all, you could possibly modify your SQL statement to convert the string to a date using your DB's built-in functions. In SQL Server you can do that with the CAST and CONVERT functions, e.g.

CAST(myDateAsTextField as datetime)

SQL Server's DATETIME data type accepts fractional seconds with 1 to 3 digits.

Finally, you can check the contents of the string and convert it to a different form before calling CDate. This should be used as a last resort if you can't fix the data at the database level.


问:
ISEXP : fatal error -6017: Internal build error
When I try to build my InstallShield package I get:

Searching project for extract-at-build components...

Extracting COM data from 2 component(s)

ISEXP : fatal error -6017: Internal build

error Express\SingleImage - 1 error(s), 0 warning(s)

I'm using: InstallShield Express Visual FoxPro Limited Edition, Version 5.0.

Where do I even start?

答: Run InstallShield Express as an Administrator


问:
Tkinter insert json data inside Text
I have a json file with names, email adress, surname etc..
I'm trying to put the data inside a Text box in tkinter.

I tried using Label like this:

```<code>with open('file.json','r') as inside:
    data = json.load(inside)

Label(Interface, text=data).place(x=100,y=100)
</code>```

What happened now is that there was only 1 line with all the information and it was not readable so I decided to go with the Text box

```<code>Text(Interface, state='normal',height = 20, width = 60).place(x=10,y=350)
Text.insert(INSERT,data)
</code>```

I get now the error:

```<code>TypeError: insert() missing 1 required positional argument: 'chars'
</code>```

I read that it only takes 2 arguments, but I tried with 3:

```<code>Text.insert(INSERT,data,"test")
</code>```

I get the error:

```<code>AttributeError: 'str' object has no attribute 'tk'
</code>```

I don't know what I am doing wrong in this case..

答:
the problem is this line of code:

```<code>Text.insert(INSERT,data,"test")
</code>```

You are calling a method on the class, which expects three arguments: the instance, the index, and the data to be entered.

Instead, you need to be calling insert in the instance:

```<code>text = Text(Interface, state='normal',height = 20, width = 60)
text.place(x=10,y=350)
...
text.insert(INSERT, data)
</code>```

Note: it's imperative that you save a reference to the text widget, and that you do not call place  (or pack or grid) on the same line (eg: Text(...).place(...)`.

Title: Tkinter insert json data inside Text

Body:
I have a json file with names, email adress, surname etc..
I'm trying to put the data inside a Text box in tkinter.

I tried using Label like this:

with open('file.json','r') as inside:
    data = json.load(inside)

Label(Interface, text=data).place(x=100,y=100)

What happened now is that there was only 1 line with all the information and it was not readable so I decided to go with the Text box

Text(Interface, state='normal',height = 20, width = 60).place(x=10,y=350)
Text.insert(INSERT,data)

I get now the error:

TypeError: insert() missing 1 required positional argument: 'chars'

I read that it only takes 2 arguments, but I tried with 3:

Text.insert(INSERT,data,"test")

I get the error:

AttributeError: 'str' object has no attribute 'tk'

I don't know what I am doing wrong in this case..

Body:
the problem is this line of code:

Text.insert(INSERT,data,"test")

You are calling a method on the class, which expects three arguments: the instance, the index, and the data to be entered.

Instead, you need to be calling insert in the instance:

text = Text(Interface, state='normal',height = 20, width = 60)
text.place(x=10,y=350)
...
text.insert(INSERT, data)

Note: it's imperative that you save a reference to the text widget, and that you do not call place  (or pack or grid) on the same line (eg: Text(...).place(...)`.


问:
How can I accept Lower , upper and mixed case query strings
What is the best way to deal with case options for the following scenario

i want to be able to check if the req.query String
rowCount, rowcount or ROWCOUNT exists and then get the value of it.
hope there is a simple way to check if the querystring in any type of case exists.

if i use

```<code>if (!req.query.rowcount) {var t_rowcount = parseInt(25)}
</code>```

it will not match if the querystring is rowCount

fyi i am running NodeJs on a windows 2016 server

答:
t's not possible as-is, but you could insert a very simple middleware which would, for instance, lowercase all keys in req.query:</p>

```<code>// insert this before your routes
app.use(function(req, res, next) {
  for (var key in req.query)
  {
    req.query[key.toLowerCase()] = req.query[key];
  }
  next();
});
</code>```

Body:
What is the best way to deal with case options for the following scenario

i want to be able to check if the req.query String
rowCount, rowcount or ROWCOUNT exists and then get the value of it.
hope there is a simple way to check if the querystring in any type of case exists.

if i use

if (!req.query.rowcount) {var t_rowcount = parseInt(25)}

it will not match if the querystring is rowCount

fyi i am running NodeJs on a windows 2016 server

Body:
t's not possible as-is, but you could insert a very simple middleware which would, for instance, lowercase all keys in req.query:

// insert this before your routes
app.use(function(req, res, next) {
  for (var key in req.query)
  {
    req.query[key.toLowerCase()] = req.query[key];
  }
  next();
});


问:
How to use ImportXML in Google Sheets to pull view count data from a Instagram and IGTV Video?
I'm trying to pull the view count from a video on Instagram.  This is the video: https://www.instagram.com/p/BxEApSqgNJn/

I have been able to get Youtube and Facebook views, but struggling with Instagram.

I have used the following Formula to pull data from Facebook Video:

```<code>=IFERROR(LEFT(IMPORTXML(H28,"//*[@data-tooltip-position='below']"),LEN(IMPORTXML(H28,"//*[@data-tooltip-position='below']"))-5),"0")
</code>```

H28 is the Link

It should show the views the video has achieved, in this case... 351,271 views as of May 14, 2019.

答:
How about this workaround for retrieving the value? In this workaround, the value is retrieved from the data which is preparing for Javascript. The data is updated when the page is loaded, and retrieved using a xpath, and the value is retrieved using a regular expression. So I used this method. The modified formula is as follows. Please think of this as just one of several answers.

Sample formula:

In this sample formula, https://www.instagram.com/p/BxEApSqgNJn/ is put in the cell "A1".

```<code>=REGEXEXTRACT(IMPORTXML(A1,"//script[@type='application/ld+json']"),"userInteractionCount"":""(\d+)")
</code>```

Retrieve data using the xpath of //script[@type='application/ld+json'] with IMPORTXML().

Retrieve the value using the regular expression of userInteractionCount"":""(\d+) with REGEXEXTRACT().

Result:

References:

IMPORTXML

REGEXEXTRACT

If I misunderstood your question and this was not the result you want, I apologize.

Body:
I'm trying to pull the view count from a video on Instagram.  This is the video: https://www.instagram.com/p/BxEApSqgNJn/

I have been able to get Youtube and Facebook views, but struggling with Instagram.

I have used the following Formula to pull data from Facebook Video:

=IFERROR(LEFT(IMPORTXML(H28,"//*[@data-tooltip-position='below']"),LEN(IMPORTXML(H28,"//*[@data-tooltip-position='below']"))-5),"0")

H28 is the Link

It should show the views the video has achieved, in this case... 351,271 views as of May 14, 2019.

Body:
How about this workaround for retrieving the value? In this workaround, the value is retrieved from the data which is preparing for Javascript. The data is updated when the page is loaded, and retrieved using a xpath, and the value is retrieved using a regular expression. So I used this method. The modified formula is as follows. Please think of this as just one of several answers.

Sample formula:

In this sample formula, https://www.instagram.com/p/BxEApSqgNJn/ is put in the cell "A1".

=REGEXEXTRACT(IMPORTXML(A1,"//script[@type='application/ld+json']"),"userInteractionCount"":""(\d+)")

Retrieve data using the xpath of //script[@type='application/ld+json'] with IMPORTXML().

Retrieve the value using the regular expression of userInteractionCount"":""(\d+) with REGEXEXTRACT().

Result:

References:

IMPORTXML

REGEXEXTRACT

If I misunderstood your question and this was not the result you want, I apologize.