问:
Why std::count is slower that plain for loop with MSVC Compiler but equal with GCC?
I am testing the performance of the C++ standard library algorithms and encountered a weird thing.

Here is my code to compare the performance of std::count vs plain for loop:

```<code>#include <algorithm>
#include <vector>
#include <iostream>
#include <chrono>
using namespace std::chrono;

int my_count(const std::vector<int>& v, int val) {
    int num = 0;

    for (int i: v) {
        if (i == val)
            num++;
    }

    return num;
}

int main()
{
    int total_count = 0;

    std::vector<int> v;
    v.resize(100000000);

    // Fill vector
    for (int i = 0; i < v.size(); i++) {
        v[i] = i % 10000;
    }

    int val = 1;

    {
        auto start = high_resolution_clock::now();
        total_count += std::count(v.begin(), v.end(), val);
        auto stop = high_resolution_clock::now();

        std::cout << "std::count time:   " << duration_cast<microseconds>(stop - start).count() << std::endl;
    }

    {
        auto start = high_resolution_clock::now();
        total_count += my_count(v, val);
        auto stop = high_resolution_clock::now();

        std::cout << "my_count   time:   " << duration_cast<microseconds>(stop - start).count() << std::endl;
    }

    // We need this so the compiler does not prune the code above
    std::cout << "Total items: " << total_count << std::endl;
}
</code>```

With MinGW I get this:

```<code>std::count time:   65827
my_count   time:   64861
</code>```

And with MSVC I get a pretty weird result:

```<code>std::count time:   65532
my_count   time:   28584
</code>```

The MinGW result seems reasonable since, as far as I know, STL count function if roughly equal to the plain for loop, but the MSVC result seems weird - why the plain for loop is more than 2x faster than std::count?

These results are reproducible on my machine - it's not something that occurs once, but it occurs each time I run the code. I even tried changing the function order, running multiple for loops to avoid caching or branch prediction bias, but I still get the same result.

Is there any reason for this?

答:
Well, that seems to be an iterator issue.

I've made an extended test:

```<code>#include <algorithm>
#include <vector>
#include <iostream>
#include <chrono>
using namespace std::chrono;

int std_count(const std::vector<int>& v, int val) {
    return std::count(v.begin(), v.end(), val);
}

int my_count_for(const std::vector<int>& v, int val) {
    int num = 0;

    for (int i = 0; i < v.size(); i++) {
        if (v[i] == val) {
            num++;
        }
    }

    return num;
}

int my_count_for_in(const std::vector<int>& v, int val) {
    int num = 0;

    for (int i : v) {
        if (i == val) {
            num++;
        }
    }

    return num;
}

int my_count_iter(const std::vector<int>& v, int val) {
    int num = 0;

    for (auto i = v.begin(); i < v.end(); i++) {
        if (*i == val) {
            num++;
        }
    }

    return num;
}

int main()
{
    std::vector<int> v;
    v.resize(1000000);

    // Fill vector
    for (int i = 0; i < v.size(); i++) {
        v[i] = i % 10000;
    }

    int val = 1;

    int num_iters = 1000;

    int total_count = 0;

    for (int a = 0; a < 3; a++) {
        {
            auto start = high_resolution_clock::now();
            for (int i = 0; i < num_iters; i++) {
                total_count += std_count(v, val);
            }
            auto stop = high_resolution_clock::now();

            auto duration = duration_cast<microseconds>(stop - start);
            std::cout << "std::count time:       " << duration.count() << std::endl;
        }

        {
            auto start = high_resolution_clock::now();
            for (int i = 0; i < num_iters; i++) {
                total_count += my_count_for(v, val);
            }
            auto stop = high_resolution_clock::now();

            auto duration = duration_cast<microseconds>(stop - start);
            std::cout << "my_count_for time:     " << duration.count() << std::endl;
        }

        {
            auto start = high_resolution_clock::now();
            for (int i = 0; i < num_iters; i++) {
                total_count += my_count_for_in(v, val);
            }
            auto stop = high_resolution_clock::now();

            auto duration = duration_cast<microseconds>(stop - start);
            std::cout << "my_count_for_in time:  " << duration.count() << std::endl;
        }

        {
            auto start = high_resolution_clock::now();
            for (int i = 0; i < num_iters; i++) {
                total_count += my_count_iter(v, val);
            }
            auto stop = high_resolution_clock::now();

            auto duration = duration_cast<microseconds>(stop - start);
            std::cout << "my_count_iter time:    " << duration.count() << std::endl;
        }

        std::cout << std::endl;
    }

    std::cout << total_count << std::endl;
    std::cin >> total_count;
}
</code>```

And here's what I get:

```<code>std::count time:       679683
my_count_for time:     235269
my_count_for_in time:  228185
my_count_iter time:    650714

std::count time:       656192
my_count_for time:     231248
my_count_for_in time:  231050
my_count_iter time:    652598

std::count time:       660295
my_count_for time:     238812
my_count_for_in time:  225893
my_count_iter time:    648812
</code>```

Still seems quite weird that STL function is not the fastest way to solve the task. If someone knows the detailed answer, please share it with me.

Body:
I am testing the performance of the C++ standard library algorithms and encountered a weird thing.

Here is my code to compare the performance of std::count vs plain for loop:

#include <algorithm>
#include <vector>
#include <iostream>
#include <chrono>
using namespace std::chrono;

int my_count(const std::vector<int>& v, int val) {
    int num = 0;

    for (int i: v) {
        if (i == val)
            num++;
    }

    return num;
}

int main()
{
    int total_count = 0;

    std::vector<int> v;
    v.resize(100000000);

    // Fill vector
    for (int i = 0; i < v.size(); i++) {
        v[i] = i % 10000;
    }

    int val = 1;

    {
        auto start = high_resolution_clock::now();
        total_count += std::count(v.begin(), v.end(), val);
        auto stop = high_resolution_clock::now();

        std::cout << "std::count time:   " << duration_cast<microseconds>(stop - start).count() << std::endl;
    }

    {
        auto start = high_resolution_clock::now();
        total_count += my_count(v, val);
        auto stop = high_resolution_clock::now();

        std::cout << "my_count   time:   " << duration_cast<microseconds>(stop - start).count() << std::endl;
    }

    // We need this so the compiler does not prune the code above
    std::cout << "Total items: " << total_count << std::endl;
}

With MinGW I get this:

std::count time:   65827
my_count   time:   64861

And with MSVC I get a pretty weird result:

std::count time:   65532
my_count   time:   28584

The MinGW result seems reasonable since, as far as I know, STL count function if roughly equal to the plain for loop, but the MSVC result seems weird - why the plain for loop is more than 2x faster than std::count?

These results are reproducible on my machine - it's not something that occurs once, but it occurs each time I run the code. I even tried changing the function order, running multiple for loops to avoid caching or branch prediction bias, but I still get the same result.

Is there any reason for this?

Body:
Well, that seems to be an iterator issue.

I've made an extended test:

#include <algorithm>
#include <vector>
#include <iostream>
#include <chrono>
using namespace std::chrono;

int std_count(const std::vector<int>& v, int val) {
    return std::count(v.begin(), v.end(), val);
}

int my_count_for(const std::vector<int>& v, int val) {
    int num = 0;

    for (int i = 0; i < v.size(); i++) {
        if (v[i] == val) {
            num++;
        }
    }

    return num;
}

int my_count_for_in(const std::vector<int>& v, int val) {
    int num = 0;

    for (int i : v) {
        if (i == val) {
            num++;
        }
    }

    return num;
}

int my_count_iter(const std::vector<int>& v, int val) {
    int num = 0;

    for (auto i = v.begin(); i < v.end(); i++) {
        if (*i == val) {
            num++;
        }
    }

    return num;
}

int main()
{
    std::vector<int> v;
    v.resize(1000000);

    // Fill vector
    for (int i = 0; i < v.size(); i++) {
        v[i] = i % 10000;
    }

    int val = 1;

    int num_iters = 1000;

    int total_count = 0;

    for (int a = 0; a < 3; a++) {
        {
            auto start = high_resolution_clock::now();
            for (int i = 0; i < num_iters; i++) {
                total_count += std_count(v, val);
            }
            auto stop = high_resolution_clock::now();

            auto duration = duration_cast<microseconds>(stop - start);
            std::cout << "std::count time:       " << duration.count() << std::endl;
        }

        {
            auto start = high_resolution_clock::now();
            for (int i = 0; i < num_iters; i++) {
                total_count += my_count_for(v, val);
            }
            auto stop = high_resolution_clock::now();

            auto duration = duration_cast<microseconds>(stop - start);
            std::cout << "my_count_for time:     " << duration.count() << std::endl;
        }

        {
            auto start = high_resolution_clock::now();
            for (int i = 0; i < num_iters; i++) {
                total_count += my_count_for_in(v, val);
            }
            auto stop = high_resolution_clock::now();

            auto duration = duration_cast<microseconds>(stop - start);
            std::cout << "my_count_for_in time:  " << duration.count() << std::endl;
        }

        {
            auto start = high_resolution_clock::now();
            for (int i = 0; i < num_iters; i++) {
                total_count += my_count_iter(v, val);
            }
            auto stop = high_resolution_clock::now();

            auto duration = duration_cast<microseconds>(stop - start);
            std::cout << "my_count_iter time:    " << duration.count() << std::endl;
        }

        std::cout << std::endl;
    }

    std::cout << total_count << std::endl;
    std::cin >> total_count;
}

And here's what I get:

std::count time:       679683
my_count_for time:     235269
my_count_for_in time:  228185
my_count_iter time:    650714

std::count time:       656192
my_count_for time:     231248
my_count_for_in time:  231050
my_count_iter time:    652598

std::count time:       660295
my_count_for time:     238812
my_count_for_in time:  225893
my_count_iter time:    648812

Still seems quite weird that STL function is not the fastest way to solve the task. If someone knows the detailed answer, please share it with me.


来源: stackexchange

问:
PostgreSQL allocated column length
I have an issue where I have one column in a database that might be anything from 10 to 10,000 bytes in size. Do you know if PostgreSQL supports sparse data (i.e. will it always set aside the 10,000 bytes fore every entry in the column ... or only the space that is required for each entry)?</p>

答:
Postgres will store long varlena types in an extended storage called TOAST.

In the case of strings, it keep things inline up to 126 bytes (potentially means less 126 characters for multibyte stuff), and then sends it to the external storage.

You can see where the data is stored using psql:

```<code>\dt+ yourtable
</code>```

As an aside, note that from Postgres' standpoint, there's absolutely no difference (with respect to storage) between declaring a column's type as varchar or varchar(large_number) -- it'll be stored in the exact same way. There is, however, a very slight performance penalty in using varchar(large_number) because of the string length check.

ContentLicense: CC BY-SA 4.0

Title: PostgreSQL allocated column length

Body:
Postgres will store long varlena types in an extended storage called TOAST.

In the case of strings, it keep things inline up to 126 bytes (potentially means less 126 characters for multibyte stuff), and then sends it to the external storage.

You can see where the data is stored using psql:

\dt+ yourtable

As an aside, note that from Postgres' standpoint, there's absolutely no difference (with respect to storage) between declaring a column's type as varchar or varchar(large_number) -- it'll be stored in the exact same way. There is, however, a very slight performance penalty in using varchar(large_number) because of the string length check.

ContentLicense: CC BY-SA 3.0


问:
Saving image in a real time object detector
I am currently running a real-time object detector using SSD MobileNetv2 in TensorFlow 1.x and would like to know if there are any ways where I can save an image when one of the class gets detected by the video stream.

```<code>PATH_TO_FROZEN_GRAPH = 'path-to-inference-graph.pb'
PATH_TO_LABEL_MAP = 'path-to-label-map.pbtxt'
NUM_CLASSES = 4
cap = cv2.VideoCapture(0)
</code>```

Basically, I have built the detector to detect 4 classes and would like to save the image (maybe it is likely to come out as a burst of images, still fine) when one of the class gets detected.

```<code>label_map = label_map_util.load_labelmap(PATH_TO_LABEL_MAP)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        while True:
            ret, image_np = cap.read()
            image_np_expanded = np.expand_dims(image_np, axis=0)
            image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
            boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
            scores = detection_graph.get_tensor_by_name('detection_scores:0')
            classes = detection_graph.get_tensor_by_name('detection_classes:0')
            num_detections = detection_graph.get_tensor_by_name('num_detections:0')

            (boxes, scores, classes, num_detections) = sess.run(
                [boxes, scores, classes, num_detections],
                feed_dict={image_tensor: image_np_expanded})

            vis_util.visualize_boxes_and_labels_on_image_array(
                image_np,
                np.squeeze(boxes),
                np.squeeze(classes).astype(np.int32),
                np.squeeze(scores),
                category_index,
                use_normalized_coordinates=True,
                line_thickness=3,
                )

            cv2.imshow('Detection', cv2.resize(image_np, (1200, 800)))
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
</code>```

How do I achieve this? Are there any other variations for it?

答:
After session.run, you get the results in (boxes, scores, classes, num_detections)

You just have to iterate over them and see the class and score and finally save the

```<code>if 'req_class_name' in classes:
   #check for confidence score also
   cv2.imwrite('/path/to/destination/image.png', image_np)
</code>```

Body:
I am currently running a real-time object detector using SSD MobileNetv2 in TensorFlow 1.x and would like to know if there are any ways where I can save an image when one of the class gets detected by the video stream.

PATH_TO_FROZEN_GRAPH = 'path-to-inference-graph.pb'
PATH_TO_LABEL_MAP = 'path-to-label-map.pbtxt'
NUM_CLASSES = 4
cap = cv2.VideoCapture(0)

Basically, I have built the detector to detect 4 classes and would like to save the image (maybe it is likely to come out as a burst of images, still fine) when one of the class gets detected.

label_map = label_map_util.load_labelmap(PATH_TO_LABEL_MAP)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        while True:
            ret, image_np = cap.read()
            image_np_expanded = np.expand_dims(image_np, axis=0)
            image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
            boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
            scores = detection_graph.get_tensor_by_name('detection_scores:0')
            classes = detection_graph.get_tensor_by_name('detection_classes:0')
            num_detections = detection_graph.get_tensor_by_name('num_detections:0')

            (boxes, scores, classes, num_detections) = sess.run(
                [boxes, scores, classes, num_detections],
                feed_dict={image_tensor: image_np_expanded})

            vis_util.visualize_boxes_and_labels_on_image_array(
                image_np,
                np.squeeze(boxes),
                np.squeeze(classes).astype(np.int32),
                np.squeeze(scores),
                category_index,
                use_normalized_coordinates=True,
                line_thickness=3,
                )

            cv2.imshow('Detection', cv2.resize(image_np, (1200, 800)))
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break

How do I achieve this? Are there any other variations for it?

Body:
After session.run, you get the results in (boxes, scores, classes, num_detections)

You just have to iterate over them and see the class and score and finally save the

if 'req_class_name' in classes:
   #check for confidence score also
   cv2.imwrite('/path/to/destination/image.png', image_np)


问:
Create List of unique elements and display group membership parsed by commas and en-dash
I'm an Excel VBA newbie and I'm trying to figure out how to create a unique list of names in one column with associated group names in the next column.

For example, the Name "cds" is a member of the following groups: "group1","group3","group4","group5", and "group6".
I would like the output to show:

```<code>  |Column D   | Column E                 |
     cds          group1, group3–group6
</code>```

I did find a Macro on a different message board that displays the unique element with the associated Group Number(s) instead of Group Name(s). Membership in consecutive group numbers are represented by the en-dash, otherwise group numbers are separated by commas.

The sample output below shows a list of Names and the associated Group Number which I have copied and pasted from another spreadsheet. The Macro creates the output found in Column D and Column E. Given the key shown in Columns G and H, Is it possible to replace the associated group numbers in Column E with the "Group Name" found in Column H? Thanks for your help!

```<code>       |Column A | Column B | Column C | Column D       | Column E  | Column F | Column G     |   Column H        |
Row 1    NAME       GROUP #              NAME (UNIQUE)    GROUP(#s)              Group # (Key)   Group Name (Key)
Row 2    cds         1                     abc             1, 9-10                   1            group1
Row 3    cds         3                     cds             1, 3, 4-6                 2            group2a
Row 4    cds         4                     xyz             7-8                       3            group3
Row 5    cds         5                     zzz             10                        4            group4b
Row 6    cds         6                                                               5            group5
Row 7    abc         10                                                              6            group6
Row 8    abc         9                                                               7            group7
Row 9    xyz         7                                                               8            group8_1
Row 10   xyz         8                                                               9            group9_Z
Row 11   zzz         10                                                              10           group10A

</code>```

Here is the associated code I used:

```<code>Sub OrganizeByNumber()

Dim a, i As Long, e, x, temp, buff

a = Range("a2").CurrentRegion.Value

With CreateObject("Scripting.Dictionary")
   For i = 2 To UBound(a, 1)
     If Not .exists(a(i, 1)) Then
        Set .Item(a(i, 1)) = _
        CreateObject("System.Collections.ArrayList")
     End If
    .Item(a(i, 1)).Add a(i, 2)
   Next

   For Each e In .keys
     .Item(e).Sort
     x = .Item(e).ToArray
     temp = x(0) & Chr(150)

       If UBound(x) > 0 Then
          For i = 1 To UBound(x)
            If x(i) - x(i - 1) = 1 Then
               buff = x(i)
            Else
              temp = temp & buff
            If temp Like "*" & Chr(150) Then temp = Left$(temp, Len(temp) - 1)
              temp = temp & ", " & x(i) & Chr(150)
              buff = ""
       End If
   Next

     If buff <> "" Then
        temp = temp & buff
     Else
        temp = Left$(temp, Len(temp) - 1)
     End If
       .Item(e) = Array(e, temp)
     Else
       .Item(e) = Array(e, Replace(temp, Chr(150), ""))
     End If
   Next

 Range("d2").Resize(.Count, 2).Value = _
 Application.Transpose(Application.Transpose(.items))

End With

End Sub
</code>```

答:
It's just a matter of replacing the code numbers in the string with the matching group name.

I used the VLookup worksheet function, but, depending on the size of your data and the speed with which it runs, there are faster routines (especially with a sorted list).

Since the original code did not output the names in sorted order, I did not do that. But it should be fairly simple to implement. One way would be use the SortedList object.

Edit: As pointed out by @T.M. in the comments below, there is a bug in the routine.  The bug is actually in your original code, which I unfortunately assumed was working.

I didn't go into it in detail, but under certain circumstances, the buff variable is not getting cleared.

I have changed the code below to ensure buff is always cleared after processing; and I also added some code to sort the output by Name. The sorting code is taken from the link in the comments below.

EDIT2: Code added to remove instances where Name/Group# might be duplicated.

```<code>Option Explicit
Sub OrganizeByNumber()

Dim a, b, i As Long, e, x, temp, buff
Dim d As Object

a = Range("a2").CurrentRegion.Value
b = Range("g2").CurrentRegion.Value

Set d = CreateObject("Scripting.Dictionary")
With d
   For i = 2 To UBound(a, 1)
     If Not .exists(a(i, 1)) Then
        Set .Item(a(i, 1)) = _
        CreateObject("System.Collections.ArrayList")
     End If
    .Item(a(i, 1)).Add a(i, 2)
   Next i

   For Each e In .keys
     .Item(e).Sort

     deDupArrList .Item(e)

     x = .Item(e).ToArray

     'temp = x(0) & Chr(150)
     temp = WorksheetFunction.VLookup(x(0), b, 2, False) & Chr(150)

       If UBound(x) > 0 Then
          For i = 1 To UBound(x)
            If x(i) - x(i - 1) = 1 Then

               'buff = x(i)
               buff = WorksheetFunction.VLookup(x(i), b, 2, False)
            Else
              temp = temp & buff
            If temp Like "*" & Chr(150) Then temp = Left$(temp, Len(temp) - 1)

              'temp = temp & ", " & x(i) & Chr(150)
              temp = temp & ", " & WorksheetFunction.VLookup(x(i), b, 2, False) & Chr(150)

              buff = ""
            End If
          Next i

     If buff <> "" Then
        temp = temp & buff
     Else
        temp = Left$(temp, Len(temp) - 1)
     End If
       .Item(e) = Array(e, temp)
     Else
       .Item(e) = Array(e, Replace(temp, Chr(150), ""))
     End If

   buff = ""
   Next e

   sortDict d

 Range("d2").Resize(.Count, 2).Value = _
 Application.Transpose(Application.Transpose(.items))

End With

End Sub

Sub sortDict(dict As Object)
    Dim i As Long, key, al

    'With CreateObject("System.Collections.SortedList")
    Set al = CreateObject("System.Collections.SortedList")
    With al
        For Each key In dict
            .Add key, dict(key)
        Next
        dict.RemoveAll
        For i = 0 To .keys.Count - 1
            dict.Add .getkey(i), .Item(.getkey(i))
        Next
    End With
End Sub

Sub deDupArrList(arrList As Object)
    Dim i As Long
For i = arrList.Count - 1 To 0 Step -1
    If arrList.indexof(arrList(i), 0) <> i Then arrList.removeat i
Next i

End Sub

</code>```

Body:
I'm an Excel VBA newbie and I'm trying to figure out how to create a unique list of names in one column with associated group names in the next column.

For example, the Name "cds" is a member of the following groups: "group1","group3","group4","group5", and "group6".
I would like the output to show:

  |Column D   | Column E                 |
     cds          group1, group3–group6

I did find a Macro on a different message board that displays the unique element with the associated Group Number(s) instead of Group Name(s). Membership in consecutive group numbers are represented by the en-dash, otherwise group numbers are separated by commas.

The sample output below shows a list of Names and the associated Group Number which I have copied and pasted from another spreadsheet. The Macro creates the output found in Column D and Column E. Given the key shown in Columns G and H, Is it possible to replace the associated group numbers in Column E with the "Group Name" found in Column H? Thanks for your help!

       |Column A | Column B | Column C | Column D       | Column E  | Column F | Column G     |   Column H        |
Row 1    NAME       GROUP #              NAME (UNIQUE)    GROUP(#s)              Group # (Key)   Group Name (Key)
Row 2    cds         1                     abc             1, 9-10                   1            group1
Row 3    cds         3                     cds             1, 3, 4-6                 2            group2a
Row 4    cds         4                     xyz             7-8                       3            group3
Row 5    cds         5                     zzz             10                        4            group4b
Row 6    cds         6                                                               5            group5
Row 7    abc         10                                                              6            group6
Row 8    abc         9                                                               7            group7
Row 9    xyz         7                                                               8            group8_1
Row 10   xyz         8                                                               9            group9_Z
Row 11   zzz         10                                                              10           group10A

Here is the associated code I used:

Sub OrganizeByNumber()

Dim a, i As Long, e, x, temp, buff

a = Range("a2").CurrentRegion.Value

With CreateObject("Scripting.Dictionary")
   For i = 2 To UBound(a, 1)
     If Not .exists(a(i, 1)) Then
        Set .Item(a(i, 1)) = _
        CreateObject("System.Collections.ArrayList")
     End If
    .Item(a(i, 1)).Add a(i, 2)
   Next

   For Each e In .keys
     .Item(e).Sort
     x = .Item(e).ToArray
     temp = x(0) & Chr(150)

       If UBound(x) > 0 Then
          For i = 1 To UBound(x)
            If x(i) - x(i - 1) = 1 Then
               buff = x(i)
            Else
              temp = temp & buff
            If temp Like "*" & Chr(150) Then temp = Left$(temp, Len(temp) - 1)
              temp = temp & ", " & x(i) & Chr(150)
              buff = ""
       End If
   Next

     If buff <> "" Then
        temp = temp & buff
     Else
        temp = Left$(temp, Len(temp) - 1)
     End If
       .Item(e) = Array(e, temp)
     Else
       .Item(e) = Array(e, Replace(temp, Chr(150), ""))
     End If
   Next

 Range("d2").Resize(.Count, 2).Value = _
 Application.Transpose(Application.Transpose(.items))

End With

End Sub

Body:
It's just a matter of replacing the code numbers in the string with the matching group name.

I used the VLookup worksheet function, but, depending on the size of your data and the speed with which it runs, there are faster routines (especially with a sorted list).

Since the original code did not output the names in sorted order, I did not do that. But it should be fairly simple to implement. One way would be use the SortedList object.

Edit: As pointed out by @T.M. in the comments below, there is a bug in the routine.  The bug is actually in your original code, which I unfortunately assumed was working.

I didn't go into it in detail, but under certain circumstances, the buff variable is not getting cleared.

I have changed the code below to ensure buff is always cleared after processing; and I also added some code to sort the output by Name. The sorting code is taken from the link in the comments below.

EDIT2: Code added to remove instances where Name/Group# might be duplicated.

Option Explicit
Sub OrganizeByNumber()

Dim a, b, i As Long, e, x, temp, buff
Dim d As Object

a = Range("a2").CurrentRegion.Value
b = Range("g2").CurrentRegion.Value

Set d = CreateObject("Scripting.Dictionary")
With d
   For i = 2 To UBound(a, 1)
     If Not .exists(a(i, 1)) Then
        Set .Item(a(i, 1)) = _
        CreateObject("System.Collections.ArrayList")
     End If
    .Item(a(i, 1)).Add a(i, 2)
   Next i

   For Each e In .keys
     .Item(e).Sort

     deDupArrList .Item(e)

     x = .Item(e).ToArray

     'temp = x(0) & Chr(150)
     temp = WorksheetFunction.VLookup(x(0), b, 2, False) & Chr(150)

       If UBound(x) > 0 Then
          For i = 1 To UBound(x)
            If x(i) - x(i - 1) = 1 Then

               'buff = x(i)
               buff = WorksheetFunction.VLookup(x(i), b, 2, False)
            Else
              temp = temp & buff
            If temp Like "*" & Chr(150) Then temp = Left$(temp, Len(temp) - 1)

              'temp = temp & ", " & x(i) & Chr(150)
              temp = temp & ", " & WorksheetFunction.VLookup(x(i), b, 2, False) & Chr(150)

              buff = ""
            End If
          Next i

     If buff <> "" Then
        temp = temp & buff
     Else
        temp = Left$(temp, Len(temp) - 1)
     End If
       .Item(e) = Array(e, temp)
     Else
       .Item(e) = Array(e, Replace(temp, Chr(150), ""))
     End If

   buff = ""
   Next e

   sortDict d

 Range("d2").Resize(.Count, 2).Value = _
 Application.Transpose(Application.Transpose(.items))

End With

End Sub

Sub sortDict(dict As Object)
    Dim i As Long, key, al

    'With CreateObject("System.Collections.SortedList")
    Set al = CreateObject("System.Collections.SortedList")
    With al
        For Each key In dict
            .Add key, dict(key)
        Next
        dict.RemoveAll
        For i = 0 To .keys.Count - 1
            dict.Add .getkey(i), .Item(.getkey(i))
        Next
    End With
End Sub

Sub deDupArrList(arrList As Object)
    Dim i As Long
For i = arrList.Count - 1 To 0 Step -1
    If arrList.indexof(arrList(i), 0) <> i Then arrList.removeat i
Next i

End Sub


问:
FeathersJs: context.params.user returning undefined in before hook
I'm getting undefined when I try to assign user._id to an entity in a before hook.

The hook

```<code>module.exports = (options = {}) => {
return async context => {

const user = context.params.user;

context.data = {
...
      userId: user._id,
...
    };
return context;
};
};
</code>```

This is my hooks register

```<code>  before: {
...
    create: [processProperty(), authenticate('jwt')],
...
  }
}
</code>```

答:
I was able to fix the issue by bringing the authenticate hook before my processProperty hook as shown below.
I think this is because each hook in the array is processed from left to right, so in this case, the processProperty hook needs access to the authenticated user, so it needs to come after the authenticate hook has been processed.

```<code>  before: {
...
    create: [authenticate('jwt'), processProperty()],
...
  }
}
</code>```

Body:
I'm getting undefined when I try to assign user._id to an entity in a before hook.

The hook

module.exports = (options = {}) => {
return async context => {

const user = context.params.user;

context.data = {
...
      userId: user._id,
...
    };
return context;
};
};

This is my hooks register

  before: {
...
    create: [processProperty(), authenticate('jwt')],
...
  }
}

Body:
I was able to fix the issue by bringing the authenticate hook before my processProperty hook as shown below.
I think this is because each hook in the array is processed from left to right, so in this case, the processProperty hook needs access to the authenticated user, so it needs to come after the authenticate hook has been processed.

  before: {
...
    create: [authenticate('jwt'), processProperty()],
...
  }
}


问:
Implement strategy pattern with enum
I'm trying to create a service to handle different payment methods. I want to implement strategy pattern. I'd like to have an enum with the different payment methods. This is an example of what I have:

```<code>public enum Pay {
    CREDITCARD(1) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }

    },
    OTHERMETHOD(2) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }
    };

    private int id;

    Payment(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public abstract void pay();
}
</code>```

somewhere in the client:

```<code>user.setPay(Pay.CREDITCARD);
user.pay();
</code>```

The problem with this approach is that method "pay" could be have a lot of logic so I'd like to have it in a different class. I could define an interface like this:

```<code>public interface Pay {
    void pay();
}

public class CreditCard implements Pay {
    @Override
    public void pay() {
    }
}

public class OtherMethod implements Pay {
    @Override
    public void pay() {
    }
}
</code>```

somewhere in the client:

```<code>if (method.equals("creditcard")) {
    user.setPay(new CreditCard());
    user.pay();
}
else {
    user.setPay(new OtherMethod());
    user.pay();
}
</code>```

but I like much more how it looks with Enum and that the reason to keep that way. Thanks

答:
You don't need the if statement in the client. If you declare set Pay with a parameter of type Pay (the interface), you can invoke it passing every class which implements the Pay interface.  Your code becames

```<code>user.setPay(new CreditCard()); //or every class which implements Pya interface
user.pay();
</code>```

The enum is useless in this case. If you want to give to each payment methods a numerical id, add it to the interface.

Title: Implement strategy pattern with enum

Body:
I'm trying to create a service to handle different payment methods. I want to implement strategy pattern. I'd like to have an enum with the different payment methods. This is an example of what I have:

public enum Pay {
    CREDITCARD(1) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }

    },
    OTHERMETHOD(2) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }
    };

    private int id;

    Payment(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public abstract void pay();
}

somewhere in the client:

user.setPay(Pay.CREDITCARD);
user.pay();

The problem with this approach is that method "pay" could be have a lot of logic so I'd like to have it in a different class. I could define an interface like this:

public interface Pay {
    void pay();
}

public class CreditCard implements Pay {
    @Override
    public void pay() {
    }
}

public class OtherMethod implements Pay {
    @Override
    public void pay() {
    }
}

somewhere in the client:

if (method.equals("creditcard")) {
    user.setPay(new CreditCard());
    user.pay();
}
else {
    user.setPay(new OtherMethod());
    user.pay();
}

but I like much more how it looks with Enum and that the reason to keep that way. Thanks

Body:
You don't need the if statement in the client. If you declare set Pay with a parameter of type Pay (the interface), you can invoke it passing every class which implements the Pay interface.  Your code becames

user.setPay(new CreditCard()); //or every class which implements Pya interface
user.pay();

The enum is useless in this case. If you want to give to each payment methods a numerical id, add it to the interface.


问:
why don't replace all letter from second array last13?
My problem is that replace only first character from last13 array.

I want replace all character from var last13 to first13

```<code> var first13 = first13Letter.map(x=>x).join(',');

 var last13 = last13Letter.map(y=>y).join(',');
</code>```

my code

```<code>function rot13(str) {

  var first13Letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M"];

  var last13Letter = ["N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

  var first13 = first13Letter.map(x=>x).join(',');

  var last13 = last13Letter.map(y=>y).join(',');

  for(let i=0; i<first13.length; i++){

     if(str.indexOf(first13[i]) !== -1){
        str = str.replace(first13[i],last13[i])
     }else{
        str = str.replace(last13[i],first13[i]) // i want to replace all letter from last13 to first13 letter but this replace only first letter.
     }
  }
  return str;
}

console.log(rot13("SERR YBIR?"))

//output:"FRRR LOVR?"
//expect output: "FREE LOVE?"

</code>```

What is the error in code above?

答:
```<code>function rot13(str) {
    const first13Letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M"];
    const last13Letter = ["N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    return str.split('')
              .map(s => last13Letter.indexOf(s) >= 0 ? first13Letter[last13Letter.indexOf(s)] :
                        first13Letter.indexOf(s) >= 0 ? last13Letter[first13Letter.indexOf(s)] : s)
              .join('')
}
console.log(rot13("SERR YBIR?"))

</code>```

Body:
My problem is that replace only first character from last13 array.

I want replace all character from var last13 to first13

 var first13 = first13Letter.map(x=>x).join(',');

 var last13 = last13Letter.map(y=>y).join(',');

my code

function rot13(str) {

  var first13Letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M"];

  var last13Letter = ["N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

  var first13 = first13Letter.map(x=>x).join(',');

  var last13 = last13Letter.map(y=>y).join(',');

  for(let i=0; i<first13.length; i++){

     if(str.indexOf(first13[i]) !== -1){
        str = str.replace(first13[i],last13[i])
     }else{
        str = str.replace(last13[i],first13[i]) // i want to replace all letter from last13 to first13 letter but this replace only first letter.
     }
  }
  return str;
}

console.log(rot13("SERR YBIR?"))

//output:"FRRR LOVR?"
//expect output: "FREE LOVE?"

What is the error in code above?


问:
How to find fast the number of files in directory?
I have thousands log files in a few directories in my system. Mostly I need to know just number of these files in directory. I fear that this attitude:

```<code>$files = count(scandir("logs")) - 2;
</code>```

Is not very effective (memory, filesystem). I am considering some global counter (incremented after file is added), unless there is some other effective way?

答:
Try to call system listing of files:</p>

```<code>$files = exec('ls logs | wc -l');
</code>```

Body:
I have thousands log files in a few directories in my system. Mostly I need to know just number of these files in directory. I fear that this attitude:

$files = count(scandir("logs")) - 2;

Is not very effective (memory, filesystem). I am considering some global counter (incremented after file is added), unless there is some other effective way?

Body:
Try to call system listing of files:

$files = exec('ls logs | wc -l');


问:
How to solve the error ""before all" hook: prepare suite:"
When I tested my contract, I got this error ""before all" hook: prepare suite:"

Does anyone know how to solve this error?

This is my dependencies.
"truffle": "5.0.7",
"web3": "1.0.0-beta.46"

答:
npm uninstall -g truffle

npm install -g truffle@5.1.10 (always got me back on track)


问:
Faulty representation of spacy tags (before and after tokenization)
Does anyone know whether this kind of output is normal or harmless (for subsequent computations with the tags pandas DF column) when using spacy on a pandas DF (see "faulty representation...")?

Code for converting DF text column ("fulltext") to spacy-tokenized text column:

```<code>df["text_tokenized"] = df["fulltext"].apply(lambda x: [y.text for y in sp_model(x)])
df["text_tokenized"] = df["text_tokenized"].apply(' '.join)
</code>```

Code for converting DF tokenized_text column to spacy tags:

```<code>df['TAG'] = df['text_tokenized'].apply(lambda x: [y.tag_ for y in  sp_model(x)])
df['TAG'] = df['TAG'].apply(' '.join)
</code>```

I have similarly added columns for spacy dependencies, lemmas, and pos-tags. Those look just fine in the output in jupyter notebook, but for some reason, the spacy tags do not look right. I'm not sure what is going on: I think I have deleted non-ASCII characters because I thought it might have something to do with that. What baffles me is that it only occurs in some instances, definitely not all of them.

答:
According to a detailed extraction the data stored in the DF should be fine. It looks like it's just an output issue in the notebook.

Image

Edit: It is a mathjax problem in the output of the notebooks: since the original text data and spacy tags include signs like "$", mathjax assumes the following characters to be mathematical equations and attempts to convert them, resulting in a strange text output. Mathjax is enabled by default, regardless whether you are dealing with numeric or text output. I found most of this info here: https://github.com/ipython/ipython/issues/4817

Body:
Does anyone know whether this kind of output is normal or harmless (for subsequent computations with the tags pandas DF column) when using spacy on a pandas DF (see "faulty representation...")?

Code for converting DF text column ("fulltext") to spacy-tokenized text column:

df["text_tokenized"] = df["fulltext"].apply(lambda x: [y.text for y in sp_model(x)])
df["text_tokenized"] = df["text_tokenized"].apply(' '.join)

Code for converting DF tokenized_text column to spacy tags:

df['TAG'] = df['text_tokenized'].apply(lambda x: [y.tag_ for y in  sp_model(x)])
df['TAG'] = df['TAG'].apply(' '.join)

I have similarly added columns for spacy dependencies, lemmas, and pos-tags. Those look just fine in the output in jupyter notebook, but for some reason, the spacy tags do not look right. I'm not sure what is going on: I think I have deleted non-ASCII characters because I thought it might have something to do with that. What baffles me is that it only occurs in some instances, definitely not all of them.


问:
How can i retrieve int data from one activity and set it to textView of another activity
Sending class code:

```<code>Intent i = new Intent(this, QuizActivity.class);
        i.putExtra("name", name);
        startActivity(i);
</code>```

Recieving class code:

```<code>Intent intent = getIntent();
    if (intent != null) {
        totalScore = intent.getIntExtra("totalScore",0);
    }
    TextView scoreView = findViewById(R.id.totalScore);
    scoreView.setText(totalScore);
</code>```

答:
On the sender side, use Intent.putExtra:

```<code>Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("totalScore", intValue);
startActivity(myIntent);
</code>```

On the receiver side, use Intent.getIntExtra:

```<code> Intent mIntent = getIntent();
 int totalScore = mIntent.getIntExtra("totalScore", 0);
 TextView scoreView = findViewById(R.id.totalScore);
 scoreView.setText(totalScore+"");
</code>```

Body:
Sending class code:

Intent i = new Intent(this, QuizActivity.class);
        i.putExtra("name", name);
        startActivity(i);

Recieving class code:

Intent intent = getIntent();
    if (intent != null) {
        totalScore = intent.getIntExtra("totalScore",0);
    }
    TextView scoreView = findViewById(R.id.totalScore);
    scoreView.setText(totalScore);

Body:
On the sender side, use Intent.putExtra:

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("totalScore", intValue);
startActivity(myIntent);

On the receiver side, use Intent.getIntExtra:

 Intent mIntent = getIntent();
 int totalScore = mIntent.getIntExtra("totalScore", 0);
 TextView scoreView = findViewById(R.id.totalScore);
 scoreView.setText(totalScore+"");


问:
How to use this aggregate condition in golang mongodb
Ho can i write this condition in golang for mongodb:

```<code>success_count: { $sum: { $cond: ["$is_success", 1, 0] } }
</code>```

I a'm trying this but not working:

```<code>"$success_count": bson.M{"$sum": bson.M{"$cond": bson.M{"$is_success", 1, 0}}}
</code>```

答:
Use []interface{} instead of bson.M. Here bson.M is map[string]interface{} but you need to use slice.

```<code>bson.M{"$cond": []interface{}{"$is_success", 1, 0}}
</code>```

Body:
Ho can i write this condition in golang for mongodb:

success_count: { $sum: { $cond: ["$is_success", 1, 0] } }

I a'm trying this but not working:

"$success_count": bson.M{"$sum": bson.M{"$cond": bson.M{"$is_success", 1, 0}}}

Body:
Use []interface{} instead of bson.M. Here bson.M is map[string]interface{} but you need to use slice.

bson.M{"$cond": []interface{}{"$is_success", 1, 0}}


问:
Detox: Multiple matcher count?
Is it possible to get the count of matches in multiple matches?

My case is: I have a list of ~20 items, they are server-side based, so it can change, and I want to be able to test each of them (they are toggles).

答:
This is not possible currently, but will be possible in the near future, with the new getAttributes() API. This is planned for release soon.

See the documentation here

const multipleMatchedElements = await element(by.text('Multiple')).getAttributes();
jestExpect(multipleMatchedElements.elements.length).toBe(5);
jestExpect(multipleMatchedElements.elements[0].identifier).toBe('FirstElement');
```

Title: Detox: Multiple matcher count?


问:
Java : How to visualize/plot two parameters relations with a matrix
I have a table with the following structure:

[relation, variable1, variable2]

I would like to visualize those relation over a triangular matrix, something like this but with any number of variables and not only 4. Is there any free java library to do so? any ideas on how to visualize it by my own?
I don't have any code yet, Just thinking about the idea and process of how doing it.

much appreciation to all :)

答:
I suggest you use a Swing framework that is natively provided by Java so you don't have to import any external library for this task.

I think painting this matrix (as in your link) is not difficult using Swing.

I find this discussion very useful for your case How to draw grid using swing class Java and detect mouse position when click and drag

Because it provides an example of painting a matrix.


问:
I want efficient data structure to store items and their counts and search for min of them?
I want efficient data structure to store items and their counts and search for min of them?

I have a number of items, and a count of each item, I want a data sturucture to store the items and their counts. in my script each time i will search about an item and update its count, also I want to find the item that has the min count, and some times I want the count of some items. would you please tell me which data structure to use with low space and low cost search operations?

答:
for example:
I have items
key:     Count:
A        2
B        3

C        1

for the above list, I want to add new items with count 1 and may i want to increment the count of the existing items A,B,C. also, I want to get the count of some items for example the count of A, the answer should be 2. also i want to get the item that has the min count which should be 1 in our example.
for my problem i want to do the operation with min time and min space!!
thanks a lot for  your replies


问:
vba referencing html elements by xpath
I am a beginner to web scraping with excel vba and need some help.

I am trying to reference an element. If there was an id then I could use getElementByID but sometimes there is no id. I could use getElementByClassName but sometimes there are too many elements of the same class.

Is there some way to refer to an element by xpath?

(I can't post the actual website since there is personal info so let us say this is the html)

```<code><!DOCTYPE html>
<html>
<body>

<a href="https://google.com">Link</a>

</body>
</html>
</code>```

is there something like ie.document.getElementByXPath.(/html/body/a).click?
I've searched all over the web and can't seem to find anything on the topic.

答:
You can do this in Excel VBA using Selenium Webdriver (https://www.selenium.dev/).

Webdriver does have a FindElementByXPath method. It has the advantage of providing control of other browser than Internet Explorer, but the disadvantage will be the need to install Selenium in every machine which will run your VBA script.

Here is a walkthrough for installing Selenium and adding its library reference to your project (this was the tutorial I used; it's a pt-br page, but I put into google for automatic translation): https://translate.google.com/translate?sl=pt&tl=en&u=https%3A%2F%2Fwww.tomasvasquez.com.br%2Fblog%2Fmicrosoft-office%2Fexcel%2Fvba-interagindo-com-paginas-web-com-o-selenium-webdriver%2F

And here is another quickstart from Coding is Love (it doesn't have the installation walkthrough): https://codingislove.com/browser-automation-in-excel-selenium/

Title: vba referencing html elements by xpath

Body:
I am a beginner to web scraping with excel vba and need some help.

I am trying to reference an element. If there was an id then I could use getElementByID but sometimes there is no id. I could use getElementByClassName but sometimes there are too many elements of the same class.

Is there some way to refer to an element by xpath?

(I can't post the actual website since there is personal info so let us say this is the html)

<!DOCTYPE html>

Link

is there something like ie.document.getElementByXPath.(/html/body/a).click?
I've searched all over the web and can't seem to find anything on the topic.


问:
Make new query to have same effect as previous one
I have the following table:

```<code>Region_id | Region_name
1           Europe
2           Americas
3           Asia
4           Middle East and Africa
</code>```

And this query:

```<code>SELECT region_id, region_name
  FROM hr.regions
 GROUP BY CUBE(region_id, region_name);
</code>```

Which returns:

```<code>Region_id | Region_name
(null)      (null)
(null)      Asia
(null)      Europe
(null)      Americas
(null)      Middle East and Africa
1           (null)
1           Europe
2           (null)
2           Americas
3           (null)
3           Asia
4           (null)
4           Middle East and Africa
</code>```

The question and problem: How do I make another query that returns the same results as above but using SET operations like union and intersect instead of group by cube(...)?

答:
You would use:

```<code>select region_id, region_name
from hr_regions
union all
select NULL as region_id, region_name
from hr_regions
union all
select region_id, NULL as region_name
from hr_regions
union all
select NULL as region_id, NULL as region_name
from dual;
</code>```

Your example data has not duplicates in either column. so no aggregation or select distinct is needed.  The one exception is the last query.  To get only one row with two NULL values, it select from dual.

Body:
I have the following table:

Region_id | Region_name
1           Europe
2           Americas
3           Asia
4           Middle East and Africa

And this query:

SELECT region_id, region_name
  FROM hr.regions
 GROUP BY CUBE(region_id, region_name);

Which returns:

Region_id | Region_name
(null)      (null)
(null)      Asia
(null)      Europe
(null)      Americas
(null)      Middle East and Africa
1           (null)
1           Europe
2           (null)
2           Americas
3           (null)
3           Asia
4           (null)
4           Middle East and Africa

The question and problem: How do I make another query that returns the same results as above but using SET operations like union and intersect instead of group by cube(...)?

Body:
You would use:

select region_id, region_name
from hr_regions
union all
select NULL as region_id, region_name
from hr_regions
union all
select region_id, NULL as region_name
from hr_regions
union all
select NULL as region_id, NULL as region_name
from dual;

Your example data has not duplicates in either column. so no aggregation or select distinct is needed.  The one exception is the last query.  To get only one row with two NULL values, it select from dual.


问:
Finishing all activities started before the activity
I want to finish all the activities which are running in the application means want to remove all the parent activities from stack.

I want to implement logout functionality locally in my application so what I was thinking, I will finish all the activities started before and will start login activity again..

答:
What you might be looking for is FLAG_ACTIVITY_CLEAR_TOP intent flag:

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

```<code>Intent i = new Intent(..);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
</code>```

and then start Activity with this intent.

See more on tasks and back stack in documentation: Tasks and Back stack.

However to implement login/logout to application (if it is not communicating with online service) you might use SharedPreferences. This way on application start you could check if user is logged in (eg. some flag turned on in preferences) and upon application exit (eg. by button) you could clear this flag.

Killing/removing Activities should be left to the system. Per system design it is Android OS that is responsible for application lifetime.

For example check the Password Safe application sources. It needs password every time you open fresh instance of application.

Body:
What you might be looking for is FLAG_ACTIVITY_CLEAR_TOP intent flag:

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

Intent i = new Intent(..);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

and then start Activity with this intent.

See more on tasks and back stack in documentation: Tasks and Back stack.

However to implement login/logout to application (if it is not communicating with online service) you might use SharedPreferences. This way on application start you could check if user is logged in (eg. some flag turned on in preferences) and upon application exit (eg. by button) you could clear this flag.

Killing/removing Activities should be left to the system. Per system design it is Android OS that is responsible for application lifetime.

For example check the Password Safe application sources. It needs password every time you open fresh instance of application.


问:
is there a way to map all keys from the keyboard to (some char) with ctypes in Python?
```<code>from ctypes import *

ok = windll.user32.BlockInput(True)
</code>```

So I learned that I can block input in windows with that code

Is it disabled when the script ends or when the pc is rebooted?

But instead of blocking all input id like to redirect all inputs to a char as "E" or "5" does anyone know how to do it?

答:
According to [MS.Docs]: BlockInput function:

The system will unblock input in the following cases:

The thread that blocked input unexpectedly exits without calling BlockInput with fBlock set to FALSE. In this case, the system cleans up properly and re-enables input.

The user presses CTRL+ALT+DEL or the system invokes the Hard System Error modal message box (for example, when a program faults or a device fails).

So, unblocking occurs when the script (Python process (and its main thread) that executes the script) ends.

For generating system events you should check SendInput documentation. For more info, also check [MS.Docs]: About Keyboard Input.

Regarding key "redirection", I don't know a(n easy) way, but it looks like an XY Problem. There should be another (simpler) way of achieving your end goal.

Body:
from ctypes import *

ok = windll.user32.BlockInput(True)

So I learned that I can block input in windows with that code

Is it disabled when the script ends or when the pc is rebooted?

But instead of blocking all input id like to redirect all inputs to a char as "E" or "5" does anyone know how to do it?


问:
How to get exponent and modulus value of RSA public key from pfx file/pem file in java
I want to extract information about RSA Public Key from the pfx file using java.

I have a pfx file and converted to x509 Pem file. From pem file, Using the below command in terminal:

```<code>openssl x509 -in file.pem -text
</code>```

I am able to view the public key exponent and modulus value

Subject Public Key Info:

```<code>Public Key Algorithm: rsaEncryption
    Public-Key: (2048 bit)
    Modulus:
        00:da:7c:e0:3e:c4:62:8d:ce:29:04:2f:93:78:7c:
        :
         6a:e7:c9:7c:8b:6f:09:5c:75:5f:8c:5e:9c:6a:b9:
        7:32:90: a4:4b
    Exponent: 65537 (0x10001)
</code>```

How to extract the above information in java?

Input: pfxfile and password

Output:public key exponent and modulus value.

I m using the below code to extract the public key exponent and modulus, but i am not getting the value that is extracted using openssl. I doubt whether java.security.cert.Certificate uses some other DER format??

What is the java equivalent of openssl?

Code:

```<code>KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(file), password.toCharArray());
Enumeration enumeration = ks.aliases();
while (enumeration.hasMoreElements()) {
    String alias = (String) enumeration.nextElement();
    java.security.cert.Certificate certificate = ks.getCertificate(alias);
    PublicKey publickey = certificate.getPublicKey();
}
</code>```

答:
```<code>Adding to the above Java Program to extract the n-modulus and e-exponent of the Base64 format of RSA would be as follows.

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class ModulusExpFromPublicKeyRSA {
    public static void main(String args[]) {
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQAB";

        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] keyBytes = Base64.getDecoder().decode(publicKey.getBytes("UTF-8"));
            X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
            PublicKey fileGeneratedPublicKey = keyFactory.generatePublic(spec);
            RSAPublicKey rsaPub  = (RSAPublicKey)(fileGeneratedPublicKey);
            BigInteger publicKeyModulus = rsaPub.getModulus();
            BigInteger publicKeyExponent  = rsaPub.getPublicExponent();
            System.out.println("publicKeyModulus: " + publicKeyModulus);
            System.out.println("publicKeyExponent: " + publicKeyExponent);
            String nModulus=Base64.getUrlEncoder().encodeToString(publicKeyModulus.toByteArray());
            String eExponent=Base64.getUrlEncoder().encodeToString(publicKeyExponent.toByteArray());
            System.out.println("n Modulus for RSA Algorithm: " + nModulus);
            System.out.println("e Exponent for RSA Algorithm: " + eExponent);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeySpecException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }

}

publicKeyModulus: 119445732379544598056145200053932732877863846799652384989588303737527328743970559883211146487286317168142202446955508902936035124709397221178664495721428029984726868375359168203283442617134197706515425366188396513684446494070223079865755643116690165578452542158755074958452695530623055205290232290667934914919
publicKeyExponent: 65537
n Modulus for RSA Algorithm: AKoYq6Q7UN7vOFmPr4fSq2NORXHBMKm8p7h4JnQU-quLRxvYll9cn8OBhIXq9SnCYkbzBVBkqN4ZyMM4vlSWy66wWdwLNYFDtEo1RJ6yZBExIaRVvX_eP6yRnpS1b7m7T2Uc2yPq1DnWzVI-sIGR51s1_ROnQZswkPJHh71PThln
e Exponent for RSA Algorithm: AQAB
</code>```

Body:
I want to extract information about RSA Public Key from the pfx file using java.

I have a pfx file and converted to x509 Pem file. From pem file, Using the below command in terminal:

openssl x509 -in file.pem -text

I am able to view the public key exponent and modulus value

Subject Public Key Info:

Public Key Algorithm: rsaEncryption
    Public-Key: (2048 bit)
    Modulus:
        00:da:7c:e0:3e:c4:62:8d:ce:29:04:2f:93:78:7c:
        :
         6a:e7:c9:7c:8b:6f:09:5c:75:5f:8c:5e:9c:6a:b9:
        7:32:90: a4:4b
    Exponent: 65537 (0x10001)

How to extract the above information in java?

Input: pfxfile and password

Output:public key exponent and modulus value.

I m using the below code to extract the public key exponent and modulus, but i am not getting the value that is extracted using openssl. I doubt whether java.security.cert.Certificate uses some other DER format??

What is the java equivalent of openssl?

Code:

KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(file), password.toCharArray());
Enumeration enumeration = ks.aliases();
while (enumeration.hasMoreElements()) {
    String alias = (String) enumeration.nextElement();
    java.security.cert.Certificate certificate = ks.getCertificate(alias);
    PublicKey publickey = certificate.getPublicKey();
}


问:
Boostrap 4 - Scrollspy issue
So, I'm trying to rebuild my website from scratch. And I want to add a scrollspy to the top of my navbar.

I've already tried to add the data-spy="scroll" data-target=".navbar" data-offset="100"to my body tag, and define it in jQuery by using jQuery('body').scrollspy();.

But it's just not working. I looked into DevTools on Chrome, but I can't find any issues in it.

My Navbar

```<code><nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top" id="navbar">
    <a class="navbar-brand" href="/"><img height="45px" src="https://dellusion.app/assets/img/logo/textlogo.png" alt="Dellusion Records"></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor" aria-controls="navbarColor" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarColor">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link" href="/#top" data-easing="easeOutQuint">Home</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="/#latest" data-easing="easeOutQuint">Releases</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="/#news" data-easing="easeOutQuint">News</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="/#artists" data-easing="easeOutQuint">Artists</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="/#contact" data-easing="easeOutQuint">Contact</a>
            </li>
        </ul>
        <ul class="navbar-nav">
            <li class="nav-item">
                <a class="nav-link" href="https://open.spotify.com/user/dellusion_records"><i class="fab fa-lg fa-spotify"></i></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="https://twitter.com/DellusionRec"><i class="fab fa-lg fa-twitter"></i></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="https://www.facebook.com/DellusionRecords"><i class="fab fa-lg fa-facebook-f"></i></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="https://www.youtube.com/DellusionRecordsOfficial"><i class="fab fa-lg fa-youtube"></i></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="https://www.soundcloud.com/dellusion-records"><i class="fab fa-lg fa-soundcloud"></i></a>
            </li>
        </ul>
    </div>
</nav>
</code>```

My question is how to get this scrollspy working? Because it's a pain in the head for this to be working.

A full example can be found here

答:
I mentioned the places I added in the comment lines.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <title>STACKOVERFLOW</title>

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor" aria-controls="navbarColor" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home

          Releases

          News

          Artists

          Contact

Home

Releases

News

Artists

Contact

```

Title: Boostrap 4 - Scrollspy issue

Body:
So, I'm trying to rebuild my website from scratch. And I want to add a scrollspy to the top of my navbar.

I've already tried to add the data-spy="scroll" data-target=".navbar" data-offset="100"to my body tag, and define it in jQuery by using jQuery('body').scrollspy();.

But it's just not working. I looked into DevTools on Chrome, but I can't find any issues in it.

My Navbar

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor" aria-controls="navbarColor" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Home

                Releases

                News

                Artists

                Contact

My question is how to get this scrollspy working? Because it's a pain in the head for this to be working.

A full example can be found here

Body:
I mentioned the places I added in the comment lines.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <title>STACKOVERFLOW</title>
</head>

<body data-spy="scroll" data-target="#navbar" data-offset="0">
  <!-- Added Here  -->

  <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top" id="navbar">
    <a class="navbar-brand" href="/"><img height="45px" src="https://dellusion.app/assets/img/logo/textlogo.png" alt="Dellusion Records"></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor" aria-controls="navbarColor" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarColor">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item">
          <a class="nav-link active" href="#top" data-easing="easeOutQuint">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#latest" data-easing="easeOutQuint">Releases</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#news" data-easing="easeOutQuint">News</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#artists" data-easing="easeOutQuint">Artists</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#contact" data-easing="easeOutQuint">Contact</a>
        </li>
      </ul>
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link" href="https://open.spotify.com/user/dellusion_records"><i
              class="fab fa-lg fa-spotify"></i></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="https://twitter.com/DellusionRec"><i class="fab fa-lg fa-twitter"></i></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="https://www.facebook.com/DellusionRecords"><i
              class="fab fa-lg fa-facebook-f"></i></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="https://www.youtube.com/DellusionRecordsOfficial"><i
              class="fab fa-lg fa-youtube"></i></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="https://www.soundcloud.com/dellusion-records"><i
              class="fab fa-lg fa-soundcloud"></i></a>
        </li>
      </ul>
    </div>
  </nav>

  <!-- Created Them for Example -->
  <div id="top" style="height: 700px; margin-top: 71px;" class="bg-warning">Home</div>
  <div id="latest" style="height: 700px;" class="bg-danger">Releases</div>
  <div id="news" style="height: 700px;" class="bg-primary">News</div>
  <div id="artists" style="height: 700px;" class="bg-info">Artists</div>
  <div id="contact" style="height: 700px;" class="bg-dark text-white">Contact</div>

  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

  <!-- JAVASCRIPT -->
  <script>
  </script>
</body>

</html>


问:
Google Analytics - Get nested span event click without class and id
I am using Tag manager and Anayltics 360.

My code as follows,

```<code><div rel="ABC_Links" class="ak_widget" >
<!-- BEGIN: Widget - Links -->
<section class="mfb-30">
    <div class="widget_links">
        <div class="widget_container">
            <div class="widget_content">
                <button type="button" class="buttonShadow" onclick="window.open('https://somepagelink.aspx); return false;">
                    <div class="widget_item">
                        <div class="widget_icon">
                            <svg>123</svg>
                        </div>
                        <div class="widget_text"><span style="overflow-wrap: normal;">ABCD TEXT</span></div>
                    </div>
                </button>

               <button type="button" class="buttonShadow" onclick="window.open('https://somepagelink.aspx); return false;">
                    <div class="widget_item">
                        <div class="widget_icon">
                            <svg> 12345</svg>
                        </div>
                        <div class="widget_text"><span style="overflow-wrap: normal;">XYZ TEXT</span></div>
                    </div>
                </button>

            </div>
        </div>
    </div>
</section>
<!-- END: Widget Links --></div>

</code>```

I have 12 buttons in this same format. Here i have given an example of two buttons.

Button name i can change later so i can not take it as hard coded for "Click Text" in tag manager.

I can use only rel= "ABC_Links" as unique identifier. I can not use any of below class as they are not unique.

I have used Custome javascript to get parent child relationship but didn't work.

I have used DOM element variable but it did not work.

Now Question is, Is there any way to trigger event in tag manager when i click on any of the button below and get the info in real time event in Anayltics 360 ???

答:
One way to achieve this would be to create a User-Defined Custom JavaScript variable in GTM to set isABCLink=true on button click.

On the Variables screen under Built-In Variables make sure you have "Click Element" ticked.

Create a User-Defined Variable

Name: isABCLink

Type: Custom JavaScript

Code: ```
function() {
  return {{Click Element}}.matches("div[rel=ABC_Links] button, div[rel=ABC_Links] button *");
}
```

Create a Trigger

Trigger Type: Click - All Elements

This trigger fires on: Some Clicks

Conditions: isABCLink equals true

Set up your tag firing on above trigger

Once caveat to point out is that the exact element clicked on could be the button or one of the child elements of the button such as the <svg> which might make it hard to set up your tag depending on what exactly you need.

Body:
I am using Tag manager and Anayltics 360.

My code as follows,

                <button type="button" class="buttonShadow" onclick="window.open('https://somepagelink.aspx); return false;">

                            <svg>123</svg>

ABCD TEXT

                </button>

               <button type="button" class="buttonShadow" onclick="window.open('https://somepagelink.aspx); return false;">

                            <svg> 12345</svg>

XYZ TEXT

                </button>

I have 12 buttons in this same format. Here i have given an example of two buttons.

Button name i can change later so i can not take it as hard coded for "Click Text" in tag manager.

I can use only rel= "ABC_Links" as unique identifier. I can not use any of below class as they are not unique.

I have used Custome javascript to get parent child relationship but didn't work.

I have used DOM element variable but it did not work.

Now Question is, Is there any way to trigger event in tag manager when i click on any of the button below and get the info in real time event in Anayltics 360 ???

Body:
One way to achieve this would be to create a User-Defined Custom JavaScript variable in GTM to set isABCLink=true on button click.

On the Variables screen under Built-In Variables make sure you have "Click Element" ticked.

Create a User-Defined Variable

Name: isABCLink

Type: Custom JavaScript

Code:

function() {
  return {{Click Element}}.matches("div[rel=ABC_Links] button, div[rel=ABC_Links] button *");
}

Create a Trigger

Trigger Type: Click - All Elements

This trigger fires on: Some Clicks

Conditions: isABCLink equals true

Set up your tag firing on above trigger

Once caveat to point out is that the exact element clicked on could be the button or one of the child elements of the button such as the <svg> which might make it hard to set up your tag depending on what exactly you need.


问:
Direct call without pressing green button flutter in ios build
I m using call_number plugin for direct call in flutter but the problem is that this is only working for Android not for iOS how I can build this functionality in iOS build.</p>

答:
Create your calling function as;

```<code>_call() async {
    if(numberToCall != null)
      await CallNumber().callNumber(numberToCall);
  }
</code>```

example usage:

```<code>IconButton(onPressed: _call);
</code>```

Body:
Create your calling function as;

_call() async {
    if(numberToCall != null)
      await CallNumber().callNumber(numberToCall);
  }

example usage:

IconButton(onPressed: _call);


问:
kusto how to write subquery
problem:
for each row in a table (from analytics table) I am trying to run a subquery to find the corresponding row in a second table (from externaldata). I think I want a subquery but there maybe a better option. there is no column linking each table so I cant use join, the only relationship is that the numbers from the analytics table may be between a start and end number in an externaldata table.

```<code>let IDlist = datatable(value:long)
[
45,
76,
150,
202,
2156,
3004,
5001,
];

// imported from externaldata
let idlookup = datatable(start:long, end:long, name:string)
[
1,100,"bob",
101,105,"susan",
200,1000,"henry",
5000,5004,"clair",
];

//using between doesnt work
idlookup
| where idlist between (start .. end)
| project idlist, name

expected output
45 - bob
76 - bob
150 - no match
202 - henry
2156 - no match
3004 - no match
5001 - clair
</code>```

The query above doesn't work as expression before the between statement is not a scalar expression. I hoped a subquery would solve this but I cant get figure out the syntax.
Any help is much appreciated.

答:
Here is one way:

let IDlist = datatable(value:long)
[
    45,
    76,
    150,
    202,
    2156,
    3004,
    5001,
];
// imported from externaldata
let idlookup = datatable(start:long, end:long, name:string)
[
    1, 100, "bob",
    101, 105, "susan",
    200, 1000, "henry",
    5000, 5004, "clair",
];
IDlist
| extend dummy = 1
| lookup (idlookup | extend dummy = 1) on dummy
| where value >=start and value <= end
| join kind=rightouter (IDlist) on value
| extend name = iff(isempty( name), "no match", name)
| project name, value = value1
```

Title: kusto how to write subquery

Body:
problem:
for each row in a table (from analytics table) I am trying to run a subquery to find the corresponding row in a second table (from externaldata). I think I want a subquery but there maybe a better option. there is no column linking each table so I cant use join, the only relationship is that the numbers from the analytics table may be between a start and end number in an externaldata table.

let IDlist = datatable(value:long)
[
45,
76,
150,
202,
2156,
3004,
5001,
];

// imported from externaldata
let idlookup = datatable(start:long, end:long, name:string)
[
1,100,"bob",
101,105,"susan",
200,1000,"henry",
5000,5004,"clair",
];

//using between doesnt work
idlookup
| where idlist between (start .. end)
| project idlist, name

expected output
45 - bob
76 - bob
150 - no match
202 - henry
2156 - no match
3004 - no match
5001 - clair

The query above doesn't work as expression before the between statement is not a scalar expression. I hoped a subquery would solve this but I cant get figure out the syntax.
Any help is much appreciated.


问:
What is the difference between res.send and res.write in express?
I am a beginner to express.js and I am trying to understand the difference between res.send and res.write ?

答:
Suppose you have two line that needs to be shown up and you use res.send as

```<code>res.send("shows only First Line")
res.send("won't show second Line")
</code>```

Then only first line will show up, whereas using res.write you have flexibility to write multiple line such as

```<code>res.write("Shows first line")
res.write("Shows second line")
res.send()
</code>```

Body:
Suppose you have two line that needs to be shown up and you use res.send as

res.send("shows only First Line")
res.send("won't show second Line")

Then only first line will show up, whereas using res.write you have flexibility to write multiple line such as

res.write("Shows first line")
res.write("Shows second line")
res.send()


问:
How to install pip for python3.7 only?
I have python3.7 and I want to install pip. However when I do the following:

```<code>sudo apt install python3-pip
</code>```

It seems to download python version 3.6 and pip for that. Is there a way to not download python3.6 and just download pip for python3.7? It seems rather strange that pip is download a whole other package.

答:
Deadsnakes

You can use a ppa called deadsnakes.

```<code>sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.7
</code>```

Then check that is has been installed successfully by running python3.7 --version. To use pip you can run python3.7 -m pip install package.

Compiling from source

You can build Python by yourself, on Debian based systems you would do:

```<code>sudo apt-get update; sudo apt-get install make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
</code>```

Download your preferred python version from https://www.python.org/ftp/python/

Then extract the tar archive and run make

```<code>./configure --enable-optimizations
make
sudo make altinstall
</code>```

Then run python3.7 --version

Title: How to install pip for python3.7 only?

Body:
I have python3.7 and I want to install pip. However when I do the following:

sudo apt install python3-pip

It seems to download python version 3.6 and pip for that. Is there a way to not download python3.6 and just download pip for python3.7? It seems rather strange that pip is download a whole other package.

Body:
Deadsnakes

You can use a ppa called deadsnakes.

sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.7

Then check that is has been installed successfully by running python3.7 --version. To use pip you can run python3.7 -m pip install package.

Compiling from source

You can build Python by yourself, on Debian based systems you would do:

sudo apt-get update; sudo apt-get install make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev

Download your preferred python version from https://www.python.org/ftp/python/

Then extract the tar archive and run make

./configure --enable-optimizations
make
sudo make altinstall

Then run python3.7 --version


问:
unexpected results which is empty array
when I run code, I see empty array, but I aim to have an array with some vowels.

let input = 'zai';
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];

for (let inputindex = 0; inputindex < input.inputindex; inputindex++) {
  for (let vowel = 0; vowel > vowels.length; vowel++) {
    if (input[inputindex] === vowels[vowel]) {
      resultArray.push(input[inputindex])
    }
  }
}

console.log(resultArray)```

答:
input string but you need array, i use split.
and some mistakes in loops

```<code>let input = 'zai';
let input2 = input.split('')
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];

 for(let inputindex = 0; inputindex < input2.length; inputindex++){
   for(let vowel = 0; vowel < vowels.length; vowel++){
     if(input2[inputindex] === vowels[vowel]){
       resultArray.push(input2[inputindex])
     }
   }
 }

display.log(resultArray)
</code>```

Without array

```<code>let input = 'zai';
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];

 for(let inputindex = 0; inputindex < input2.length; inputindex++){
   for(let vowel = 0; vowel < vowels.length; vowel++){
     if(input.slice(inputindex, inputindex+1) === vowels[vowel]){
       resultArray.push(input.slice(inputindex, inputindex+1))
     }
   }
 }

display.log(resultArray)
</code>```

Title: unexpected results which is empty array

Body:
input string but you need array, i use split.
and some mistakes in loops

let input = 'zai';
let input2 = input.split('')
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];

 for(let inputindex = 0; inputindex < input2.length; inputindex++){
   for(let vowel = 0; vowel < vowels.length; vowel++){
     if(input2[inputindex] === vowels[vowel]){
       resultArray.push(input2[inputindex])
     }
   }
 }

display.log(resultArray)

Without array

let input = 'zai';
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];

 for(let inputindex = 0; inputindex < input2.length; inputindex++){
   for(let vowel = 0; vowel < vowels.length; vowel++){
     if(input.slice(inputindex, inputindex+1) === vowels[vowel]){
       resultArray.push(input.slice(inputindex, inputindex+1))
     }
   }
 }

display.log(resultArray)


问:
Uploading files using the Postman binary method to asp.net MVC controller cannot receive files?
In the Postman tool, using the Form-data method to upload files to asp.net MVC controller can receive files normally, but using the binary method to upload file controller Action method Request.Files Unable to receive the file, excuse me where is the mistake?

For example, controller action:

```<code>public class UploadFilesController : Controller
{
    // GET: UploadFiles
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Test()
    {
        if (Request.Files.Count > 0)
        {
            var file = Request.Files[0];

            return Json("OK! Received file");
        }
        else
        {
            return Json("No file Received");
        }

    }
}
</code>```

The following is the Postman binary method upload file icon:

答:
As you have not set Content-Type explicitly, Postman set default Content-Type. For form-data type of body, Postman sets Content-Type to multipart/form-data. And it does not set Content-Type for binary method. But in a binary type, the file attached must be binary in nature i.e. not human-readable. It seems that your file is human readable and hence your request is not processed as you are expecting.

You can refer below link for default Content-Type in different cases.

text/plain is the default value for textual files. A textual file should be human-readable and must not contain binary data. application/octet-stream is the default value for all other cases.

Sending request using Postman - click here

Body:
In the Postman tool, using the Form-data method to upload files to asp.net MVC controller can receive files normally, but using the binary method to upload file controller Action method Request.Files Unable to receive the file, excuse me where is the mistake?

For example, controller action:

public class UploadFilesController : Controller
{
    // GET: UploadFiles
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Test()
    {
        if (Request.Files.Count > 0)
        {
            var file = Request.Files[0];

            return Json("OK! Received file");
        }
        else
        {
            return Json("No file Received");
        }

    }
}

The following is the Postman binary method upload file icon: