问:
How to multiply a number until it reaches a specific number in Python?
I want this code to multiply this list until all numbers exceeds 100, but I am struggling in the loop part.

import numpy as np

a = np.array([230, 10, 284, 39, 76])

def all_30_or_up(ls):
    for i in ls:
        if i < 100:
            return False
    return True

while True:
    if all_30_or_up(a) == False:
        print(a*2)
    else:
        break
```
<p>This exercise is from the book "How to Think Like a Computer Scientist: Learning with Python 3". That's the actual question in the book:</p>
<p>"Use a mask to multiply all values below 100 in the following list by 2:</p>
<pre class="lang-py prettyprint-override"><code>a = np.array([230, 10, 284, 39, 76])
</code>```

Repeat this until all values are above 100. (Not manually, but by looping)
Then, select all values between 150 < a < 200."

答:
You start off with a = np.array([230, 10, 284, 39, 76])

Now, you want to continue looping while any of the values in a are less than 100. Since a is a numpy array, the best way to do this is to check which values are less than 100, and then run the np.any() function.

```<code>while (a < 100).any():
    # do something
</code>```

Now, we want to multiply the values that are less than 100 by 2. Remember, we want to modify the original array.

```<code>where_to_multiply = a < 100 # Gives an array of True / False.
a[where_to_multiply] = a[where_to_multiply] * 2
</code>```

All combined, and if your python version supports the walrus operator, you can do:

```<code>while ((where_to_multiply := a < 100)).any():
    a[where_to_multiply] = a[where_to_multiply] * 2
    print(a)
</code>```

Which gives the output:

```<code>[230  20 284  78 152]
[230  40 284 156 152]
[230  80 284 156 152]
[230 160 284 156 152]
</code>```

Finally, you can filter out the unwanted values using a similar logical indexing:

```<code>gt_150 = a > 150
lt_200 = a < 200
select_elem = np.logical_and(gt_150, lt_200)
filtered_a = a[select_elem] # array([160, 156, 152])
</code>```

Body:
I want this code to multiply this list until all numbers exceeds 100, but I am struggling in the loop part.

import numpy as np

a = np.array([230, 10, 284, 39, 76])

def all_30_or_up(ls):
    for i in ls:
        if i < 100:
            return False
    return True

while True:
    if all_30_or_up(a) == False:
        print(a*2)
    else:
        break

This exercise is from the book "How to Think Like a Computer Scientist: Learning with Python 3". That's the actual question in the book:

"Use a mask to multiply all values below 100 in the following list by 2:

a = np.array([230, 10, 284, 39, 76])

Repeat this until all values are above 100. (Not manually, but by looping)
Then, select all values between 150 < a < 200."

Body:
You start off with a = np.array([230, 10, 284, 39, 76])

Now, you want to continue looping while any of the values in a are less than 100. Since a is a numpy array, the best way to do this is to check which values are less than 100, and then run the np.any() function.

while (a < 100).any():
    # do something

Now, we want to multiply the values that are less than 100 by 2. Remember, we want to modify the original array.

where_to_multiply = a < 100 # Gives an array of True / False.
a[where_to_multiply] = a[where_to_multiply] * 2

All combined, and if your python version supports the walrus operator, you can do:

while ((where_to_multiply := a < 100)).any():
    a[where_to_multiply] = a[where_to_multiply] * 2
    print(a)

Which gives the output:

[230  20 284  78 152]
[230  40 284 156 152]
[230  80 284 156 152]
[230 160 284 156 152]

Finally, you can filter out the unwanted values using a similar logical indexing:

gt_150 = a > 150
lt_200 = a < 200
select_elem = np.logical_and(gt_150, lt_200)
filtered_a = a[select_elem] # array([160, 156, 152])


来源: stackexchange

问:
Java 11 sending HTTP post request without body
I am using java 11 http client and I need to send a post request without body.

```<code>HttpRequest request = getRequestBuilder()
    .uri(urlBuilder.toURL().toURI())
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
</code>```

When I try as above I receive 411 error code.
I also tried to set "Content-Length" header "0" but saw that is restricted.

Then I tried this:

```<code>    URL url = new URL(getHost());
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("trackingNo", orderPackage.getCargoTrackingCode());
    params.put("referenceNo", orderPackage.getCargoCode());

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    StringBuilder sb = new StringBuilder();
    for (int c; (c = in.read()) >= 0;)
        sb.append((char)c);
    String response = sb.toString();
</code>```

It throws java.io.FileNotFoundException

Normally I should use response like below:

```<code>CancelDeliveryResponse cancelDeliveryResponse = gson.fromJson(httpResponse.body(), CancelDeliveryResponse.class);
</code>```

So how can I make this request?

答:
You should be able to do the same with HttpClient - on Jdk 11 if I enable logging with -Djdk.httpclient.HttpClient.log=requests,headers I can see that Content-Length: 0 is sent with the following request:

```<code>HttpRequest request = HttpRequest.newBuilder()
    .uri(<uri>)
    .header("Authorization", "Bearer " + <token>)
    .version(HttpClient.Version.HTTP_1_1)
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using java 11 http client and I need to send a post request without body.

HttpRequest request = getRequestBuilder()
    .uri(urlBuilder.toURL().toURI())
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

When I try as above I receive 411 error code.
I also tried to set "Content-Length" header "0" but saw that is restricted.

Then I tried this:

    URL url = new URL(getHost());
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("trackingNo", orderPackage.getCargoTrackingCode());
    params.put("referenceNo", orderPackage.getCargoCode());

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    StringBuilder sb = new StringBuilder();
    for (int c; (c = in.read()) >= 0;)
        sb.append((char)c);
    String response = sb.toString();

It throws java.io.FileNotFoundException

Normally I should use response like below:

CancelDeliveryResponse cancelDeliveryResponse = gson.fromJson(httpResponse.body(), CancelDeliveryResponse.class);

So how can I make this request?

Body:
You should be able to do the same with HttpClient - on Jdk 11 if I enable logging with -Djdk.httpclient.HttpClient.log=requests,headers I can see that Content-Length: 0 is sent with the following request:

HttpRequest request = HttpRequest.newBuilder()
    .uri(<uri>)
    .header("Authorization", "Bearer " + <token>)
    .version(HttpClient.Version.HTTP_1_1)
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());


问:
rhomobile prepopulated DB and reset
Hi I am prepopulating the db as said here
http://docs.rhomobile.com/faq#how-to-pre-populate-client-database
but I have a problem, that when I make reset DB with default code

```<code>def do_reset
    Rhom::Rhom.database_full_reset
    SyncEngine.dosync
    @msg = "Database has been reset."
    redirect :action => :index, :query => {:msg => @msg}
  end
</code>```

then I am losing the data. How can I make that the prepopulated database alsways will be loaded, when I make reset.
Cheers

I come up with such solution

in view do_reset.erb

```<code><%
Antwort.delete_all()
   file_name = File.join(Rho::RhoApplication::get_model_path('app','Settings'), 'antwort.txt')
   file = File.new(file_name,"r")
   aid=0
   file.each_line("\n") do |row|
     col = row.split("|")
 aid=aid+1
    @antwort=Antwort.create(
       {"aid" => aid, "qid" => col[0],"antwort"=>col[1],"richtig"=>col[2]}
     )

     qty=file.lineno
     break if file.lineno > 3000
   end

   Questions.delete_all()
file_name = File.join(Rho::RhoApplication::get_model_path('app','Settings'), 'questions.txt')
  file = File.new(file_name)

  file.each_line("\n") do |row|
    col = row.split("|")

   @question=Questions.create(
      {"id" => col[0], "question" => col[1],"answered"=>'0',"show"=>'1',"tutorial"=>col[4]}
    )

    break if file.lineno > 1500
  end
file.close
  @msg="OK"
  %>
</code>```

But only problem I have now is single quotes aka '   in the texts. They are then displayed in app as a triangle with ? inside  like  � one. What to do?

答:
You can seed the database using a pipe delimited text file, as explained here.

So, in the instance you are using the Property Bag model definitions, you will have a file called object_values.txt and load up whichever sources, properties, and values necessary.

ContentLicense: CC BY-SA 3.0

Title: rhomobile prepopulated DB and reset

Body:
Hi I am prepopulating the db as said here
http://docs.rhomobile.com/faq#how-to-pre-populate-client-database
but I have a problem, that when I make reset DB with default code

def do_reset
    Rhom::Rhom.database_full_reset
    SyncEngine.dosync
    @msg = "Database has been reset."
    redirect :action => :index, :query => {:msg => @msg}
  end

then I am losing the data. How can I make that the prepopulated database alsways will be loaded, when I make reset.
Cheers

I come up with such solution

in view do_reset.erb

<%
Antwort.delete_all()
   file_name = File.join(Rho::RhoApplication::get_model_path('app','Settings'), 'antwort.txt')
   file = File.new(file_name,"r")
   aid=0
   file.each_line("\n") do |row|
     col = row.split("|")
 aid=aid+1
    @antwort=Antwort.create(
       {"aid" => aid, "qid" => col[0],"antwort"=>col[1],"richtig"=>col[2]}
     )

     qty=file.lineno
     break if file.lineno > 3000
   end

   Questions.delete_all()
file_name = File.join(Rho::RhoApplication::get_model_path('app','Settings'), 'questions.txt')
  file = File.new(file_name)

  file.each_line("\n") do |row|
    col = row.split("|")

   @question=Questions.create(
      {"id" => col[0], "question" => col[1],"answered"=>'0',"show"=>'1',"tutorial"=>col[4]}
    )

    break if file.lineno > 1500
  end
file.close
  @msg="OK"
  %>

But only problem I have now is single quotes aka '   in the texts. They are then displayed in app as a triangle with ? inside  like  � one. What to do?


问:
How can I send data from a tablayout fragment to the main activity
I have a listview in my tablayout. When I click on one of these elements, I want that element to be added to a list in the mainactivity. So that I can display this list on another fragment.</p>

答:
You can use interface when clicked on item
Create interface like this in one fragment

```<code>public interface OnClickListener{
     void onClick(Item listItem);
}
</code>```

and in fragment create object like:

```<code>OnClickListener onClickListener;
</code>```

and in onAttach assign the object

```<code> @Override
 public void onAttach(Context context) {
super.onAttach(context);
    try {
      onClickListener= (onClickListener) context;
    } catch (ClassCastException e) {

    }
 }
</code>```

and then implement this listener in your MainActivity

```<code>public class MainActivity extends AppCompatActivity implements onClickListener{}
</code>```

and on button click in fragment pass the data to your MainActivity

```<code> button.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
    onClickListener.onClick(YOUR_ITEM);
  }
});
</code>```

Body:
You can use interface when clicked on item
Create interface like this in one fragment

public interface OnClickListener{
     void onClick(Item listItem);
}

and in fragment create object like:

OnClickListener onClickListener;

and in onAttach assign the object

 @Override
 public void onAttach(Context context) {
super.onAttach(context);
    try {
      onClickListener= (onClickListener) context;
    } catch (ClassCastException e) {

    }
 }

and then implement this listener in your MainActivity

public class MainActivity extends AppCompatActivity implements onClickListener{}

and on button click in fragment pass the data to your MainActivity

 button.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
    onClickListener.onClick(YOUR_ITEM);
  }
});


问:
the system cannot find the file npx create-react-app myapp
To create a react app, when I use

```<code>npx create-react-app myapp
</code>```

I get an error saying

"PS C:\Users\yashj\OneDrive\Desktop\messaging_app> npx create-react-app myapp

  Program 'npx.cmd' failed to run: The system cannot find the file

  specifiedAt line:1 char:1

  + npx create-react-app myapp

  + ~~~~~~~~~~~~~~~~~~~~~~~~~~.

  At line:1 char:1

  + npx create-react-app myapp

  + ~~~~~~~~~~~~~~~~~~~~~~~~~~

      + CategoryInfo          : ResourceUnavailable: (:) [],

  ApplicationFailedException

      + FullyQualifiedErrorId : NativeCommandFailed"

I have reinstalled nodejs again but still, I get the same error.

答:
To solve this problem, I suggest using the command in PowerShell
If the problem persists, install a new version of PowerShell and then run the command</p>

Body:
To create a react app, when I use

npx create-react-app myapp

I get an error saying

"PS C:\Users\yashj\OneDrive\Desktop\messaging_app> npx create-react-app myapp

  Program 'npx.cmd' failed to run: The system cannot find the file

  specifiedAt line:1 char:1

  + npx create-react-app myapp

  + ~~~~~~~~~~~~~~~~~~~~~~~~~~.

  At line:1 char:1

  + npx create-react-app myapp

  + ~~~~~~~~~~~~~~~~~~~~~~~~~~

      + CategoryInfo          : ResourceUnavailable: (:) [],

  ApplicationFailedException

      + FullyQualifiedErrorId : NativeCommandFailed"

I have reinstalled nodejs again but still, I get the same error.


问:
SQL determine business days passed since beginning of month using calendar table
I have a calendar table with all dates and a column indicating whether its a business day.

For example

Date
Business_Day

1/1/2021
False

1/2/2021
False

1/3/2021
True

...
I have another table with dates and would like to determine how many business days have elapsed since the beginning of that month.
For example:

Date
Business_Days_Passed

1/1/2022
0

1/2/2022
0

1/3/2022
1

1/4/2022
2

1/15/2022
10

2/2/2022
2

2/11/2022
9

2/12/2022
9

Is there a way to do this using standard sql?  I was thinking of creating some kind of UDF but there may be an easier way?  This using snowflake so there is access to all common date functions and window/udf functions

答:
Here is a simple query</p>
```<code>Select count(c.date) from calendar c
Join dates_to_check d
Where month(c.date) = month(d.day)
And day(c.date) < day(d.day)
And business_Day = True;
</code>```

Body:
Here is a simple query

Select count(c.date) from calendar c
Join dates_to_check d
Where month(c.date) = month(d.day)
And day(c.date) < day(d.day)
And business_Day = True;


问:
Postgres date value dynamic inserting
I am scratching my head trying to fix the following:

```<code>create or replace procedure my_schema.Test()
as $$

declare
    today date = now();

begin
    drop table if exists my_schema.tst_table;
    create table  my_schema.tst_table (
        todays_date varchar     );

    execute('
        insert into my_schema.tst_table
        values (' || today || ')
    ');

end;
$$
language plpgsql;
</code>```

Basically I am trying to dynamically insert the current date into a table which will be used in later steps.

The issue I am facing is that due to the today variable looking like '2022-02-11',  and because I am inserting the record dynamically, postgres is interpreting the "-" as a minus sign and inserting the value 2009 into my table.

Does anyone have a workaround for this?

答:
Don't concatenate input values into dynamic SQL. And never store date values in a varchar column:

```<code>create or replace procedure my_schema.Test()
as $$
declare
    today date := current_date;
begin
    drop table if exists my_schema.tst_table;
    create table  my_schema.tst_table
    (
      todays_date date
    );

    execute('
        insert into my_schema.tst_table
        values ($1)
    ') using today;
end;
$$
language plpgsql;
</code>```

But creating a table just to store the value of current_date seems a bit of an overkill.

Title: Postgres date value dynamic inserting

Body:
I am scratching my head trying to fix the following:

create or replace procedure my_schema.Test()
as $$

declare
    today date = now();

begin
    drop table if exists my_schema.tst_table;
    create table  my_schema.tst_table (
        todays_date varchar     );

    execute('
        insert into my_schema.tst_table
        values (' || today || ')
    ');

end;
$$
language plpgsql;

Basically I am trying to dynamically insert the current date into a table which will be used in later steps.

The issue I am facing is that due to the today variable looking like '2022-02-11',  and because I am inserting the record dynamically, postgres is interpreting the "-" as a minus sign and inserting the value 2009 into my table.

Does anyone have a workaround for this?

Body:
Don't concatenate input values into dynamic SQL. And never store date values in a varchar column:

create or replace procedure my_schema.Test()
as $$
declare
    today date := current_date;
begin
    drop table if exists my_schema.tst_table;
    create table  my_schema.tst_table
    (
      todays_date date
    );

    execute('
        insert into my_schema.tst_table
        values ($1)
    ') using today;
end;
$$
language plpgsql;

But creating a table just to store the value of current_date seems a bit of an overkill.


问:
How can I work around pagination using chunk because of repeated errors being thrown?
I'm trying to paginate my json response in terms of multiples of 20 but for some reason, I'm getting Error: Call to a member function chunk() on array.

To clarify, $results has data in it and $request->get('offset'); has a value.  Is there something I'm doing wrong?  I'm seeing examples when searching on SO where people are doing this on a collection but for some reason, it isn't working for me. How can I make this work?

Note: If I do dd($results['num_results']);, it displays 360.  I feel like I need to use this some how but I'm not sure how.  I'm trying to achieve this in the most Laravel way possible.  Also note, no database is being used - this is simply a get request on an external API.

Thanks in advance.

```<code>collect($results);
$outputs = $results->chunk(20)[$request->get('offset')];
dd($outputs);
</code>```

答:
$results is still an array. You are not setting the new Collection you are creating to a variable: collect($results). This does not change $results. So you are calling chunk on the array, $results. Call chunk on the Collection instead:

```<code>$collection = collect($results);
$outputs = $collection->chunk(20)...;
</code>```

Body:
I'm trying to paginate my json response in terms of multiples of 20 but for some reason, I'm getting Error: Call to a member function chunk() on array.

To clarify, $results has data in it and $request->get('offset'); has a value.  Is there something I'm doing wrong?  I'm seeing examples when searching on SO where people are doing this on a collection but for some reason, it isn't working for me. How can I make this work?

Note: If I do dd($results['num_results']);, it displays 360.  I feel like I need to use this some how but I'm not sure how.  I'm trying to achieve this in the most Laravel way possible.  Also note, no database is being used - this is simply a get request on an external API.

Thanks in advance.

collect($results);
$outputs = $results->chunk(20)[$request->get('offset')];
dd($outputs);

Body:
$results is still an array. You are not setting the new Collection you are creating to a variable: collect($results). This does not change $results. So you are calling chunk on the array, $results. Call chunk on the Collection instead:

$collection = collect($results);
$outputs = $collection->chunk(20)...;


答:
Numpy allows for conditional selection and multiplication:

```<code>import numpy as np

a = np.array([230, 10, 284, 39, 76])

while a [a<100].any():   # loop and check if any < 100
        a [a<100] *= 2   # using a mask to multiply
        print(a)

print("done")
</code>```

Output:

```<code>[230  20 284  78 152]
[230  40 284 156 152]
[230  80 284 156 152]
[230 160 284 156 152]
done
</code>```

Use print(a[(a>150) * (a<200)]) to filter down to [160 156 152]

Title: How to multiply a number until it reaches a specific number in Python?

Body:
Numpy allows for conditional selection and multiplication:

import numpy as np

a = np.array([230, 10, 284, 39, 76])

while a [a<100].any():   # loop and check if any < 100
        a [a<100] *= 2   # using a mask to multiply
        print(a)

print("done")

Output:

[230  20 284  78 152]
[230  40 284 156 152]
[230  80 284 156 152]
[230 160 284 156 152]
done

Use print(a[(a>150) * (a<200)]) to filter down to [160 156 152]


问:
Regex exclude rows in csv that has forbidding word
I've been trying to exclude all the rows that contain 'shirt' and then from that have the rows that have 'cotton' (case insensitive)
for example:

"Cotton Shirt for sale" - don't include

"Cotton Dress for Sale" - Pass

"dress shirt-V-neck-cotton" -fail

"no words relevant" - Fail (no cotton in it)

"cotton-url click" - pass

My regex:

```<code>pattern = re.compile('(?i)^((?!.*shirt).).*(?=.*cotton.*)')
</code>```

But for some reason my rows in csv still remain on a sentence:

"Stone Italian Yarn Fringe Yoke Cable Cotton Shirt New Look"

my code:

```<code>pattern1 = re.compile("(?i)(.*shirt.*)")
    with open("sample.csv", 'r', encoding="utf-8") as bigCSV:
        csv_reader = csv.reader(bigCSV)
        counterWithout = 0
        counterCheck = 0
        headFlag = True
        for row in csv_reader:
            if headFlag:
                header = row
                headFlag = False
            if any(pattern.match(line) for line in row)://there is a difference in the number of rows here
                if any(pattern1.match(line) for line in row):
                    print(row)
                    counterCheck += 1
                counterWithout += 1
</code>```

Help fix regex please

答:
Options:

Define two regex patterns (# Solution 1)

Use re.findall (# Solution 2)

Search 'shirt' behind and ahead of 'cotton' (# Solution 3)

Check strings without regex (# Solution 4)

Code:

# Preparation:

import re

test_strings = [
    'Cotton Shirt for sale',
    'Cotton Dress for Sale', # Pass
    'dress shirt-V-neck-cotton',
    'no words relevant',
    'cotton-url click', # Pass
    'Stone Italian Yarn Fringe Yoke Cable Cotton Shirt New Look',
    'Black Chunky Cotton Round Neck Shirt',
    ]
```
<h3># Solution 1:</h3>
<pre class="lang-py prettyprint-override"><code>pat_cotton = re.compile(r'cotton', re.IGNORECASE)
pat_shirt = re.compile(r'shirt', re.IGNORECASE)

for s in test_strings:
    if pat_cotton.search(s) and not pat_shirt.search(s):
        print(s)
</code>```

# Solution 2:

pat = re.compile(r'shirt|cotton', re.IGNORECASE)

for s in test_strings:
    elements = set(e.lower() for e in pat.findall(s))
    if 'cotton' in elements and len(elements) == 1:
        print(s)
```
<h3># Solution 3:</h3>
<pre class="lang-py prettyprint-override"><code>pat = re.compile(r'.*(?:(shirt)|^).*?cotton.*?(?:(shirt)|$)', re.IGNORECASE)

for s in test_strings:
    m = pat.search(s)
    if m and m.group(1) is None and m.group(2) is None:
        print(s)
</code>```

# Solution 4:

for s in test_strings:
    s_lower = s.lower()
    if s_lower.find('cotton') >= 0 and s_lower.find('shirt') < 0:
        print(s)
```
<h2>Output:</h2>
```Cotton Dress for Sale
cotton-url click
```

Body:
I've been trying to exclude all the rows that contain 'shirt' and then from that have the rows that have 'cotton' (case insensitive)
for example:

"Cotton Shirt for sale" - don't include

"Cotton Dress for Sale" - Pass

"dress shirt-V-neck-cotton" -fail

"no words relevant" - Fail (no cotton in it)

"cotton-url click" - pass

My regex:

pattern = re.compile('(?i)^((?!.*shirt).).*(?=.*cotton.*)')

But for some reason my rows in csv still remain on a sentence:

"Stone Italian Yarn Fringe Yoke Cable Cotton Shirt New Look"

my code:

pattern1 = re.compile("(?i)(.*shirt.*)")
    with open("sample.csv", 'r', encoding="utf-8") as bigCSV:
        csv_reader = csv.reader(bigCSV)
        counterWithout = 0
        counterCheck = 0
        headFlag = True
        for row in csv_reader:
            if headFlag:
                header = row
                headFlag = False
            if any(pattern.match(line) for line in row)://there is a difference in the number of rows here
                if any(pattern1.match(line) for line in row):
                    print(row)
                    counterCheck += 1
                counterWithout += 1

Help fix regex please

Body:
Options:

Define two regex patterns (# Solution 1)

Use re.findall (# Solution 2)

Search 'shirt' behind and ahead of 'cotton' (# Solution 3)

Check strings without regex (# Solution 4)

Code:

# Preparation:

import re

test_strings = [
    'Cotton Shirt for sale',
    'Cotton Dress for Sale', # Pass
    'dress shirt-V-neck-cotton',
    'no words relevant',
    'cotton-url click', # Pass
    'Stone Italian Yarn Fringe Yoke Cable Cotton Shirt New Look',
    'Black Chunky Cotton Round Neck Shirt',
    ]

# Solution 1:

pat_cotton = re.compile(r'cotton', re.IGNORECASE)
pat_shirt = re.compile(r'shirt', re.IGNORECASE)

for s in test_strings:
    if pat_cotton.search(s) and not pat_shirt.search(s):
        print(s)

# Solution 2:

pat = re.compile(r'shirt|cotton', re.IGNORECASE)

for s in test_strings:
    elements = set(e.lower() for e in pat.findall(s))
    if 'cotton' in elements and len(elements) == 1:
        print(s)

# Solution 3:

pat = re.compile(r'.*(?:(shirt)|^).*?cotton.*?(?:(shirt)|$)', re.IGNORECASE)

for s in test_strings:
    m = pat.search(s)
    if m and m.group(1) is None and m.group(2) is None:
        print(s)

# Solution 4:

for s in test_strings:
    s_lower = s.lower()
    if s_lower.find('cotton') >= 0 and s_lower.find('shirt') < 0:
        print(s)

Output:

Cotton Dress for Sale
cotton-url click


问:
when i check dart version on cmd i got version 2.16.0(stable) but on flutter doctor i found 2.0.14
```<code>dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  sqflite: ^2.0.1
  intl: ^0.17.0
  bloc: ^8.0.2
  flutter_bloc: ^8.0.1
  conditional_builder_null_safety: ^0.0.6
  dio: ^4.0.4
  shared_preferences: ^2.0.5
  webview_flutter: ^3.0.0
</code>```

I get this error:

```<code>The current Dart SDK version is 2.13.4

Because todo depends on webview_flutter >=2.0.14 which requires SDK version >=2.14.0 <3.0.0, version solving failed.
pub get failed (1; Because todo depends on webview_flutter >=2.0.14 which requires SDK version >=2.14.0 <3.0.0, version solving failed.)
</code>```

答:
Your current dart sdk version is 2.13.4, 2.0.14 is webview_flutter version, and in error message it asks you so dart sdk version is above 2.14.

Since one of the releases( do not remember which one :(, proof is here ) Dart is bundled with flutter sdk so if you installed dart on your system separately versions might mismatch because flutter uses bundled one and in shell you see system one. try upgrading flutter sdk constraints.

Body:
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  sqflite: ^2.0.1
  intl: ^0.17.0
  bloc: ^8.0.2
  flutter_bloc: ^8.0.1
  conditional_builder_null_safety: ^0.0.6
  dio: ^4.0.4
  shared_preferences: ^2.0.5
  webview_flutter: ^3.0.0

I get this error:

The current Dart SDK version is 2.13.4

Because todo depends on webview_flutter >=2.0.14 which requires SDK version >=2.14.0 <3.0.0, version solving failed.
pub get failed (1; Because todo depends on webview_flutter >=2.0.14 which requires SDK version >=2.14.0 <3.0.0, version solving failed.)


问:
How to expand a Toggle upwards in react bootstrap?
I'm experimentating react bootstrap.

With the component Navbar.Collapse, to expand a NavDropdown upwards, i found this property drop="up"

```<code><Navbar>
  <Navbar.Toggle aria-controls="basic-navbar-nav"/>
  <Navbar.Collapse id="responsive-navbar-nav">
      <Nav>
         <NavDropdown drop="up"
              title="Changer la police"
              id="basic-nav-nav"
               onSelect={changeFont} >
                  <NavDropdown.Item
                    className={font.name}
                    eventKey={font.name}>
                    {font.name}
                  </NavDropdown.Item>
        </NavDropdown>
     </Nav>
   </Navbar.Collapse>
</Navbar>
</code>```

But i didn't find the equivalent for Navbar.Toggle, to as well expand upwards instead of downwards.

Thank you

答:
I found a solution,

I added this code to the css :

```<code>.CustomFooter .navbar-collapse {
  position: fixed;
  bottom: 100px;
}
/* 1000px because this is the point where toggle disappears */
@media (min-width: 1000px) {
  .CustomFooter .navbar-collapse {
    position: relative;
    bottom: 0px;
  }
}
</code>```

So it's get the impression of collapsing upwards

Body:
I'm experimentating react bootstrap.

With the component Navbar.Collapse, to expand a NavDropdown upwards, i found this property drop="up"

<Navbar>
  <Navbar.Toggle aria-controls="basic-navbar-nav"/>
  <Navbar.Collapse id="responsive-navbar-nav">

         <NavDropdown drop="up"
              title="Changer la police"
              id="basic-nav-nav"
               onSelect={changeFont} >
                  <NavDropdown.Item
                    className={font.name}
                    eventKey={font.name}>
                    {font.name}
                  </NavDropdown.Item>
        </NavDropdown>

   </Navbar.Collapse>
</Navbar>

But i didn't find the equivalent for Navbar.Toggle, to as well expand upwards instead of downwards.

Thank you

Body:
I found a solution,

I added this code to the css :

.CustomFooter .navbar-collapse {
  position: fixed;
  bottom: 100px;
}
/* 1000px because this is the point where toggle disappears */
@media (min-width: 1000px) {
  .CustomFooter .navbar-collapse {
    position: relative;
    bottom: 0px;
  }
}

So it's get the impression of collapsing upwards


问:
Split row into multiple rows to limit length of array in column (spark / scala)
I have a dataframe that looks like this:

+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, .... x, y, z]|
+--------------+--------------------+
|             1|[q, z, .... x, b, 5]|
+--------------+--------------------+
|             2|[q, z, .... x, b, 5]|
+--------------+--------------------+
```
<p>I want to split the rows so that the array in the <code>items</code> column is at most length 20. If an array has length greater than 20, I would want to make new rows and split the array up so that each array is of length 20 or less. So for the first row in my example dataframe, if we assume the length is 10 and I want at most length 3 for each row, I would like for it to be split like this:</p>
<pre class="lang-none prettyprint-override"><code>+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, c]           |
+--------------+--------------------+
|             1|[z, y, z]           |
+--------------+--------------------+
|             1|[e, f, g]           |
+--------------+--------------------+
|             1|[q]                 |
+--------------+--------------------+
</code>```

Ideally, all rows should be of length 3 except the last row if the length of the array is not evenly divisible by the max desired length. Note - the id column is not unique

答:
Since this requires a more complex transformation, I've used datasets. This might not be as performant, but it will get what you want.

Setup

Creating some sample data to mimic your data.

val arrayData = Seq(
  Row(1,List(1, 2, 3, 4, 5, 6, 7)),
  Row(2,List(1, 2, 3, 4)),
  Row(3,List(1, 2)),
  Row(4,List(1, 2, 3))
)

val arraySchema = new StructType().add("id",IntegerType).add("values", ArrayType(IntegerType))

val df = spark.createDataFrame(spark.sparkContext.parallelize(arrayData), arraySchema)
/*
 +---+---------------------+
 |id |values               |
 +---+---------------------+
 |1  |[1, 2, 3, 4, 5, 6, 7]|
 |2  |[1, 2, 3, 4]         |
 |3  |[1, 2]               |
 |4  |[1, 2, 3]            |
 +---+---------------------+
*/

```
<h4>Transformations</h4>
<pre class="lang-scala prettyprint-override"><code>// encoder for custom type of transformation
implicit val encoder = ExpressionEncoder[(Int, Array[Array[Int]])]

// Here we are using a sliding window of size 3 and step 3.
// This can be made into a generic function for a window of size k.
val df2 = df.map(r => {
  val id = r.getInt(0)
  val a = r.getSeq[Int](1).toArray
  val arrays = a.sliding(3, 3).toArray
  (id, arrays)
})
/*
 +---+---------------------------------------------------------------+
 |_1 |_2                                                             |
 +---+---------------------------------------------------------------+
 |1  |[WrappedArray(1, 2, 3), WrappedArray(4, 5, 6), WrappedArray(7)]|
 |2  |[WrappedArray(1, 2, 3), WrappedArray(4)]                       |
 |3  |[WrappedArray(1, 2)]                                           |
 |4  |[WrappedArray(1, 2, 3)]                                        |
 +---+---------------------------------------------------------------+
*/

val df3 = df2
  .withColumnRenamed("_1", "id")
  .withColumnRenamed("_2", "values")
/*
 +---+---------------------------------------------------------------+
 |id |values                                                         |
 +---+---------------------------------------------------------------+
 |1  |[WrappedArray(1, 2, 3), WrappedArray(4, 5, 6), WrappedArray(7)]|
 |2  |[WrappedArray(1, 2, 3), WrappedArray(4)]                       |
 |3  |[WrappedArray(1, 2)]                                           |
 |4  |[WrappedArray(1, 2, 3)]                                        |
 +---+---------------------------------------------------------------+
*/

</code>```

Use explode

Expode will create a new element for each array entry in the second column.

val df4 = df3.withColumn("values", functions.explode($"values"))
/*
 +---+---------+
 |id |values   |
 +---+---------+
 |1  |[1, 2, 3]|
 |1  |[4, 5, 6]|
 |1  |[7]      |
 |2  |[1, 2, 3]|
 |2  |[4]      |
 |3  |[1, 2]   |
 |4  |[1, 2, 3]|
 +---+---------+
*/

```

Limitations

This approach is not without limitations.

Primarily, it will not be as performant on larger datasets since this code is no longer using dataframe built-in optimizations. However, the dataframe API might require the use of window functions, which can also have limited performance based on the size of the data. If it's possible to alter this data at the source, this would be recommended.

This approach also requires defining an encoder for something more complex. If the data schema changes, then different encoders will have to be used.

Body:
I have a dataframe that looks like this:

+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, .... x, y, z]|
+--------------+--------------------+
|             1|[q, z, .... x, b, 5]|
+--------------+--------------------+
|             2|[q, z, .... x, b, 5]|
+--------------+--------------------+

I want to split the rows so that the array in the items column is at most length 20. If an array has length greater than 20, I would want to make new rows and split the array up so that each array is of length 20 or less. So for the first row in my example dataframe, if we assume the length is 10 and I want at most length 3 for each row, I would like for it to be split like this:

+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, c]           |
+--------------+--------------------+
|             1|[z, y, z]           |
+--------------+--------------------+
|             1|[e, f, g]           |
+--------------+--------------------+
|             1|[q]                 |
+--------------+--------------------+

Ideally, all rows should be of length 3 except the last row if the length of the array is not evenly divisible by the max desired length. Note - the id column is not unique

Body:
Since this requires a more complex transformation, I've used datasets. This might not be as performant, but it will get what you want.

Setup

Creating some sample data to mimic your data.

val arrayData = Seq(
  Row(1,List(1, 2, 3, 4, 5, 6, 7)),
  Row(2,List(1, 2, 3, 4)),
  Row(3,List(1, 2)),
  Row(4,List(1, 2, 3))
)

val arraySchema = new StructType().add("id",IntegerType).add("values", ArrayType(IntegerType))

val df = spark.createDataFrame(spark.sparkContext.parallelize(arrayData), arraySchema)
/*
 +---+---------------------+
 |id |values               |
 +---+---------------------+
 |1  |[1, 2, 3, 4, 5, 6, 7]|
 |2  |[1, 2, 3, 4]         |
 |3  |[1, 2]               |
 |4  |[1, 2, 3]            |
 +---+---------------------+
*/

Transformations

// encoder for custom type of transformation
implicit val encoder = ExpressionEncoder[(Int, Array[Array[Int]])]

// Here we are using a sliding window of size 3 and step 3.
// This can be made into a generic function for a window of size k.
val df2 = df.map(r => {
  val id = r.getInt(0)
  val a = r.getSeq[Int](1).toArray
  val arrays = a.sliding(3, 3).toArray
  (id, arrays)
})
/*
 +---+---------------------------------------------------------------+
 |_1 |_2                                                             |
 +---+---------------------------------------------------------------+
 |1  |[WrappedArray(1, 2, 3), WrappedArray(4, 5, 6), WrappedArray(7)]|
 |2  |[WrappedArray(1, 2, 3), WrappedArray(4)]                       |
 |3  |[WrappedArray(1, 2)]                                           |
 |4  |[WrappedArray(1, 2, 3)]                                        |
 +---+---------------------------------------------------------------+
*/

val df3 = df2
  .withColumnRenamed("_1", "id")
  .withColumnRenamed("_2", "values")
/*
 +---+---------------------------------------------------------------+
 |id |values                                                         |
 +---+---------------------------------------------------------------+
 |1  |[WrappedArray(1, 2, 3), WrappedArray(4, 5, 6), WrappedArray(7)]|
 |2  |[WrappedArray(1, 2, 3), WrappedArray(4)]                       |
 |3  |[WrappedArray(1, 2)]                                           |
 |4  |[WrappedArray(1, 2, 3)]                                        |
 +---+---------------------------------------------------------------+
*/

Use explode

Expode will create a new element for each array entry in the second column.

val df4 = df3.withColumn("values", functions.explode($"values"))
/*
 +---+---------+
 |id |values   |
 +---+---------+
 |1  |[1, 2, 3]|
 |1  |[4, 5, 6]|
 |1  |[7]      |
 |2  |[1, 2, 3]|
 |2  |[4]      |
 |3  |[1, 2]   |
 |4  |[1, 2, 3]|
 +---+---------+
*/

Limitations

This approach is not without limitations.

Primarily, it will not be as performant on larger datasets since this code is no longer using dataframe built-in optimizations. However, the dataframe API might require the use of window functions, which can also have limited performance based on the size of the data. If it's possible to alter this data at the source, this would be recommended.

This approach also requires defining an encoder for something more complex. If the data schema changes, then different encoders will have to be used.


问:
Improving upon bit masking and shifting function
Can this function be improved upon to make it more efficient?:

```<code>private unsafe uint GetValue(uint value, int bitsToGrab, int bitsToMoveOver)
        {
            byte[] bytes = BitConverter.GetBytes(value);

            uint myBitMask = 0x80;  //MSB of 8 bits (byte)
            int arrayIndex = 0;
            for (int i = 0; i < bitsToMoveOver; i++)
            {
                if (myBitMask == 0)
                {
                    arrayIndex++;
                    myBitMask = 0x80;
                }

                myBitMask >>= 1;
            }

            uint outputMask1 = (uint)(1 << (bitsToGrab - 1));
            uint returnVal = 0;
            for (int i = 0; i < bitsToGrab; i++)
            {
                if (myBitMask == 0)
                {
                    arrayIndex++;
                    myBitMask = 0x80;
                }

                if ((bytes[arrayIndex] & myBitMask) > 0)
                {
                    returnVal |= outputMask1;
                }

                outputMask1 >>= 1;
                myBitMask >>= 1;
            }

            return returnVal;
        }
</code>```

i have an array of uints.  each uint contains multiple pieces of data.  In order to get the information, i pass in the number of bits, and the offset of those bits.  Using that information, i build an output value.
The offset is generally on a byte boundary, but i cannot guarantee that it will be.

I'm actually really looking to see if i can simplify the code.  Am i unnecessarily verbose in the code, or could it be done a bit cleaner?

Updated function:  How do you guys feel about this?

```<code>private unsafe uint GetValue(uint value, int bitsToGrab, int bitsToMoveOver)
        {
            if (bitsToGrab + bitsToMoveOver >= 32)
            {
                return 0;
            }

            byte[] bytes = BitConverter.GetBytes(value);
            Array.Reverse(bytes);
            uint newValue = BitConverter.ToUInt32(bytes, 0);

            uint grabMask = (0xFFFFFFFF << (32 - bitsToGrab));
            grabMask >>= bitsToMoveOver;

            uint returnVal = (newValue & grabMask) >> (32 - bitsToMoveOver - bitsToGrab);
            return returnVal;
}
</code>```

答:
This needs testing (and assumes that bitsToGrab + bitsToMoveOver <= 32), but I think you can do this:

```<code>uint grabMask = ~(0xFFFFFFFF << (bitsToGrab + bitsToMoveOver));
return (value & grabMask) >> bitsToMoveOver;
</code>```

Since the OP has indicated that it should be sampling bits from an internal binary representation of the number (including endian encoding), with byte order swapping within each word, you can swap bytes first like this:

```<code>uint reorderedValue = ((value << 8) & 0xFF00FF00) | ((value >> 8) & 0x00FF00FF);
uint grabMask = ~(0xFFFFFFFF << (bitsToGrab + bitsToMoveOver));
return (reorderedValue & grabMask) >> bitsToMoveOver;
</code>```

Body:
Can this function be improved upon to make it more efficient?:

private unsafe uint GetValue(uint value, int bitsToGrab, int bitsToMoveOver)
        {
            byte[] bytes = BitConverter.GetBytes(value);

            uint myBitMask = 0x80;  //MSB of 8 bits (byte)
            int arrayIndex = 0;
            for (int i = 0; i < bitsToMoveOver; i++)
            {
                if (myBitMask == 0)
                {
                    arrayIndex++;
                    myBitMask = 0x80;
                }

                myBitMask >>= 1;
            }

            uint outputMask1 = (uint)(1 << (bitsToGrab - 1));
            uint returnVal = 0;
            for (int i = 0; i < bitsToGrab; i++)
            {
                if (myBitMask == 0)
                {
                    arrayIndex++;
                    myBitMask = 0x80;
                }

                if ((bytes[arrayIndex] & myBitMask) > 0)
                {
                    returnVal |= outputMask1;
                }

                outputMask1 >>= 1;
                myBitMask >>= 1;
            }

            return returnVal;
        }

i have an array of uints.  each uint contains multiple pieces of data.  In order to get the information, i pass in the number of bits, and the offset of those bits.  Using that information, i build an output value.
The offset is generally on a byte boundary, but i cannot guarantee that it will be.

I'm actually really looking to see if i can simplify the code.  Am i unnecessarily verbose in the code, or could it be done a bit cleaner?

Updated function:  How do you guys feel about this?

private unsafe uint GetValue(uint value, int bitsToGrab, int bitsToMoveOver)
        {
            if (bitsToGrab + bitsToMoveOver >= 32)
            {
                return 0;
            }

            byte[] bytes = BitConverter.GetBytes(value);
            Array.Reverse(bytes);
            uint newValue = BitConverter.ToUInt32(bytes, 0);

            uint grabMask = (0xFFFFFFFF << (32 - bitsToGrab));
            grabMask >>= bitsToMoveOver;

            uint returnVal = (newValue & grabMask) >> (32 - bitsToMoveOver - bitsToGrab);
            return returnVal;
}

Body:
This needs testing (and assumes that bitsToGrab + bitsToMoveOver <= 32), but I think you can do this:

uint grabMask = ~(0xFFFFFFFF << (bitsToGrab + bitsToMoveOver));
return (value & grabMask) >> bitsToMoveOver;

Since the OP has indicated that it should be sampling bits from an internal binary representation of the number (including endian encoding), with byte order swapping within each word, you can swap bytes first like this:

uint reorderedValue = ((value << 8) & 0xFF00FF00) | ((value >> 8) & 0x00FF00FF);
uint grabMask = ~(0xFFFFFFFF << (bitsToGrab + bitsToMoveOver));
return (reorderedValue & grabMask) >> bitsToMoveOver;


问:
using same variable that is created in function into another function
I want to use 'number' variable that was created out of the function and use it in  couple functions and also give it an initial value 0, but it gives "local variable 'number' referenced before assignment" error at the last line of code.How could I fix it?Thanks in advance.</p>
```<code>lst_img=[img0,img1,img2,img3,img4]
number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment
</code>```

答: The problem is that you are using the number variable as global variable.</p>

Body:
I want to use 'number' variable that was created out of the function and use it in  couple functions and also give it an initial value 0, but it gives "local variable 'number' referenced before assignment" error at the last line of code.How could I fix it?Thanks in advance.

lst_img=[img0,img1,img2,img3,img4]
number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment


问:
trying to understand async / await / sync in node
i know this probably has been asked before, but coming from single-threaded language for the past 20 years, i am really struggling to grasp the true nature of node. believe me, i have read a bunch of SO posts, github discussions, and articles about this.

i think i understand that each function has it's own thread type of deal. however, there are some cases where i want my code to be fully synchronous (fire one function after the other).

for example, i made 3 functions which seem to show me how node's async i/o works:

function sleepA() {
    setTimeout(() => {
        console.log('sleep A')
    }, 3000)
}

function sleepB() {
    setTimeout(() => {
        console.log('sleep B')
    }, 2000)
}

function sleepC() {
    setTimeout(() => {
        console.log('sleep C')
    }, 1000)
}

sleepA()
sleepB()
sleepC()
```
<p>this outputs the following:</p>
```sleep C
sleep B
sleep A
```

ok so that makes sense. node is firing all of the functions at the same time, and whichever ones complete first get logged to the console. kind of like watching horses race. node fires a gun and the functions take off, and the fastest one wins.

so now how would i go about making these synchronous so that the order is always A, B, C, regardless of the setTimeout number?

i've dabbled with things like bluebird and the util node library and am still kind of confused. i think this async logic is insanely powerful despite my inability to truly grasp it. php has destroyed my mind.

答:
how would i go about making these synchronous so that the order is always A, B, C

You've confirmed that what you mean by that is that you don't want to start the timeout for B until A has finished (etc.).

Here in 2021, the easiest way to do that is to use a promise-enabled wrapper for setTimeout, like this one:

```<code>const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
</code>```

Then, make sleepA and such async functions:

```<code>async function sleepA() {
    await delay(3000);
    console.log("sleep A");
}

async function sleepB() {
    await delay(2000);
    console.log("sleep B");
}

async function sleepC() {
    await delay(1000);
    console.log("sleep C");
}
</code>```

Then your code can await the promise each of those functions returns, which prevents the code from continuing until the promise is settled:

```<code>await sleepA();
await sleepB();
await sleepC();
</code>```

You can do that inside an async function or (in modern versions of Node.js) at the top level of a module. You can't use await in a synchronous function, since await is asynchronous by nature.

i think i understand that each function has it's own thread type of deal

No, JavaScript functions are just like those of other synchronous languages (despite its reputation, JavaScript itself is overwhelmingly synchronous; it's just used in highly-asynchronous environments and recently got some features to make that easier). More on this below.

ok so that makes sense. node is firing all of the functions at the same time, and whichever ones complete first get logged to the console. kind of like watching horses race. node fires a gun and the functions take off, and the fastest one wins.

Close. The functions run in order, but all that each of them does is set up a timer and return. They don't wait for the timer to fire. Later, when it does fire, it calls the callback you passed into setTimeout.

JavaScript has a main thread and everything runs on that main thread unless you explicitly make it run on a worker thread or in a child process. Node.js is highly asynchronous (as are web browsers, the other place JavaScript is mostly used), but your JavaScript code all runs on one thread by default. There's a loop that processes "jobs." Jobs get queued by events (such as a timer firing), and then processed in order by the event loop. I go into a bit more on it here, and the Node.js documentation covers their loop here (I think it's slightly out of date, but the principal hasn't changed).

Body:
i know this probably has been asked before, but coming from single-threaded language for the past 20 years, i am really struggling to grasp the true nature of node. believe me, i have read a bunch of SO posts, github discussions, and articles about this.

i think i understand that each function has it's own thread type of deal. however, there are some cases where i want my code to be fully synchronous (fire one function after the other).

for example, i made 3 functions which seem to show me how node's async i/o works:

function sleepA() {
    setTimeout(() => {
        console.log('sleep A')
    }, 3000)
}

function sleepB() {
    setTimeout(() => {
        console.log('sleep B')
    }, 2000)
}

function sleepC() {
    setTimeout(() => {
        console.log('sleep C')
    }, 1000)
}

sleepA()
sleepB()
sleepC()

this outputs the following:

sleep C
sleep B
sleep A

ok so that makes sense. node is firing all of the functions at the same time, and whichever ones complete first get logged to the console. kind of like watching horses race. node fires a gun and the functions take off, and the fastest one wins.

so now how would i go about making these synchronous so that the order is always A, B, C, regardless of the setTimeout number?

i've dabbled with things like bluebird and the util node library and am still kind of confused. i think this async logic is insanely powerful despite my inability to truly grasp it. php has destroyed my mind.

Body:
how would i go about making these synchronous so that the order is always A, B, C

You've confirmed that what you mean by that is that you don't want to start the timeout for B until A has finished (etc.).

Here in 2021, the easiest way to do that is to use a promise-enabled wrapper for setTimeout, like this one:

const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

Then, make sleepA and such async functions:

async function sleepA() {
    await delay(3000);
    console.log("sleep A");
}

async function sleepB() {
    await delay(2000);
    console.log("sleep B");
}

async function sleepC() {
    await delay(1000);
    console.log("sleep C");
}

Then your code can await the promise each of those functions returns, which prevents the code from continuing until the promise is settled:

await sleepA();
await sleepB();
await sleepC();

You can do that inside an async function or (in modern versions of Node.js) at the top level of a module. You can't use await in a synchronous function, since await is asynchronous by nature.

i think i understand that each function has it's own thread type of deal

No, JavaScript functions are just like those of other synchronous languages (despite its reputation, JavaScript itself is overwhelmingly synchronous; it's just used in highly-asynchronous environments and recently got some features to make that easier). More on this below.

ok so that makes sense. node is firing all of the functions at the same time, and whichever ones complete first get logged to the console. kind of like watching horses race. node fires a gun and the functions take off, and the fastest one wins.

Close. The functions run in order, but all that each of them does is set up a timer and return. They don't wait for the timer to fire. Later, when it does fire, it calls the callback you passed into setTimeout.

JavaScript has a main thread and everything runs on that main thread unless you explicitly make it run on a worker thread or in a child process. Node.js is highly asynchronous (as are web browsers, the other place JavaScript is mostly used), but your JavaScript code all runs on one thread by default. There's a loop that processes "jobs." Jobs get queued by events (such as a timer firing), and then processed in order by the event loop. I go into a bit more on it here, and the Node.js documentation covers their loop here (I think it's slightly out of date, but the principal hasn't changed).


问:
Insertion of legends for images embedded in Capella description
M2doc already provides several services on the descriptions of Capella elements. For example substitutions of hypertext links, autosize of images, etc.

I need to be able to insert legends under each image or table coming with a Capella description. I believe this would require the development of a specific service, but I would like to have a first feedback on the feasibility.

One of the difficulty I see is the following one: I am thinking for example that for such legends to appear in a consolidated table of figures at the end of the generated document, the legends would need to have a specific style. Would a Java M2Doc service be able to take a style as a parameter?

Thank you very much,

Stéphane

答:
You can apply an existing style to a text or a table with the asStyle() service. You can apply the style in a comment block to make sure it's present in the template. You can also use availableTextStyles() and availableTableStyles() on any object to get the list of available styles in your template.

But for what you want to do, you will need to create a service that works on a List of MElement and find and change the style of wanted MText elements. You might also need to create new MText to get sub parts of existing MText. Then you can creat a MParagraph containing the wanted MText with the wanted style ID:

```<code>new MParagraphImpl(new MTextImpl(text, null), styleID)
</code>```

I'm not sure it will be enough to have the numbering working since it might not be included in the style itself. For the numbering, you can use the availableNumberingIDs() service on any object to get a list of available numbering IDs in your template. you can the use the setNumbering() on a MParagraph to set the numbering and level. Programmatically, you can use:

```<code>paragraph.setNumberingID(Long.valueOf(numberingID));
paragraph.setNumberingLevel(Long.valueOf(level));
</code>```

Body:
You can apply an existing style to a text or a table with the asStyle() service. You can apply the style in a comment block to make sure it's present in the template. You can also use availableTextStyles() and availableTableStyles() on any object to get the list of available styles in your template.

But for what you want to do, you will need to create a service that works on a List of MElement and find and change the style of wanted MText elements. You might also need to create new MText to get sub parts of existing MText. Then you can creat a MParagraph containing the wanted MText with the wanted style ID:

new MParagraphImpl(new MTextImpl(text, null), styleID)

I'm not sure it will be enough to have the numbering working since it might not be included in the style itself. For the numbering, you can use the availableNumberingIDs() service on any object to get a list of available numbering IDs in your template. you can the use the setNumbering() on a MParagraph to set the numbering and level. Programmatically, you can use:

paragraph.setNumberingID(Long.valueOf(numberingID));
paragraph.setNumberingLevel(Long.valueOf(level));


问:
Inclue Web Page in livecode
I am new to LiveCode, and I would like to embed a web page in a map. Realize the user then on a button, which opens a map, this map and provided with a back button, and I would like to display a site directly in LiveCode. How can I do, so that we see on the whole map (or almost) the site? do you need a particular widget?</p>

答:
I don't understand your question completely, but there is a web browser widget that you can drag onto the card. It is in the Tools palette and looks like a world globe. You drag it onto the card then set its URL property:</p>
```<code>set the URL of widget "myBrowser" to "https://livecode.com"
</code>```

Title: Inclue Web Page in livecode

Body:
I don't understand your question completely, but there is a web browser widget that you can drag onto the card. It is in the Tools palette and looks like a world globe. You drag it onto the card then set its URL property:

set the URL of widget "myBrowser" to "https://livecode.com"


问:
Parent Child Relationship in SQL Server 2019
I have a table that stores relationships like this:

```<code>ParentName ParentID ChildName ChildId
-------------------------------------
Name1      Guid     NameA      Guid
Name2      Guid     NameB      Guid
Name3      Guid     NameC      Guid
NameA      Guid     NameY      Guid
NameB      Guid     NameX      Guid
NameC      Guid     NameZ      Guid
NameY      Guid     Name1A     Guid
</code>```

My goal is to retrieve data stacked in way that no matter far down the hierarchy, the child columns shows who the top most parent is.

I know it's a recursive CTE, but I don't know how to write the recursive join in the query back to the anchor without breaking the max number of recursion. Parent query has 78 records using a WHERE clause, but total levels shouldn't be more than 4 or 5. The parent can have multiple children.

答:
The below query should work. Although it is subjected to maximum recursion permitted by database which is 100 by default in case of SQL server. So it should work till that many level of nested Parent-Child relationship.

```<code>WITH RECURSIVE cte AS (
    SELECT ChildID,ChildName,ParentID,ParentName, 1 AS Level FROM parents

    UNION ALL

    SELECT cte.ChildID,
        cte.ChildName,
        GrandParent.ParentID,
        GrandParent.ParentName,
        Level+1
    FROM cte
    INNER JOIN parents AS GrandParent
    ON cte.ParentID=GrandParent.ChildID
)
SELECT ChildID,ChildName,ParentID,ParentName
FROM(
    SELECT cte.*,
        ROW_NUMBER() OVER(PARTITION BY ChildID,ChildName ORDER BY Level DESC) AS rnk
    FROM cte
) Rank_Highest_Level
WHERE rnk=1
ORDER BY ChildID;
</code>```

Here is a working example in DB Fiddle.

Body:
I have a table that stores relationships like this:

ParentName ParentID ChildName ChildId
-------------------------------------
Name1      Guid     NameA      Guid
Name2      Guid     NameB      Guid
Name3      Guid     NameC      Guid
NameA      Guid     NameY      Guid
NameB      Guid     NameX      Guid
NameC      Guid     NameZ      Guid
NameY      Guid     Name1A     Guid

My goal is to retrieve data stacked in way that no matter far down the hierarchy, the child columns shows who the top most parent is.

I know it's a recursive CTE, but I don't know how to write the recursive join in the query back to the anchor without breaking the max number of recursion. Parent query has 78 records using a WHERE clause, but total levels shouldn't be more than 4 or 5. The parent can have multiple children.

Body:
The below query should work. Although it is subjected to maximum recursion permitted by database which is 100 by default in case of SQL server. So it should work till that many level of nested Parent-Child relationship.

WITH RECURSIVE cte AS (
    SELECT ChildID,ChildName,ParentID,ParentName, 1 AS Level FROM parents

    UNION ALL

    SELECT cte.ChildID,
        cte.ChildName,
        GrandParent.ParentID,
        GrandParent.ParentName,
        Level+1
    FROM cte
    INNER JOIN parents AS GrandParent
    ON cte.ParentID=GrandParent.ChildID
)
SELECT ChildID,ChildName,ParentID,ParentName
FROM(
    SELECT cte.*,
        ROW_NUMBER() OVER(PARTITION BY ChildID,ChildName ORDER BY Level DESC) AS rnk
    FROM cte
) Rank_Highest_Level
WHERE rnk=1
ORDER BY ChildID;

Here is a working example in DB Fiddle.


问:
What is the fastest way in C# to find a pattern in a group of files?
```<code>using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace regex
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      Regex exp = new Regex(@"e(-)?m[a@]il(s)?|input|output|padr(ão|ões)|máquina(s)?|reconhecimento",
                            RegexOptions.IgnoreCase | RegexOptions.Compiled |
                            RegexOptions.Multiline  | RegexOptions.ExplicitCapture);

      for (int filecount = 0 ; filecount < 22 ; filecount++)
      {
        string file = "/home/files/file"+ string.Format("{0:0#}",filecount) + ".txt";
        StreamReader reader = new StreamReader(file);

        string text = reader.ReadToEnd();
        int c=0;

        MatchCollection matchList = exp.Matches(text);
        c = matchList.Count;

        Console.WriteLine("Reading " + file + " -> " + c + " matches");
      }
    }
  }
}
</code>```

If I comment out the line

```<code>c = matchList.Count;
</code>```

it is pretty fast. But I need to know the number of matches it has found.

Is this the fastest way to do this? For the group of files I have, it's taking me 14 seconds to parse every file. Perl takes 1 second to output exactly the same information.

PS: Each file (text file) has +/- 1Mb so it's ~20Mb to process.

Thanks ;)

答: You could use BackgroundWorker to parallelize the searching of the files.  You will have to keep track of the count and aggregate it at the end.  You could have a BGWorker per file or per a group of files.  4.0 Framework will ease this code as it has parallel data structures.</p>

OwnerDisplayName: Ricardo Mestre

ContentLicense: CC BY-SA 2.5

Body:
using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace regex
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      Regex exp = new Regex(@"e(-)?m[a@]il(s)?|input|output|padr(ão|ões)|máquina(s)?|reconhecimento",
                            RegexOptions.IgnoreCase | RegexOptions.Compiled |
                            RegexOptions.Multiline  | RegexOptions.ExplicitCapture);

      for (int filecount = 0 ; filecount < 22 ; filecount++)
      {
        string file = "/home/files/file"+ string.Format("{0:0#}",filecount) + ".txt";
        StreamReader reader = new StreamReader(file);

        string text = reader.ReadToEnd();
        int c=0;

        MatchCollection matchList = exp.Matches(text);
        c = matchList.Count;

        Console.WriteLine("Reading " + file + " -> " + c + " matches");
      }
    }
  }
}

If I comment out the line

c = matchList.Count;

it is pretty fast. But I need to know the number of matches it has found.

Is this the fastest way to do this? For the group of files I have, it's taking me 14 seconds to parse every file. Perl takes 1 second to output exactly the same information.

PS: Each file (text file) has +/- 1Mb so it's ~20Mb to process.

Thanks ;)

LastEditorDisplayName: Alan M

OwnerDisplayName: foosnazzy


问:
bitmap size exceeds VM budget Error on Android
I'm loading 100 images from Asset folder to an array object. The pictures are quite small (png ~20k each), and im using this code do to it, and to prevent memory leak & optimized performances:

in a loop:

```<code>// create resized bitmap from asset resource
        InputStream istr = assetManager.open(pics[i]);
        Bitmap b = BitmapFactory.decodeStream(istr);
        b = Bitmap.createScaledBitmap(b, 240, 240, true);
</code>```

where pics[i] is a list of filenames which sits in my Asset folder.

The code works for me, but i still receive from time to time Errors from users (i see it on Developer Console errors):

```<code>java.lang.OutOfMemoryError: bitmap size exceeds VM budget
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:468)
at android.graphics.Bitmap.createBitmap(Bitmap.java:435)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:340)
</code>```

Is there anything i can do to improve it? or this is Android's world, we can never deliever a perfect application?

答:
Of course you can improve something: Don't load too much pictures into the memory at the same time (or reduce their size). Some devices don't have much memory available. Your device may have a higher heap limit than some of your customers phones. Therefore it crashes for them when it works for you (see this video for some heap limits [at 4:44]).

You may get the available heap size via ActivityManager.getMemoryClass().

To improve this, test which pictures you need right now (which are displayed) and are which not. Load only the required ones and recycle the bitmaps you don't need anymore.

Also try using the BitmapFactory.decodeResource() and BitmapFactory.Options.inSampleSize. This allows you to load images at a lower resolution directly without loading them at the full size and then resizing them as you did here.

Body:
I'm loading 100 images from Asset folder to an array object. The pictures are quite small (png ~20k each), and im using this code do to it, and to prevent memory leak & optimized performances:

in a loop:

// create resized bitmap from asset resource
        InputStream istr = assetManager.open(pics[i]);
        Bitmap b = BitmapFactory.decodeStream(istr);
        b = Bitmap.createScaledBitmap(b, 240, 240, true);

where pics[i] is a list of filenames which sits in my Asset folder.

The code works for me, but i still receive from time to time Errors from users (i see it on Developer Console errors):

java.lang.OutOfMemoryError: bitmap size exceeds VM budget
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:468)
at android.graphics.Bitmap.createBitmap(Bitmap.java:435)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:340)

Is there anything i can do to improve it? or this is Android's world, we can never deliever a perfect application?


问:
Pagination with Grails/GORM/DataServices @Query annotation
How do you add pagination when using GORM JPA-QL Queries via the grails.gorm.services.Query annotation

```<code>@Service(User)
abstract class UserDataService implements IUserService {

    @Query($/SELECT DISTINCT new Map(user.id as id, user.username as username)
             FROM $User user
              join $UserRelationship ur on ur.user.id = user.id or ur.manager.id = user.id
              join ur.manager manager
           /$)
   abstract List<Map> searchAllUsers(String searchString, [offset: 0, max: 10])

}
</code>```

答:
you can pass Map args in the method like listWithQuery and listWithQuery2, args would need to look like [offset: (rows to offset) , max: (limit of rows to return)]</p>
```<code>@Service(User)
interface IUserService {

    List<User> findAll()

    List<User> list(Map args)

    @Query("from ${User user} where ${user.lastName} like '%halp%'")
    List<User> listWithQuery(Map args)

    @Query("from ${User} user where user.lastName like $nameLike")
    List<User> listWithQuery2(String nameLike, Map args)
}
</code>```

Body:
How do you add pagination when using GORM JPA-QL Queries via the grails.gorm.services.Query annotation

@Service(User)
abstract class UserDataService implements IUserService {

    @Query($/SELECT DISTINCT new Map(user.id as id, user.username as username)
             FROM $User user
              join $UserRelationship ur on ur.user.id = user.id or ur.manager.id = user.id
              join ur.manager manager
           /$)
   abstract List<Map> searchAllUsers(String searchString, [offset: 0, max: 10])

}

Body:
you can pass Map args in the method like listWithQuery and listWithQuery2, args would need to look like [offset: (rows to offset) , max: (limit of rows to return)]

@Service(User)
interface IUserService {

    List<User> findAll()

    List<User> list(Map args)

    @Query("from ${User user} where ${user.lastName} like '%halp%'")
    List<User> listWithQuery(Map args)

    @Query("from ${User} user where user.lastName like $nameLike")
    List<User> listWithQuery2(String nameLike, Map args)
}


问:
python PyGObject :how to save clipboard as image
I have a snapshot tool in linux, i copied the image there into clipboard

now i want to save. I am not able to understand how to complete the steps. I wrote what i can understand till

I want to do it using pyObject

```<code>import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
</code>```

after this how to save image to  /home/user/filename.png

答:
As discussed in this post on SO, the call to Gtk.Clipboard.get() requires an argument to identify the clipboard. Therefore, to get an image from the clipboard, you'd have to call wait_for_image(). This will return a pixbuf object.

In order to save this pixbuf object as a .png to disk, you could convert it to a Pillow image object using the pixbuf2image(pix) function that was taken from this GitHub Gist from user mozbugbox. The Pillow image object then has a save() method to save the image directly to disk.

import gi
from PIL import Image as PILImage
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk

def pixbuf2image(pix):
    """Convert gdkpixbuf to PIL image"""
    data = pix.get_pixels()
    w = pix.props.width
    h = pix.props.height
    stride = pix.props.rowstride
    mode = "RGB"
    if pix.props.has_alpha == True:
        mode = "RGBA"
    im = PILImage.frombytes(mode, (w, h), data, "raw", mode, stride)
    return im

clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)

pixbuf_img = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).wait_for_image()
pil_image = pixbuf2image(pixbuf_img)
pil_image.save(str(imgpath))
```

Body:
I have a snapshot tool in linux, i copied the image there into clipboard

now i want to save. I am not able to understand how to complete the steps. I wrote what i can understand till

I want to do it using pyObject

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)

after this how to save image to  /home/user/filename.png


问:
MongoDB nested object aggregation counting
I have a highly nested mongoDB set of objects and I want to count the number of subdocuments that match a given condition Edit: (in each document).  For example:

```<code>{"_id":{"chr":"20","pos":"14371","ref":"A","alt":"G"},
"studies":[
    {
        "study_id":"Study1",
        "samples":[
            {
                "sample_id":"NA00001",
                "formatdata":[
                    {"GT":"1|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            },
            {
                "sample_id":"NA00002",
                "formatdata":[
                    {"GT":"0|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            }
        ]
    }
]
}
{"_id":{"chr":"20","pos":"14372","ref":"T","alt":"AA"},
"studies":[
    {
        "study_id":"Study3",
        "samples":[
            {
                "sample_id":"SAMPLE1",
                "formatdata":[
                    {"GT":"1|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            },
            {
                "sample_id":"SAMPLE2",
                "formatdata":[
                    {"GT":"1|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            }
        ]
    }
]
}
{"_id":{"chr":"20","pos":"14373","ref":"C","alt":"A"},
"studies":[
    {
        "study_id":"Study3",
        "samples":[
            {
                "sample_id":"SAMPLE3",
                "formatdata":[
                    {"GT":"0|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            },
            {
                "sample_id":"SAMPLE7",
                "formatdata":[
                    {"GT":"0|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            }
        ]
    }
]
}
</code>```

I want to know how many subdocuments contain GT:"1|0", which in this case would be 1 in the first document, and two in the second, and 0 in the 3rd.  I've tried the unwind and aggregate functions but I'm obviously not doing something correct.  When I try to count the sub documents by the "GT" field, mongo complains:

```<code>db.collection.aggregate([{$group: {"$studies.samples.formatdata.GT":1,_id:0}}])
</code>```

since my group's names cannot contain ".", yet if I leave them out:

```<code>db.collection.aggregate([{$group: {"$GT":1,_id:0}}])
</code>```

it complains because "$GT cannot be an operator name"

Any ideas?

答:
https://mongoplayground.net/p/DpX6cFhR_mm</p>
```<code>db.collection.aggregate([
  {
    "$unwind": "$tags"
  },
  {
    "$match": {
      "$or": [
        {
          "tags.name": "Canada"
        },
        {
          "tags.name": "ABC"
        }
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": 1
      }
    }
  }
])
</code>```

Body:
I have a highly nested mongoDB set of objects and I want to count the number of subdocuments that match a given condition Edit: (in each document).  For example:

{"_id":{"chr":"20","pos":"14371","ref":"A","alt":"G"},
"studies":[
    {
        "study_id":"Study1",
        "samples":[
            {
                "sample_id":"NA00001",
                "formatdata":[
                    {"GT":"1|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            },
            {
                "sample_id":"NA00002",
                "formatdata":[
                    {"GT":"0|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            }
        ]
    }
]
}
{"_id":{"chr":"20","pos":"14372","ref":"T","alt":"AA"},
"studies":[
    {
        "study_id":"Study3",
        "samples":[
            {
                "sample_id":"SAMPLE1",
                "formatdata":[
                    {"GT":"1|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            },
            {
                "sample_id":"SAMPLE2",
                "formatdata":[
                    {"GT":"1|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            }
        ]
    }
]
}
{"_id":{"chr":"20","pos":"14373","ref":"C","alt":"A"},
"studies":[
    {
        "study_id":"Study3",
        "samples":[
            {
                "sample_id":"SAMPLE3",
                "formatdata":[
                    {"GT":"0|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            },
            {
                "sample_id":"SAMPLE7",
                "formatdata":[
                    {"GT":"0|0","GQ":48,"DP":8,"HQ":[51,51]}
                ]
            }
        ]
    }
]
}

I want to know how many subdocuments contain GT:"1|0", which in this case would be 1 in the first document, and two in the second, and 0 in the 3rd.  I've tried the unwind and aggregate functions but I'm obviously not doing something correct.  When I try to count the sub documents by the "GT" field, mongo complains:

db.collection.aggregate([{$group: {"$studies.samples.formatdata.GT":1,_id:0}}])

since my group's names cannot contain ".", yet if I leave them out:

db.collection.aggregate([{$group: {"$GT":1,_id:0}}])

it complains because "$GT cannot be an operator name"

Any ideas?

Body:
https://mongoplayground.net/p/DpX6cFhR_mm

db.collection.aggregate([
  {
    "$unwind": "$tags"
  },
  {
    "$match": {
      "$or": [
        {
          "tags.name": "Canada"
        },
        {
          "tags.name": "ABC"
        }
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": 1
      }
    }
  }
])


问:
No Cucumber tests run in a simplified Spring Boot 5.7+ JDK17 and JUnit 5 environment
Can you help getting this most simple Cucumber test run in a the simplified Spring Boot 2.5, JDK17, JUnit 5 environment? I tried all kinds of solutions without any result.

You can find a minimal github repo in this github project.

The error message is (without executing any tests):

[ERROR] feb. 11, 2022 12:44:05 P.M. org.junit.platform.launcher.core.LauncherConfigurationParameters
loadClasspathResource

[ERROR] INFO: Loading JUnit Platform configuration parameters from classpath resource
[file:/K:/A__IntelliJ_projects/spring-boot-cucumbertests/target/test-classes/junit-platform.properties].

Pom.xml:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.7</version>
    <relativePath/>
</parent>
<groupId>nl.tester.springboot.cucumbertests</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>17</java.version>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-api</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-params</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-engine</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.junit.platform</groupId>
                <artifactId>junit-platform-launcher</artifactId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.2.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit-platform-engine</artifactId>
        <version>7.2.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-suite-api</artifactId>
        <version>1.8.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
        </plugin>
    </plugins>
</build>
</code>```

答:
This is the right list of test packages:</p>
```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.3</version>
    <relativePath/>
</parent>
<groupId>nl.tester.springboot.cucumbertests</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>17</java.version>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-suite</artifactId>
        <version>1.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.2.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit-platform-engine</artifactId>
        <version>7.2.3</version>
        <scope>test</scope>
    </dependency>
</code>```

Body:
Can you help getting this most simple Cucumber test run in a the simplified Spring Boot 2.5, JDK17, JUnit 5 environment? I tried all kinds of solutions without any result.

You can find a minimal github repo in this github project.

The error message is (without executing any tests):

[ERROR] feb. 11, 2022 12:44:05 P.M. org.junit.platform.launcher.core.LauncherConfigurationParameters
loadClasspathResource

[ERROR] INFO: Loading JUnit Platform configuration parameters from classpath resource
[file:/K:/A__IntelliJ_projects/spring-boot-cucumbertests/target/test-classes/junit-platform.properties].

Pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.7</version>
    <relativePath/>
</parent>
<groupId>nl.tester.springboot.cucumbertests</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>17</java.version>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-api</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-params</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-engine</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.junit.platform</groupId>
                <artifactId>junit-platform-launcher</artifactId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.2.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit-platform-engine</artifactId>
        <version>7.2.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-suite-api</artifactId>
        <version>1.8.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
        </plugin>
    </plugins>
</build>

Body:
This is the right list of test packages:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.3</version>
    <relativePath/>
</parent>
<groupId>nl.tester.springboot.cucumbertests</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>17</java.version>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-suite</artifactId>
        <version>1.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.2.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit-platform-engine</artifactId>
        <version>7.2.3</version>
        <scope>test</scope>
    </dependency>


问:
Function empty object check

I need help this task
You have to implement function that will
Check that object is empty.
Object considered to be empty when it has no properties or all its properties are false (I.e. 0, “”, false …)

check object for presence: {},0, “”, symbol(“key”), null, 5,[].

答:
You can use 'Object.Values(obj)' which returns an array of all the values from the key value pairs of the object passed as parameter.

'!Object.Values(obj)' will return false if there are no values, which means this is not an object.

'anArray.every(element => { //return a boolean } )' will loop through all the items of the array and return true only if the the arrow function returns true for all 'every' element on the array

```<code>function isEmpty (obj){
    return !Object.Values(obj) ||
    Object.Values(obj).every (v => !v));

</code>```

Title: Function empty object check

Body:
You can use 'Object.Values(obj)' which returns an array of all the values from the key value pairs of the object passed as parameter.

'!Object.Values(obj)' will return false if there are no values, which means this is not an object.

'anArray.every(element => { //return a boolean } )' will loop through all the items of the array and return true only if the the arrow function returns true for all 'every' element on the array

function isEmpty (obj){
    return !Object.Values(obj) ||
    Object.Values(obj).every (v => !v));


问:
Custom function to loop over a list
I have a working custom function but not sure how to allow it to loop with a list of inputs. Looks like I need to understand apply() and the such but I'm not quite there with my current setup. The function uses rollapply() to find the largest metric for a given time frame.

```<code>library(zoo)
library(dplyr)

# Data
set.seed(1)
df <- tibble(player = rep(LETTERS[1:2], each = 10),
             minute = rep(1:10, times = 2),
             tdc = sample(100:200,size = 20),
             sumad = sample(1:10, size = 20, replace = TRUE))

# Custom function
x_min_roll <- function(df, metric, n_minutes, fun){
  metric <- ensym(metric)
  newname <- glue::glue("{rlang::as_string(metric)}_x{as.character(n_minutes)}")
  df %>%
    # dynamically create new column name based on input
    mutate("{newname}" := rollapply(!!metric, n_minutes, fun, align='left', fill=NA)) %>%
    group_by(player) %>%
    slice_max(.data[[newname]]) %>%
    select(player, .data[[newname]])
}

# This works
df %>%
  x_min_roll(metric = tdc, n_minutes = 2, fun = sum)

# A tibble: 2 x 2
# Groups:   player [2]
  player tdc_x2
  <chr>   <int>
1 A         339
2 B         380
</code>```

I would like to be able to do this:

```<code>metric_list <- c('tdc', 'sumad')
minutes_list <- c(2,5)

df %>%
  x_min_roll(metric = metric_list, n_minutes = minutes_list, fun = sum) %>%
  # maybe a few more steps here.... to get this

# A tibble: 2 x 5
  player tdc_x2 tdc_x5 sumad_x2 sumad_x5
  <chr>   <dbl>  <dbl>    <dbl>    <dbl>
1 A         339    793       20       36
2 B         380    866       19       41
</code>```

答:
We can use map2 to loop over the corresponding elements of both vectors

```<code>library(purrr)
library(dplyr)
map2(metric_list, minutes_list,
  ~ df %>%
    x_min_roll(metric = !!.x, n_minutes = .y, fun = sum))
</code>```

-output

```<code>[[1]]
# A tibble: 2 × 2
# Groups:   player [2]
  player tdc_x2
  <chr>   <int>
1 A         339
2 B         380

[[2]]
# A tibble: 3 × 2
# Groups:   player [2]
  player sumad_x5
  <chr>     <int>
1 A            36
2 B            41
3 B            41
</code>```

EDIT: Based on @Onyambu's comments

If we want for each combination, then use crossing to create the combination

```<code>library(tidyr)
crossing(metric_list, minutes_list) %>%
 pmap(~ df %>%
      x_min_roll(metric = !!.x, n_minutes = .y, fun = sum))
</code>```

Based on the comments from the OP, if we want to combine the datasets

```<code>crossing(metric_list, minutes_list) %>%
 pmap(~ df %>% x_min_roll(metric = !!.x, n_minutes = .y, fun = sum)) %>%
    reduce(inner_join, by = 'player')
</code>```

Title: Custom function to loop over a list

Body:
I have a working custom function but not sure how to allow it to loop with a list of inputs. Looks like I need to understand apply() and the such but I'm not quite there with my current setup. The function uses rollapply() to find the largest metric for a given time frame.

library(zoo)
library(dplyr)

# Data
set.seed(1)
df <- tibble(player = rep(LETTERS[1:2], each = 10),
             minute = rep(1:10, times = 2),
             tdc = sample(100:200,size = 20),
             sumad = sample(1:10, size = 20, replace = TRUE))

# Custom function
x_min_roll <- function(df, metric, n_minutes, fun){
  metric <- ensym(metric)
  newname <- glue::glue("{rlang::as_string(metric)}_x{as.character(n_minutes)}")
  df %>%
    # dynamically create new column name based on input
    mutate("{newname}" := rollapply(!!metric, n_minutes, fun, align='left', fill=NA)) %>%
    group_by(player) %>%
    slice_max(.data[[newname]]) %>%
    select(player, .data[[newname]])
}

# This works
df %>%
  x_min_roll(metric = tdc, n_minutes = 2, fun = sum)

# A tibble: 2 x 2
# Groups:   player [2]
  player tdc_x2
  <chr>   <int>
1 A         339
2 B         380

I would like to be able to do this:

metric_list <- c('tdc', 'sumad')
minutes_list <- c(2,5)

df %>%
  x_min_roll(metric = metric_list, n_minutes = minutes_list, fun = sum) %>%
  # maybe a few more steps here.... to get this

# A tibble: 2 x 5
  player tdc_x2 tdc_x5 sumad_x2 sumad_x5
  <chr>   <dbl>  <dbl>    <dbl>    <dbl>
1 A         339    793       20       36
2 B         380    866       19       41

Body:
We can use map2 to loop over the corresponding elements of both vectors

library(purrr)
library(dplyr)
map2(metric_list, minutes_list,
  ~ df %>%
    x_min_roll(metric = !!.x, n_minutes = .y, fun = sum))

-output

[[1]]
# A tibble: 2 × 2
# Groups:   player [2]
  player tdc_x2
  <chr>   <int>
1 A         339
2 B         380

[[2]]
# A tibble: 3 × 2
# Groups:   player [2]
  player sumad_x5
  <chr>     <int>
1 A            36
2 B            41
3 B            41

EDIT: Based on @Onyambu's comments

If we want for each combination, then use crossing to create the combination

library(tidyr)
crossing(metric_list, minutes_list) %>%
 pmap(~ df %>%
      x_min_roll(metric = !!.x, n_minutes = .y, fun = sum))

Based on the comments from the OP, if we want to combine the datasets

crossing(metric_list, minutes_list) %>%
 pmap(~ df %>% x_min_roll(metric = !!.x, n_minutes = .y, fun = sum)) %>%
    reduce(inner_join, by = 'player')