问:
Hashmap's values update every time if I put new values & keys in it
So the problem is that if I add a new key&value pair to my hashmap it gets updated ,

right now the key is a number like and ID and the value is a list what countains numbers and
every id should have different list but it's broken for some reason.

So I would like to achieve different list values.

There is the code:

```<code>HashMap<Integer,List<Integer>> map22 = new HashMap<>();
int countrrr = 0;
List<Integer> asd = new ArrayList<>();
for (int i = 0; i <50; i++) {
    asd.add(i);
    if (i % 5 == 0) {
        countrrr++;
        map22.put(countrrr,asd);
        System.out.println(asd);
        asd.clear();
    }
}
System.out.println(map22);
</code>```

答:
The source of your problem is that your code currently uses only one List for storing all results (because HashMap.put() doesn't make clones of its arguments.) You need to create a fresh list after storing a result in the HashMap.

Something like this:

```<code>HashMap<Integer,List<Integer>> map22 = new HashMap<>();
int countrrr = 0;
List<Integer> asd = new ArrayList<>();
for (int i = 0; i <50; i++) {
    asd.add(i);
    if (i % 5 == 0) {
        countrrr++;
        map22.put(countrrr, asd);
        System.out.println(asd);
        asd = new ArrayList<>();
    }
}
System.out.println(map22);
</code>```

Body:
So the problem is that if I add a new key&value pair to my hashmap it gets updated ,

right now the key is a number like and ID and the value is a list what countains numbers and
every id should have different list but it's broken for some reason.

So I would like to achieve different list values.

There is the code:

HashMap<Integer,List<Integer>> map22 = new HashMap<>();
int countrrr = 0;
List<Integer> asd = new ArrayList<>();
for (int i = 0; i <50; i++) {
    asd.add(i);
    if (i % 5 == 0) {
        countrrr++;
        map22.put(countrrr,asd);
        System.out.println(asd);
        asd.clear();
    }
}
System.out.println(map22);

Body:
The source of your problem is that your code currently uses only one List for storing all results (because HashMap.put() doesn't make clones of its arguments.) You need to create a fresh list after storing a result in the HashMap.

Something like this:

HashMap<Integer,List<Integer>> map22 = new HashMap<>();
int countrrr = 0;
List<Integer> asd = new ArrayList<>();
for (int i = 0; i <50; i++) {
    asd.add(i);
    if (i % 5 == 0) {
        countrrr++;
        map22.put(countrrr, asd);
        System.out.println(asd);
        asd = new ArrayList<>();
    }
}
System.out.println(map22);


来源: stackexchange

问:
What is the name of the this sorting method?
I am learning sorting. but I don't know what this sorting method is called.

class Solution {
    public void sort(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (nums[i] > nums[j]) {
                    swap(nums, i, j);
                }
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
```

答:
It looks like a selection sort, but it's not correctly implemented.

https://en.wikipedia.org/wiki/Selection_sort

To start, your second for loop should start with j = i + 1

ContentLicense: CC BY-SA 4.0


问:
Material input type datetime-local shows its own placeholder and toggle button
I'm trying to render the angular material date picker. Which is not the problem (DEMO)

```<code><mat-form-field class="example-full-width">
    <input
        matInput
       [matDatepickerFilter]="myFilter"
       [matDatepicker]="picker"
       placeholder="Choose a date"
    />
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</code>```

But in my case I need a date-time picker. From what I found on the web, you simple add

```<code> type="datetime-local"
</code>```

to the input field. And I can confirm that this works, but it does weird things with the input field.

DEMO

Although angular material seems to support this type the picker you get however is native.

It has its own toggle button and it shows default text dd/mm/yyyy --:--. Is there a way to hide this text and toggle button?

答:
Angular material does not support time picker currently, but there is an open issue requesting that: https://github.com/angular/components/issues/5648

You can try to use 3rd party extension for date & time picker until it is added to Angular material: https://ng-matero.github.io/extensions/components/datetimepicker/overview

Body:
I'm trying to render the angular material date picker. Which is not the problem (DEMO)

<mat-form-field class="example-full-width">
    <input
        matInput
       [matDatepickerFilter]="myFilter"
       [matDatepicker]="picker"
       placeholder="Choose a date"
    />
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

But in my case I need a date-time picker. From what I found on the web, you simple add

 type="datetime-local"

to the input field. And I can confirm that this works, but it does weird things with the input field.

DEMO

Although angular material seems to support this type the picker you get however is native.

It has its own toggle button and it shows default text dd/mm/yyyy --:--. Is there a way to hide this text and toggle button?


问:
Calculating the 3 largest colums in excel and summing them
I am trying to calculate the total for the PT colums. I want it to calculate the top 3 PT colums and add them together. Excell noob so hoping someone can point me in the right direction. You can see my attempt in the screenshot below

答:
```<code>=SUM(LARGE(B2:P2*(B1:P1="PT"),{1,2,3}))
</code>```

Also an Array formula. Leave cell with CTRL+SHIFT+ENTER

Body:
=SUM(LARGE(B2:P2*(B1:P1="PT"),{1,2,3}))

Also an Array formula. Leave cell with CTRL+SHIFT+ENTER


问:
How to Create oracle PL/SQL function to store/retrieve data from table
i am beginner so i am confusing about what should i write in return type.

and how to write function to select all records from  particular ID

2   shadik  27  25-05-14    4000    pakistan
1   AKSHAY  28  30-04-20    2000    INDIA
3   GAURANG 25  06-05-20    4000    USA
4   NIRAV   23  16-11-14    1000    CANADA
5   VEER    29  26-12-19    5000    DUBAI
```

答:
A simple option is to return refcursor; you don't have to declare any type for that.

Here's an example based on Scott's sample schema. Function returns all rows from the EMP table whose DEPTNO column matches value passed as function's IN parameter.

```<code>SQL> create or replace function f_test (par_deptno in number)
  2    return sys_refcursor
  3  is
  4    rc sys_refcursor;
  5  begin
  6    open rc for select * from emp
  7                where deptno = par_deptno;
  8    return rc;
  9  end;
 10  /

Function created.

SQL> select f_test(10) from dual;

F_TEST(10)
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

     EMPNO ENAME      JOB              MGR HIREDATE        SAL       COMM     DEPTNO
---------- ---------- --------- ---------- -------- ---------- ---------- ----------
      7782 CLARK      MANAGER         7839 09.06.81       2450                    10
      7839 KING       PRESIDENT            17.11.81       5000                    10
      7934 MILLER     CLERK           7782 23.01.82       1300                    10

SQL>
</code>```

Body:
A simple option is to return refcursor; you don't have to declare any type for that.

Here's an example based on Scott's sample schema. Function returns all rows from the EMP table whose DEPTNO column matches value passed as function's IN parameter.

SQL> create or replace function f_test (par_deptno in number)
  2    return sys_refcursor
  3  is
  4    rc sys_refcursor;
  5  begin
  6    open rc for select * from emp
  7                where deptno = par_deptno;
  8    return rc;
  9  end;
 10  /

Function created.

SQL> select f_test(10) from dual;

F_TEST(10)
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

     EMPNO ENAME      JOB              MGR HIREDATE        SAL       COMM     DEPTNO
---------- ---------- --------- ---------- -------- ---------- ---------- ----------
      7782 CLARK      MANAGER         7839 09.06.81       2450                    10
      7839 KING       PRESIDENT            17.11.81       5000                    10
      7934 MILLER     CLERK           7782 23.01.82       1300                    10

SQL>


问:
How to append multiple values in setstate for array object Reactjs
I want to append objects in my array using setState function.
My initial variable looks like this:

```<code>columns1: [
        {
          title: "Sr. No.",
          render(text, record, index) {
            return {
              children: <div> {index + 1}</div>,
            };
          },
        },
        {
          title: "Account ID",
          dataIndex: "Accountid",
        },
        {
          title: "Alias",
          dataIndex: "Alias",
        },
      ],
</code>```

Now, in a function I want to add 2 more objects in columns1:

```<code>const projCol = {
      title: "Projected Cost",
      dataIndex: "forecast_amount",
      key: "forecast_amount",
  },

  const projChange = {
          title: "Percentage Change",
          dataIndex: "%change",
          key: "%change",
   }
</code>```

if I only wanted to add projCol I can do

```<code>this.setState((prevState) => {
      return {
        columns1: [...prevState.columns1,projCol],
      };
    });
</code>```

but how can I add both projCol and projChange?

答:
Just add one more element to the array like you do with projCol, separated by commas.

```<code>this.setState((prevState) => {
      return {
        columns1: [...prevState.columns1, projCol, projChange]
      };
  });
</code>```

Body:
I want to append objects in my array using setState function.
My initial variable looks like this:

columns1: [
        {
          title: "Sr. No.",
          render(text, record, index) {
            return {
              children:
 {index + 1}
,
            };
          },
        },
        {
          title: "Account ID",
          dataIndex: "Accountid",
        },
        {
          title: "Alias",
          dataIndex: "Alias",
        },
      ],

Now, in a function I want to add 2 more objects in columns1:

const projCol = {
      title: "Projected Cost",
      dataIndex: "forecast_amount",
      key: "forecast_amount",
  },

  const projChange = {
          title: "Percentage Change",
          dataIndex: "%change",
          key: "%change",
   }

if I only wanted to add projCol I can do

this.setState((prevState) => {
      return {
        columns1: [...prevState.columns1,projCol],
      };
    });

but how can I add both projCol and projChange?

Body:
Just add one more element to the array like you do with projCol, separated by commas.

this.setState((prevState) => {
      return {
        columns1: [...prevState.columns1, projCol, projChange]
      };
  });


问:
Reference another sheet in a formula using INDIRECT but it does not update as I add a new sheet
I have a sheet which has some results I need.  This sheet is then duplicated and renamed and the results updated. On a separate sheet I have a list of numbers, each sheet is renamed as a number from this column.  I then have a formula which pulls a cell from each sheet based on their name using the number column.  I am using the indirect formula =INDIRECT("'"&A5&"'!"&"B3" also  =INDIRECT(A6&"!B3") seems to work as well.  The problem I have is that when I duplicate a sheet and rename it the formula does not seem to work.  Interestingly when you are in the cell the result is shown in blue above but there is an error reported.

If I drag the formula down after I have duplicated the sheet it works. It just does not seem to recognise a new sheet.

Here is a very simple example of what I am trying to achieve.

Many thanks for any advice and help.

https://docs.google.com/spreadsheets/d/1D9UaIrtInEckdRP2jhWqTrevxGb0MqzYIMMrKDQI4Hc/edit?usp=sharing

答:
you will need to add swich:

```<code>=IF(D$2=TRUE, INDIRECT("'"&A9&"'!"&"B3"), INDIRECT("'"&A9&"'!"&"B3"))
</code>```

you can also use:

```<code>=IF(NOW()=NOW(), INDIRECT("'"&A14&"'!"&"B3"), )
</code>```

and set minute updates:

Body:
you will need to add swich:

=IF(D$2=TRUE, INDIRECT("'"&A9&"'!"&"B3"), INDIRECT("'"&A9&"'!"&"B3"))

you can also use:

=IF(NOW()=NOW(), INDIRECT("'"&A14&"'!"&"B3"), )

and set minute updates:


问:
Receiving or transmitting other protocols by LoRaWAN
There is a description in 《LoRaWAN Specification 1.0.2》:

3.3.7 Receiving or transmitting other protocols
  The node may listen or transmit other protocols or do any transactions between the LoRaWAN transmission and reception windows, as long as the end-device remains compatible with the local regulation and compliant with the LoRaWAN specification.

I'm puzzled about this “between the LoRaWAN transmission and reception windows”. Does it mean that we cloud do any transactions in the slot which is after LoRaWAN transmission and before reception windows?

答:
Does it mean that we cloud do any transactions in the slot which is after LoRaWAN transmission and before reception windows?

That's exactly what it means! As long as you comply with the specification - i.e. open Rx1 reception window (and Rx2 if nothing is received during Rx1) on time and with the right parameters - you can do whatever you want outside of these slots.

For instance, if you look at the SX126x description, you'll see that chip is capable of both LoRa and GFSK modulations. Between Tx and Rx1 (and Rx1 and Rx2 if it occurs), you can interleave a transmission / reception using GFSK modulation with the same chip.

ContentLicense: CC BY-SA 3.0


答:
Joining is always a procedure of first getting all combinations of all rows followed by a filter. We can do this manually:

library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#>     date, intersect, setdiff, union

datetimes_a <- tibble(
  id = seq(3),
  group = "A",
  datetime = c("2016-12-28 00:00:00", "2016-12-28 03:00:00", "2016-12-28 23:59:59") %>% as.POSIXct()
)
datetimes_b <- tibble(
  id = seq(3),
  group = "B",
  datetime = c("2016-12-28 00:00:10", "2016-12-28 03:20:00", "2016-12-29 00:00:02") %>% as.POSIXct()
)

datetimes_a %>%
  # start with cross product of all possible pairs
  expand_grid(datetimes_b %>% rename_all(~ paste0(.x, "_b"))) %>%
  mutate(diff = abs(datetime - datetime_b)) %>%
  # get shortest time difference
  group_by(id, id_b) %>%
  arrange(diff) %>%
  slice(1) %>%
  # time diff must be less than 1hr
  filter(diff < hours(1))
#> # A tibble: 3 x 7
#> # Groups:   id, id_b [3]
#>      id group datetime             id_b group_b datetime_b          diff
#>   <int> <chr> <dttm>              <int> <chr>   <dttm>              <drtn>
#> 1     1 A     2016-12-28 00:00:00     1 B       2016-12-28 00:00:10   10 secs
#> 2     2 A     2016-12-28 03:00:00     2 B       2016-12-28 03:20:00 1200 secs
#> 3     3 A     2016-12-28 23:59:59     3 B       2016-12-29 00:00:02    3 secs
```

Created on 2022-02-08 by the reprex package (v2.0.1)

This works also if the nearest timepoint is on another date e.g. right before and after midnight.

Title: Match two tables based on a time difference criterium

Body:
I have a data table (lv_timest) with time stamps every 3 hours for each date:

# A tibble: 6 × 5
     LV0_mean LV1_mean  LV2_mean Date_time           Date
     <dbl>    <dbl>     <dbl>    <S3:POSIXct>        <date>
1    0.778    -4.12     0.736    2016-12-28 00:00:00 2016-12-28
2    0.376    -0.234    0.388    2016-12-28 03:00:00 2016-12-28
3    0.409    1.46      0.241    2016-12-28 06:00:00 2016-12-28
4    0.760    2.07      0.460    2016-12-28 09:00:00 2016-12-28
5    0.759    2.91      0.735    2016-12-28 12:00:00 2016-12-28
6    0.857    3.00      0.803    2016-12-28 15:00:00 2016-12-28

from which I would like to extract the time stamps that match as closely as possible those of another table (event_timest):

# A tibble: 6 × 4
   Event_number Date_time           Date       Date_time_new
   <int>        <S3: POSIXct>       <date>     <S3: POSIXct>
1  75           2016-12-28 08:00:00 2016-12-28 2016-12-28 08:00:00
2  123          2016-12-30 14:02:00 2016-12-30 2016-12-30 14:00:00
3  264          2017-01-07 06:12:00 2017-01-07 2017-01-07 06:00:00
4  317          2017-01-09 10:59:00 2017-01-09 2017-01-09 11:00:00
5  318          2017-01-09 13:31:00 2017-01-09 2017-01-09 14:00:00
6  369          2017-01-11 07:24:00 2017-01-11 2017-01-11 07:00:00

For example, for row 1 in table event_timest, I would extract row 4 from table lv_timest:

Event_number Date_time.x          Date.x      Date_time_new      LV0_mean LV1_mean   LV2_mean Date_time.y          Date.y
<int>        <S3: POSIXct>        <date>      <S3: POSIXct>      <dbl>    <dbl>      <dbl>    <S3: POSIXct>        <date>
75           2016-12-28 08:00:00  2016-12-28 2016-12-28 08:00:00 0.760    2.07       0.460    2016-12-28 09:00:00  2016-12-28

In fact, the time difference should not be over one hour. I thought of using the fuzzyjoin package for this, and writing a function that computes the time difference between timestamps of the two table, as hours. However, fuzzy_inner_join replicates rows in the second table and takes several timestamps in the first table to match it.

require(lubridate)
require(fuzzyjoin)

diff_timest <- function(x, y){abs(x%--%y %/% hours(1)) <= 1} # time interval as hours ≤ 1 hour

match_timest <- fuzzy_inner_join(event_timest, lv_timest,
                                 by = c("Date" = "Date",
                                        "Date_time_new" = "Date_time"),
                                 match_fun = list(`==`, diff_timest))
head(match_timest)

# A tibble: 6 × 9
  Event_number Date_time.x         Date.x     Date_time_new       LV0_mean LV1_mean LV2_mean Date_time.y         Date.y
         <int> <dttm>              <date>     <dttm>                 <dbl>    <dbl>    <dbl> <dttm>              <date>
1           75 2016-12-28 08:00:00 2016-12-28 2016-12-28 08:00:00   0.760     2.07     0.460 2016-12-28 09:00:00 2016-12-28
2          123 2016-12-30 14:02:00 2016-12-30 2016-12-30 14:00:00   1.24      1.83     2.05  2016-12-30 15:00:00 2016-12-30
3          264 2017-01-07 06:12:00 2017-01-07 2017-01-07 06:00:00  -0.128    -5.43     2.72  2017-01-07 06:00:00 2017-01-07
4          317 2017-01-09 10:59:00 2017-01-09 2017-01-09 11:00:00  -0.0751    0.171    2.56  2017-01-09 09:00:00 2017-01-09
5          317 2017-01-09 10:59:00 2017-01-09 2017-01-09 11:00:00  -0.204    -0.797    2.28  2017-01-09 12:00:00 2017-01-09
6          318 2017-01-09 13:31:00 2017-01-09 2017-01-09 14:00:00  -0.204    -0.797    2.28  2017-01-09 12:00:00 2017-01-09

Would there be another way to do this?

Body:
Joining is always a procedure of first getting all combinations of all rows followed by a filter. We can do this manually:

library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#>     date, intersect, setdiff, union

datetimes_a <- tibble(
  id = seq(3),
  group = "A",
  datetime = c("2016-12-28 00:00:00", "2016-12-28 03:00:00", "2016-12-28 23:59:59") %>% as.POSIXct()
)
datetimes_b <- tibble(
  id = seq(3),
  group = "B",
  datetime = c("2016-12-28 00:00:10", "2016-12-28 03:20:00", "2016-12-29 00:00:02") %>% as.POSIXct()
)

datetimes_a %>%
  # start with cross product of all possible pairs
  expand_grid(datetimes_b %>% rename_all(~ paste0(.x, "_b"))) %>%
  mutate(diff = abs(datetime - datetime_b)) %>%
  # get shortest time difference
  group_by(id, id_b) %>%
  arrange(diff) %>%
  slice(1) %>%
  # time diff must be less than 1hr
  filter(diff < hours(1))
#> # A tibble: 3 x 7
#> # Groups:   id, id_b [3]
#>      id group datetime             id_b group_b datetime_b          diff
#>   <int> <chr> <dttm>              <int> <chr>   <dttm>              <drtn>
#> 1     1 A     2016-12-28 00:00:00     1 B       2016-12-28 00:00:10   10 secs
#> 2     2 A     2016-12-28 03:00:00     2 B       2016-12-28 03:20:00 1200 secs
#> 3     3 A     2016-12-28 23:59:59     3 B       2016-12-29 00:00:02    3 secs

Created on 2022-02-08 by the reprex package (v2.0.1)

This works also if the nearest timepoint is on another date e.g. right before and after midnight.


问:
Postgresql join_collapse_limit and time for query planning
I just discovered join_collapse_limit has been preventing the PostgreSQL planner from finding a much better join order. In my case, increasing the limit to 10 (from the default of 8) allowed the planner to improve search time from ~30 secs to ~1 ms, which is much more acceptable.

The documentation suggests that setting this "too high" could result in long planning times, but does not provide even a "rule of thumb" about how long the planning step might be for various values. I understand the general problem is exponential in time, but I cannot find a way to determine the actual planning time unless it it simply the time it takes to run ANALYZE SELECT .... If that is the case, I believe the default of 8 is quite low for modern computers since I can detect no difference in the speed of planning between 8 and 10.

Questions:

1) How can one measure planning time?

2) Approximately, how high can join_collapse_limit be and still expect planning to take less than a couple hundred milliseconds?

答:
This combination has been performing well for me in case of 30+ joins generated by NHibernate hierarchies, creating much better plans than with the default settings.

```<code>SET geqo = on;
SET geqo_threshold = 12;

SET from_collapse_limit = 40;
SET join_collapse_limit = 40;
</code>```

In such cases suboptimal query plans are often created unless the collapse limits are set to a larger number than the max expected joins.
The trick is that when using such high values for from_collapse_limit and join_collapse_limit you have to also use geqo with low enough geqo_threshold to avoid the (N!) problem.

This seems the very opposite of what the documentation is recommending to do:

Setting this value to geqo_threshold or more may trigger use of the GEQO planner, resulting in non-optimal plans.

But without geqo, or a value of it's threshold set too high even a value as low as 16 will cause the planning phase to take 10+ seconds and not be able to pick a good plan. In this case the 'non-optimal' plan provided by geqo in ~100ms is more desirable than the optimal plan taking hours of CPU time to compute.

Same settings can decide not to use geqo and get stuck in endless planning - your mileage may vary.

Body:
This combination has been performing well for me in case of 30+ joins generated by NHibernate hierarchies, creating much better plans than with the default settings.

SET geqo = on;
SET geqo_threshold = 12;

SET from_collapse_limit = 40;
SET join_collapse_limit = 40;

In such cases suboptimal query plans are often created unless the collapse limits are set to a larger number than the max expected joins.
The trick is that when using such high values for from_collapse_limit and join_collapse_limit you have to also use geqo with low enough geqo_threshold to avoid the (N!) problem.

This seems the very opposite of what the documentation is recommending to do:

Setting this value to geqo_threshold or more may trigger use of the GEQO planner, resulting in non-optimal plans.

But without geqo, or a value of it's threshold set too high even a value as low as 16 will cause the planning phase to take 10+ seconds and not be able to pick a good plan. In this case the 'non-optimal' plan provided by geqo in ~100ms is more desirable than the optimal plan taking hours of CPU time to compute.

Same settings can decide not to use geqo and get stuck in endless planning - your mileage may vary.


问:
.WSC won't recognize code changes
I've run into this problem before and the solution has usually been to restart IIS. Basically I've made a number of changes to a .wsc file on our server. But when it runs it doesn't run the new code changes I made. I've verified this with event logging at the beginning of the file and it doesn't show up.

My problem is that obviously restarting IIS on our production server is something I'm loathe to do, but we need this running today. I've tried re-registering the file but to no avail.

The server is a 32-bit Server 2008 OS. And the code is running, it still generates the file it is supposed to, but like I said, it's not using the latest changes.

Any other info I can provide, please leave a comment and I'll edit.

Thank you,
Jeff

Edit: Oisin, thanks for the reply and yes I know I hate VBScript, and anything related to it including these Window Script Components. I've expressed such feelings to my manager, but it's a dirty job and someone has to do it!

Yes it's using a Server.CreateObject to call the component.

ANSWER: I've since realized my mistake. I was only 'registering' it over and over, when I should have first 'unregester'ed it the 'register'ed it. Man I feel stupid, but haste makes waste as they say.

Thanks for the response and link!

答:
Eek, you mean WSC as in a Windows Script Component? I haven't written one of them since 2000.

Are you loading it using CreateObject (e.g. it's registered as a COM object via regsvr32), or are you using a file-based moniker to load it? (not registered).

If it's registered, it probably is cached until app restart. If you switched to a file based moniker, e.g. like: Set o = GetObject("script:c:\path\obj.wsc"), you might get away with runtime changes to the .wsc file.

(man, how did I even remember this)

more info here - quick before it's archived! :D
http://www.microsoft.com/technet/scriptcenter/resources/scriptshop/default.mspx

-Oisin

OwnerDisplayName: Jeff Keslinke

ContentLicense: CC BY-SA 2.5

Title: .WSC won't recognize code changes

LastEditorDisplayName: Jeff Keslinke


问:
Azure function which just inserts a record into a snowflake table is working fine but failing because of timeout issue sometime
I have an Azure function that inserts a record into a snowflake table. The function is working fine but sometimes the function is failing because of a timeout issue. The below work code is handled in the host.json file. The application insight logs say that it is a timeout error. Though the retry option is given as 3. The function fails again.

"extensions": {
"concurrency": {
"dynamicConcurrencyEnabled": true,
"snapshotPersistenceEnabled": true
}
}
}

Any solution to fix this issue?

答:
I assume your goal is to get rid of timeout? If yes than this table might help you: https://learn.microsoft.com/en-us/azure/azure-functions/functions-scale

You can control the timeout by adding this entry to your job configuration in azure:

Key: AzureFunctionsJobHost__functionTimeout

Value: valueInMinutes

If you wonna go unlimited just put '-1' in value.


问:
serier to tolist() gives elements in squared brackets when appended python
When i convert the series object to list and append each element to a new list the elements are added with extra squared brackets.

Can someone help me on how to remove the brackets or append without adding extra bracket for each element

```<code>import pandas as pd

df = pd.DataFrame({'col1':[10,20,30],'col2':[40,50,60]})
print(df.head())
df_fd = pd.DataFrame({'variable':['col1','col1','col1','col2','col2','col2'],'Value':[10,20,30,40,50,60],'ratio':[0.1,0.2,0.3,0.4,0.5,0.6]})

print(df_fd)

df_new = pd.DataFrame()
print(df.head())
for col in df.columns:
    ratio_list = []
    print('Columns:',col)
    for val in df[col].unique():
        print('Instance:',val)
        print('Ratio value:',(df_fd.loc[(df_fd['variable'] == col) & (df_fd['Value'] == val)]['ratio']))
        ratio = df_fd.loc[(df_fd['variable'] == col) & (df_fd['Value'] == val)]['ratio']
        ratio = list(ratio)
        print('ratio:',ratio)
        ratio_list.append(ratio)
        print(ratio_list)
    df_new['ratio'] = ratio_list
    df_new.rename(columns={"ratio":"Ratio_"+col},inplace=True)
    print(df_new.head())

df = pd.concat([df,df_new],axis=1)
print(df.head())
</code>```
```<code>I get output something like this :
[[0.1], [0.2], [0.3]]

col1  col2 Ratio_col1 Ratio_col2
0    10    40      [0.1]      [0.4]
1    20    50      [0.2]      [0.5]
2    30    60      [0.3]      [0.6]
</code>```

答:
```<code>ratio = df_fd.loc[(df_fd['variable'] == col) & (df_fd['Value'] == val)]['ratio'].values[0]
</code>```

remove

ratio=list(ratio)

Body:
When i convert the series object to list and append each element to a new list the elements are added with extra squared brackets.

Can someone help me on how to remove the brackets or append without adding extra bracket for each element

import pandas as pd

df = pd.DataFrame({'col1':[10,20,30],'col2':[40,50,60]})
print(df.head())
df_fd = pd.DataFrame({'variable':['col1','col1','col1','col2','col2','col2'],'Value':[10,20,30,40,50,60],'ratio':[0.1,0.2,0.3,0.4,0.5,0.6]})

print(df_fd)

df_new = pd.DataFrame()
print(df.head())
for col in df.columns:
    ratio_list = []
    print('Columns:',col)
    for val in df[col].unique():
        print('Instance:',val)
        print('Ratio value:',(df_fd.loc[(df_fd['variable'] == col) & (df_fd['Value'] == val)]['ratio']))
        ratio = df_fd.loc[(df_fd['variable'] == col) & (df_fd['Value'] == val)]['ratio']
        ratio = list(ratio)
        print('ratio:',ratio)
        ratio_list.append(ratio)
        print(ratio_list)
    df_new['ratio'] = ratio_list
    df_new.rename(columns={"ratio":"Ratio_"+col},inplace=True)
    print(df_new.head())

df = pd.concat([df,df_new],axis=1)
print(df.head())

I get output something like this :
[[0.1], [0.2], [0.3]]

col1  col2 Ratio_col1 Ratio_col2
0    10    40      [0.1]      [0.4]
1    20    50      [0.2]      [0.5]
2    30    60      [0.3]      [0.6]

Body:
ratio = df_fd.loc[(df_fd['variable'] == col) & (df_fd['Value'] == val)]['ratio'].values[0]

remove

ratio=list(ratio)


问:
Link worktime from one form to another
I have a model in which we can choose the opening hours of the institution for each day of the week, from such and such to such and such, for example Monday 12:00 AM - 11:30 PM

```<code><?php

namespace common\models;

use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;

class WorkHours extends _source_WorkHours
{
    public const WEEK_DAY_MON = 'Mon';
    public const WEEK_DAY_TUE = 'Tue';
    public const WEEK_DAY_WED = 'Wed';
    public const WEEK_DAY_THU = 'Thu';
    public const WEEK_DAY_FRI = 'Fri';
    public const WEEK_DAY_SAT = 'Sat';
    public const WEEK_DAY_SUN = 'Sun';

    /**
     * {@inheritdoc}
     */
    public function behaviors(): array
    {
        return [
            'timestamp' => [
                'class'      => TimestampBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                ],
                'value'      => new Expression('NOW()'),
            ],
        ];
    }

    public static function weekDays(): array
    {
        return [
            self::WEEK_DAY_MON => 'Monday',
            self::WEEK_DAY_TUE => 'Tuesday',
            self::WEEK_DAY_WED => 'Wednesday',
            self::WEEK_DAY_THU => 'Thursday',
            self::WEEK_DAY_FRI => 'Friday',
            self::WEEK_DAY_SAT => 'Saturday',
            self::WEEK_DAY_SUN => 'Sunday',
        ];
    }

    public static function getWeekDay(string $val): string
    {
        $ar = self::weekDays();

        return $ar[$val] ?? $val;
    }

    public static function hoursList(): array
    {
        $list = [];
        for ($i = 0; $i < 24; $i++) {
            $A = 'AM';
            $n = $i;
            if ($i >= 12) {
                $A = 'PM';
                $n = $i - 12;
            }

            $n = $n < 10 ? '0' . $n : $n;
            $_A = ($i === 12 ? 'AM' : $A);
            $list[$i . '.00'] = $n . '.00 ' . ($i === 0 ? 'PM' : $_A);
            $list[$i . '.30'] = $n . '.30 ' . $A;
        }
        return $list;
    }
}
</code>```

Next, I use this model when creating an institution, and the ability to choose the opening hours there

```<code><div class="form-group">
        <label class="control-label col-sm-3">Wokr Hours</label>
        <div class="col-sm-6">

            <div class="form-group">
                <?php foreach (WorkHours::weekDays() as $weekDay => $day) { ?>
                    <div class="col-sm-2"><?= $weekDay ?></div>
                    <div class="col-sm-5">
                        <?= $form->field(
                            $restaurantWorkHoursForm,
                            RestaurantWorkHoursForm::getAttributeName($weekDay, 'open'),
                            ['template' => '<div class="col-sm-12">{input}</div>']
                        )->dropDownList(WorkHours::hoursList(), ['prompt' => ''])->label(false) ?>
                    </div>
                    <div class="col-sm-5">
                        <?= $form->field(
                            $restaurantWorkHoursForm,
                            RestaurantWorkHoursForm::getAttributeName($weekDay, 'close'),
                            ['template' => '<div class="col-sm-12">{input}</div>']
                        )->dropDownList(WorkHours::hoursList(), ['prompt' => ''])->label(false) ?></div>
                <?php } ?>
            </div>
        </div>
    </div>
</code>```

I also use this model when booking a place in an institution where you can choose the time, but here you can choose any time of the day

```<code><a class="btn btn-fourth <?= $restaurantReservationForm->getErrors('time') ? 'btn-error' : '' ?>"
               id="reservation-time" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <span class="icon br-clock"></span> <span class="js-value">
                    <?= $restaurantReservationForm->time
                        ? WorkHours::hoursList()[$restaurantReservationForm->time] : '-- : --' ?>
                </span>
            </a>
            <ul class="dropdown-menu dropdown-menu-height-fixed" aria-labelledby="reservation-time">
                <?php foreach (WorkHours::hoursList() as $k => $v) { ?>
                    <li><a class="dropdown-item <?= $restaurantReservationForm->time === $k ? 'active' : ''
                        ?>" href="#" data-value="<?= $k ?>"><?= $v ?></a></li>
                <?php } ?>
            </ul>
</code>```

Now what is the question. I have two forms. In one, the time was indicated, in the other there should be a choice of time from the first form. How can you link the opening hours of the establishment that we indicated with the choice of the time of booking?

Let's say we have a working time 12:00 AM - 11:30 PM, any time is available in the booking, but it is necessary that there is a choice only within the opening hours of the institution that we specified earlier, that is, from 12:00 AM to 11:30 PM, and so on every day, if the time is not selected in the institution for some day , then the booking will also be empty

Is there a way to do this via json ?

答:
This is solvable of course, but you will need to handle it both on the server-side and client-side. The need on the server-side is that you ensure that there is no shenanigans done by a technically advanced user and on the client-side your need is to help the user know from which period he or she can choose the value.

On the server-side you have several choices in terms of storage, but a feasible approach (assuming that the chosen interval will be reused in the future as well) is to store this value into the database. That would mean that you will need a CRUD for this value on server-side and an API function that serves client-side requests, telling the user what his/her choice was. On the server-side you can encode stuff into JSON via json_encode and send the result to the client.

You will need a validator both on the server-side and the client-side in order to determine whether a given date is inside the specified interval.

In short, you need:

Database schema support for this interval

Application server-side CRUD

Server-side API

Client-side functionality that handles the API request

Validator both on server and client-side

Handling the logic on the UI rendering and handling using the validator

Handling the logic when the chosen date or date interval is being stored

Title: Link worktime from one form to another

Body:
I have a model in which we can choose the opening hours of the institution for each day of the week, from such and such to such and such, for example Monday 12:00 AM - 11:30 PM

<?php

namespace common\models;

use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;

class WorkHours extends _source_WorkHours
{
    public const WEEK_DAY_MON = 'Mon';
    public const WEEK_DAY_TUE = 'Tue';
    public const WEEK_DAY_WED = 'Wed';
    public const WEEK_DAY_THU = 'Thu';
    public const WEEK_DAY_FRI = 'Fri';
    public const WEEK_DAY_SAT = 'Sat';
    public const WEEK_DAY_SUN = 'Sun';

    /**
     * {@inheritdoc}
     */
    public function behaviors(): array
    {
        return [
            'timestamp' => [
                'class'      => TimestampBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                ],
                'value'      => new Expression('NOW()'),
            ],
        ];
    }

    public static function weekDays(): array
    {
        return [
            self::WEEK_DAY_MON => 'Monday',
            self::WEEK_DAY_TUE => 'Tuesday',
            self::WEEK_DAY_WED => 'Wednesday',
            self::WEEK_DAY_THU => 'Thursday',
            self::WEEK_DAY_FRI => 'Friday',
            self::WEEK_DAY_SAT => 'Saturday',
            self::WEEK_DAY_SUN => 'Sunday',
        ];
    }

    public static function getWeekDay(string $val): string
    {
        $ar = self::weekDays();

        return $ar[$val] ?? $val;
    }

    public static function hoursList(): array
    {
        $list = [];
        for ($i = 0; $i < 24; $i++) {
            $A = 'AM';
            $n = $i;
            if ($i >= 12) {
                $A = 'PM';
                $n = $i - 12;
            }

            $n = $n < 10 ? '0' . $n : $n;
            $_A = ($i === 12 ? 'AM' : $A);
            $list[$i . '.00'] = $n . '.00 ' . ($i === 0 ? 'PM' : $_A);
            $list[$i . '.30'] = $n . '.30 ' . $A;
        }
        return $list;
    }
}

Next, I use this model when creating an institution, and the ability to choose the opening hours there

        Wokr Hours

                <?php foreach (WorkHours::weekDays() as $weekDay => $day) { ?>

<?= $weekDay ?>

                        <?= $form->field(
                            $restaurantWorkHoursForm,
                            RestaurantWorkHoursForm::getAttributeName($weekDay, 'open'),
                            ['template' => '
{input}
']
                        )->dropDownList(WorkHours::hoursList(), ['prompt' => ''])->label(false) ?>

                        <?= $form->field(
                            $restaurantWorkHoursForm,
                            RestaurantWorkHoursForm::getAttributeName($weekDay, 'close'),
                            ['template' => '
{input}
']
                        )->dropDownList(WorkHours::hoursList(), ['prompt' => ''])->label(false) ?>

                <?php } ?>

I also use this model when booking a place in an institution where you can choose the time, but here you can choose any time of the day

<a class="btn btn-fourth <?= $restaurantReservationForm->getErrors('time') ? 'btn-error' : '' ?>"
               id="reservation-time" role="button" data-bs-toggle="dropdown" aria-expanded="false">

                    <?= $restaurantReservationForm->time
                        ? WorkHours::hoursList()[$restaurantReservationForm->time] : '-- : --' ?>

                <?php foreach (WorkHours::hoursList() as $k => $v) { ?>

<a class="dropdown-item <?= $restaurantReservationForm->time === $k ? 'active' : ''
                        ?>" href="#" data-value="<?= $k ?>"><?= $v ?>

                <?php } ?>

Now what is the question. I have two forms. In one, the time was indicated, in the other there should be a choice of time from the first form. How can you link the opening hours of the establishment that we indicated with the choice of the time of booking?

Let's say we have a working time 12:00 AM - 11:30 PM, any time is available in the booking, but it is necessary that there is a choice only within the opening hours of the institution that we specified earlier, that is, from 12:00 AM to 11:30 PM, and so on every day, if the time is not selected in the institution for some day , then the booking will also be empty

Is there a way to do this via json ?


问:
TypeError: strptime() argument 1 must be str, not Timestamp
I want to add a time interval of 1 day to a timestamp end, of format 0   2020-12-03 Name: Test Date, dtype: datetime64[ns].

df:

```<code>    Date        Id  Value
0   2020-12-03  5   050
1   2020-04-07  12  051
2   2020-05-05  6   052
3   2020-05-19  6   059
</code>```

I used:

```<code>import datetime
...
end = df.loc[df.col== i, 'Date']
print(end)
start = (datetime.datetime.strptime(end,'%Y-%m-%d') - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
...
</code>```

and it caught error:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-161-d9b441080f1a> in <module>

     10     print(end)
---> 11     start = (datetime.datetime.strptime(end,'%Y-%m-%d %H:%M:%S') - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
     12
     13

TypeError: strptime() argument 1 must be str, not Timestamp

</code>```

答:
In your program, the end is in the "date" type. But it should be in str.

try this,

end = str(end)

Body:
I want to add a time interval of 1 day to a timestamp end, of format 0   2020-12-03 Name: Test Date, dtype: datetime64[ns].

df:

    Date        Id  Value
0   2020-12-03  5   050
1   2020-04-07  12  051
2   2020-05-05  6   052
3   2020-05-19  6   059

I used:

import datetime
...
end = df.loc[df.col== i, 'Date']
print(end)
start = (datetime.datetime.strptime(end,'%Y-%m-%d') - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
...

and it caught error:

TypeError                                 Traceback (most recent call last)
<ipython-input-161-d9b441080f1a> in <module>

     10     print(end)
---> 11     start = (datetime.datetime.strptime(end,'%Y-%m-%d %H:%M:%S') - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
     12
     13

TypeError: strptime() argument 1 must be str, not Timestamp


问:
How can I read the contents of a DocumentFile in Android?
I have added a feature to an application to allow the user to create a local backup on external storage. That part is working great, but I am having trouble restoring that back up.

Using the SAF, I have found an easy way for the user to select the file they are wanting to restore. The file they choose comes back to the app as a DocumentFile

How can I open the DocumentFile and read its contents on API 26 and up?

So far I tried 2 things and neither worked:

1)
new File(myDocumentFile.getUri().getPath())

2)
I've tried this answer but it didn't work. It is also so hacky and I don't really need access to the java.io.File I just need a way to read the contents.

How does Google want us to approach reading user's files?

答:
Kotlin code to read lines from a text file (where 'file' is a DocumentFile)</p>
```<code>val inputStream = contentResolver.openInputStream(file.uri)
val reader = BufferedReader(InputStreamReader(inputStream))
val lines = reader.readLines()
</code>```

Body:
Kotlin code to read lines from a text file (where 'file' is a DocumentFile)

val inputStream = contentResolver.openInputStream(file.uri)
val reader = BufferedReader(InputStreamReader(inputStream))
val lines = reader.readLines()


问:
Are nested groups inside azure active directory work in SharePoint online
Are nested groups inside azure active directory work in SharePoint online? so if we created a nested azure active directory group, can we add this nested group to SharePoint site permission?

In other words, let say we have 2 AD groups; Group-A & Group-B .. and we added Group-B inside Group-A .. then we added the nested group to a SharePoint site >> then will all users inside AD Group-A and AD Group-B get the permission on SharePoint? Thanks

答:
•   As per what you said, nested groups are a subset of the larger groups they are a part of, i.e., nested group members can be a part of multiple member groups and other nested groups of which they are originally a part of. And since you are talking of Azure AD groups, they are of two types, viz., Microsoft 365 and Security. I tried to give permission to groups created in Azure AD, both Microsoft 365 and Security groups to Sharepoint site through ‘Site Permissions’ option and was successful in adding the groups to the respective sites for Sharepoint access.

Also, these groups are nested as specified by me above and I didn’t encounter any such issue in accessing the Sharepoint site through them. Please find the screenshot below for reference: -

Of the above, ‘Test_group’ and ‘All Users’ are Security groups, so they cannot be added in the ‘Grant Permissions’ list or they won’t be invited whereas the other two groups are Microsoft 365 groups, so their users who have Office 365 license enabled will be invited and be able to grant the required permissions. Thus, nested Microsoft 365 Azure AD groups are only allowed for Sharepoint site permissions. For more information regarding the groups, please refer the below link for more details: -

https://learn.microsoft.com/en-us/microsoft-365/admin/create-groups/compare-groups?view=o365-worldwide


问:
SonarQube XPATH: Validate the data based on the delimiters
We have a pattern set of file name separated with delimiter, Sometimes Customers put the incorrect naming pattern, to validate it we are using SonarQube, Can we split the data based on delimiter and validate it?

Correct Pattern:
1st File:

```<code><root><filename>FILE_SALES_Outlet_C2C_CARGO_09092021</filename></root>
</code>```

2nd File

```<code><root><filename>FILE_SALES_Inhouse_B2B_WAREHOUSE_10122021</filename></root>
</code>```

Incorrect Pattern:

```<code><root><filename>FILE_09092021_SALE_BB_CARGO_Copy</filename></root>

<root><filename>SALES_Business_WAREHOUSE_10122021_v2_File</filename></root>
</code>```

In a single xpath Can I Validate below rules?

It should Start with FILE

After 1st Delimiter (_) it should be always SALES

After 3rd Delimited it should be (C2C/B2B)

It should only have 5 delimiters

Thanks in advance!

答:
Try this (not so pretty) XPath-1.0 expression (if the second string should start with 'SALES'):

```<code>/root/filename[starts-with(.,'FILE') and starts-with(substring-after(.,'_'),'SALES') and (substring-before(substring-after(substring-after(substring-after(.,'_'),'_'),'_'),'_')='C2C' or substring-before(substring-after(substring-after(substring-after(.,'_'),'_'),'_'),'_')='B2B') and (string-length(.)-string-length(translate(.,'_',''))=5)]
</code>```

or (if the second string should be 'SALES' only)

```<code>/root/filename[starts-with(.,'FILE') and substring-before(substring-after(.,'_'),'_')='SALES' and (substring-before(substring-after(substring-after(substring-after(.,'_'),'_'),'_'),'_')='C2C' or substring-before(substring-after(substring-after(substring-after(.,'_'),'_'),'_'),'_')='B2B') and (string-length(.)-string-length(translate(.,'_',''))=5)]
</code>```

Both approaches should do the job.

Body:
We have a pattern set of file name separated with delimiter, Sometimes Customers put the incorrect naming pattern, to validate it we are using SonarQube, Can we split the data based on delimiter and validate it?

Correct Pattern:
1st File:

<root><filename>FILE_SALES_Outlet_C2C_CARGO_09092021</filename></root>

2nd File

<root><filename>FILE_SALES_Inhouse_B2B_WAREHOUSE_10122021</filename></root>

Incorrect Pattern:

<root><filename>FILE_09092021_SALE_BB_CARGO_Copy</filename></root>

<root><filename>SALES_Business_WAREHOUSE_10122021_v2_File</filename></root>

In a single xpath Can I Validate below rules?

It should Start with FILE

After 1st Delimiter (_) it should be always SALES

After 3rd Delimited it should be (C2C/B2B)

It should only have 5 delimiters

Thanks in advance!

Body:
Try this (not so pretty) XPath-1.0 expression (if the second string should start with 'SALES'):

/root/filename[starts-with(.,'FILE') and starts-with(substring-after(.,'_'),'SALES') and (substring-before(substring-after(substring-after(substring-after(.,'_'),'_'),'_'),'_')='C2C' or substring-before(substring-after(substring-after(substring-after(.,'_'),'_'),'_'),'_')='B2B') and (string-length(.)-string-length(translate(.,'_',''))=5)]

or (if the second string should be 'SALES' only)

/root/filename[starts-with(.,'FILE') and substring-before(substring-after(.,'_'),'_')='SALES' and (substring-before(substring-after(substring-after(substring-after(.,'_'),'_'),'_'),'_')='C2C' or substring-before(substring-after(substring-after(substring-after(.,'_'),'_'),'_'),'_')='B2B') and (string-length(.)-string-length(translate(.,'_',''))=5)]

Both approaches should do the job.


问:
Spring Reactive Repository: findById(ID) vs. findById(Publisher<ID>)
What ist better to create a fully non-blocking REST-Service?

Mono<T> findById(ID id);
```
<p>or</p>
<pre class="lang-java prettyprint-override"><code>Mono<T> findById(Publisher<ID> id);
</code>```

Is the second method less blocking?

Here is an example:

@GetMapping
public Mono<UserProfile> getUserProfile(Mono<Authentication> authentication) {
     return reactiveUserProfileRepository.findById(
          authentication.map(auth -> auth.getName()));
}
```
<p>Or is it good enough to use an object as parameter?</p>
<pre class="lang-java prettyprint-override"><code>public Mono<UserProfile> getUserProfile(Authentication authentication) {
...
</code>```

答:
According to the documentation you can benefit from non-blocking reading when using @RequestBody and reactive types:

Unlike Spring MVC, in WebFlux, the @RequestBody method argument
supports reactive types and fully non-blocking reading and
(client-to-server) streaming.

Body:
What ist better to create a fully non-blocking REST-Service?

Mono<T> findById(ID id);

or

Mono<T> findById(Publisher<ID> id);

Is the second method less blocking?

Here is an example:

@GetMapping
public Mono<UserProfile> getUserProfile(Mono<Authentication> authentication) {
     return reactiveUserProfileRepository.findById(
          authentication.map(auth -> auth.getName()));
}

Or is it good enough to use an object as parameter?

public Mono<UserProfile> getUserProfile(Authentication authentication) {
...


问:
JOIN of two subqueries returns 1000x more rows than the total both subqueries combined
Im using a Postgres DB via PGAdmin 4.13

For the sake of performance, I'm trying to run two separate selects, and then do an inner join on them. However, it appears to be running every row against every other row, and I'm returning a table that exponentially too large (literally 1000x bigger than either query alone returns.)

First query returns 4320 rows:

```<code>SELECT * FROM schema_name.table_one WHERE resultset_name LIKE 'My test results%'
</code>```

Second query returns 1080 rows:

```<code>SELECT * FROM schema_name.table_two WHERE resultset_name LIKE 'My test results%'
</code>```

Join returns 518000 rows :D

```<code>SELECT *
FROM
(SELECT * FROM schema_name.table_one WHERE resultset_name LIKE 'My test results%') t1
INNER JOIN
(SELECT * FROM schema_name.table_two WHERE resultset_name LIKE 'My test results%') t2
ON t1.resultset_name = t2.resultset_name
</code>```

Attempting to run a more traditional inner or left join runs forever...

```<code>SELECT *
FROM schema_name.table_two
INNER JOIN schema_name.table_one
ON schema_name.table_two.resultset_name = schema_name.table_one.resultset_name
WHERE schema_name.table_two.resultset_name LIKE 'My test results%'
</code>```

NOTE: That the WHERE schema_name.table_two.resultset_name LIKE 'My test results%' requires the schema_name.table_two. to be in the WHERE clause, otherwise it errors on an ambiguous column name.

QUESTION 1:
Why is the JOIN from two subselects returning so many rows? My intention was to slim down memory use - by returning two smaller tables - and then joining only the data in those tables. Can the query be corrected to do this?

QUESTION 2:
If my initial join of two subselects cannot work the way I want it to, how can I filter down the memory use for the traditional join?

EDIT: For additional clarity

答:
QUESTION 1: you are joining via resultset_name. I suspect that a lot of rows have the same value in this column. If you have 10 rows in Table_one with resultset_name='My test results 1', and table_two has 20 rows with the same value then the result will have 10x20=200 rows for the same resultset_name.

QUESTION 2: Most database systems do this optimisation themselves (without you having to restructure/rearrange your query). I guess it is because of Q1 that it uses lots of resources.

Are you certain that the join condition is t1.resultset_name = t2.resultset_name?

If you can't confirm that this is the case, do some profiling of the resultset_name to find out how many unique values in how many rows, and if the scenario I mentioned in Q1 applies.

Edit: if table_two has the same date for every row for the same resultset_name (or if you are interested in any one of them), then you can reduce table_to two one row per resultset_name before joining to table_one, as follows:

```<code>SELECT *
FROM
    schema_name.table_one t1

    INNER JOIN
    (   SELECT t2a.resultset_name,
               min(t2a.date_of_experiment) as date_of_experiment
        FROM schema_name.table_two t2a
        WHERE t2a.resultset_name LIKE 'My test results%'
        GROUP BY t2a.resultset_name) t2
    ON t1.resultset_name = t2.resultset_name
    AND t1.resultset_name LIKE 'My test results%'
</code>```

Body:
Im using a Postgres DB via PGAdmin 4.13

For the sake of performance, I'm trying to run two separate selects, and then do an inner join on them. However, it appears to be running every row against every other row, and I'm returning a table that exponentially too large (literally 1000x bigger than either query alone returns.)

First query returns 4320 rows:

SELECT * FROM schema_name.table_one WHERE resultset_name LIKE 'My test results%'

Second query returns 1080 rows:

SELECT * FROM schema_name.table_two WHERE resultset_name LIKE 'My test results%'

Join returns 518000 rows :D

SELECT *
FROM
(SELECT * FROM schema_name.table_one WHERE resultset_name LIKE 'My test results%') t1
INNER JOIN
(SELECT * FROM schema_name.table_two WHERE resultset_name LIKE 'My test results%') t2
ON t1.resultset_name = t2.resultset_name

Attempting to run a more traditional inner or left join runs forever...

SELECT *
FROM schema_name.table_two
INNER JOIN schema_name.table_one
ON schema_name.table_two.resultset_name = schema_name.table_one.resultset_name
WHERE schema_name.table_two.resultset_name LIKE 'My test results%'

NOTE: That the WHERE schema_name.table_two.resultset_name LIKE 'My test results%' requires the schema_name.table_two. to be in the WHERE clause, otherwise it errors on an ambiguous column name.

QUESTION 1:
Why is the JOIN from two subselects returning so many rows? My intention was to slim down memory use - by returning two smaller tables - and then joining only the data in those tables. Can the query be corrected to do this?

QUESTION 2:
If my initial join of two subselects cannot work the way I want it to, how can I filter down the memory use for the traditional join?

EDIT: For additional clarity

Body:
QUESTION 1: you are joining via resultset_name. I suspect that a lot of rows have the same value in this column. If you have 10 rows in Table_one with resultset_name='My test results 1', and table_two has 20 rows with the same value then the result will have 10x20=200 rows for the same resultset_name.

QUESTION 2: Most database systems do this optimisation themselves (without you having to restructure/rearrange your query). I guess it is because of Q1 that it uses lots of resources.

Are you certain that the join condition is t1.resultset_name = t2.resultset_name?

If you can't confirm that this is the case, do some profiling of the resultset_name to find out how many unique values in how many rows, and if the scenario I mentioned in Q1 applies.

Edit: if table_two has the same date for every row for the same resultset_name (or if you are interested in any one of them), then you can reduce table_to two one row per resultset_name before joining to table_one, as follows:

SELECT *
FROM
    schema_name.table_one t1

    INNER JOIN
    (   SELECT t2a.resultset_name,
               min(t2a.date_of_experiment) as date_of_experiment
        FROM schema_name.table_two t2a
        WHERE t2a.resultset_name LIKE 'My test results%'
        GROUP BY t2a.resultset_name) t2
    ON t1.resultset_name = t2.resultset_name
    AND t1.resultset_name LIKE 'My test results%'


问:
Buildozer failed to execute the last command: The headers or library files could not be found for zlib
I have been trying to generate an .apk with buildozer. The .apk is successfully generated, but it crashes each time due to the following error:

```<code>setup.py build_ext -v

  File "setup.py", line 622, in build_extensions
    raise RequiredDependencyException(f)
__main__.RequiredDependencyException: zlib

  STDOUT:
running build_ext

The headers or library files could not be found for zlib,
a required dependency when compiling Pillow from source.
</code>```

I have tried all the possible solutions found for similar errors, such as:

Downgrade pip:

```<code>python -m pip install pip==19.3.1
</code>```

Change Pillow's version:

```<code>pip install  Pillow==6.2.2
</code>```

Installed the following packages:

```<code>sudo apt-get python-dev py-pip jpeg-dev zlib-dev
sudo apt-get install libjpeg-dev zlib1g-dev
</code>```

But none of them solved the problem. I'm using Python version 3.8.12. And I'm running on WSL:Ubuntu virtual machine.

I would very much appreciate any help.

答: I was able to bypass the issue by using cv2 instead of Pillow, definitely not the best approach.

Body:
I have been trying to generate an .apk with buildozer. The .apk is successfully generated, but it crashes each time due to the following error:

setup.py build_ext -v

  File "setup.py", line 622, in build_extensions
    raise RequiredDependencyException(f)
__main__.RequiredDependencyException: zlib

  STDOUT:
running build_ext

The headers or library files could not be found for zlib,
a required dependency when compiling Pillow from source.

I have tried all the possible solutions found for similar errors, such as:

Downgrade pip:

python -m pip install pip==19.3.1

Change Pillow's version:

pip install  Pillow==6.2.2

Installed the following packages:

sudo apt-get python-dev py-pip jpeg-dev zlib-dev
sudo apt-get install libjpeg-dev zlib1g-dev

But none of them solved the problem. I'm using Python version 3.8.12. And I'm running on WSL:Ubuntu virtual machine.

I would very much appreciate any help.


问:
In C++ map, which is better for usage/perfomance and conforms to the guidelines, using find_if or find then and .at
I am using a C++ map, in which I need to search for an element then get the element if it is exist.

The first way to do that is using find

if (mymap.find(mykey) == mymap.end())
{
    //return error code
    return ERROR_CODE;
}
else
{
    value = mymap.at(mykey).second;
    return SUCCESS_CODE;
}
```
<p>second way to do that:</p>
<pre class="lang-cpp prettyprint-override"><code>auto iter= find_if(mymap.begin(), mymap.end(), [&key](auto &item){return item.first == key;})
if(iter == mymap.end())
{
   return ERROR_CODE;
}
else
{
    value = iter->second;
    return SUCCESS_CODE;
}
</code>```

Is there any technical consideration or guidelines (like cpp guideline) that mention something like that, which way is better?

答:
You should not use std::find_if which is linear, whereas you might have iterator in logarithm time. You might do

```<code>auto it = mymap.find(mykey)
if (it == mymap.end())
{
    //return error code
    return ERROR_CODE;
}
else
{
    value = it->second;
    return SUCCESS_CODE;
}
</code>```

Body:
I am using a C++ map, in which I need to search for an element then get the element if it is exist.

The first way to do that is using find

if (mymap.find(mykey) == mymap.end())
{
    //return error code
    return ERROR_CODE;
}
else
{
    value = mymap.at(mykey).second;
    return SUCCESS_CODE;
}

second way to do that:

auto iter= find_if(mymap.begin(), mymap.end(), [&key](auto &item){return item.first == key;})
if(iter == mymap.end())
{
   return ERROR_CODE;
}
else
{
    value = iter->second;
    return SUCCESS_CODE;
}

Is there any technical consideration or guidelines (like cpp guideline) that mention something like that, which way is better?

Body:
You should not use std::find_if which is linear, whereas you might have iterator in logarithm time. You might do

auto it = mymap.find(mykey)
if (it == mymap.end())
{
    //return error code
    return ERROR_CODE;
}
else
{
    value = it->second;
    return SUCCESS_CODE;
}


问:
Read configuration using IOptions<Configuration>
I'm trying to read configuration with options pattern. I want to read a connection string from appsettings given IOptions<Configuration> as injection. I have tried so many ways, but I couldnt figure it out please help.

```<code>        private readonly Configuration _config;
        private readonly string _connectionString;

        public QueueClientFactory(IOptions<Configuration> config)
        {
            _config = config.Value;
            var _connectionString = _config.GetSection("Queue:ConnectionString").Get<string>(); //but this is not available in Configuration rather in IConfiguration
}
</code>```

答:
You should create a class to hold the configuration section you want to use in QueueClientFactory.

Assuming your settings.json looks something like this:

```<code>...
"AllowedHosts": "*",
"Queue": {
    "ConnectionString": "connection;string;here;",
    "OtherProperty": "Something"
}
...
</code>```

Create a model with matching names to bind to the configuration values:

```<code>public class QueueClientConfig
{
    public string ConnectionString { get; set; }
    // map any other properties you need
}
</code>```

And in your Startup.cs/Program.cs class:

```<code>public void ConfigureServices(IServiceCollection services)
{
    ...
    services.Configure<QueueClientConfig>(_configuration.GetSection("Queue"));
    ...
}
</code>```

Or if you're using .NET 6:

```<code>builder.Services.Configure<QueueClientConfig>(builder.Configuration.GetSection("Queue"));
</code>```

Then in the QueueClientFactory you can access the configuration values:

```<code>private readonly QueueClientConfig queueClientConfig;

public QueueClientFactory(IOptions<QueueClientConfig> options)
{
    queueClientConfig = options.Value;
}
</code>```

Alternatively, you should be able to pass IConfiguration to the factory and have DI handle it automatically:

```<code>private readonly IConfiguration _config;

public QueueClientFactory(IConfiguration config)
{
    _config = config;
    _connectionString = _config.GetSection("Queue:ConnectionString").Get<string>();
}
</code>```

Body:
I'm trying to read configuration with options pattern. I want to read a connection string from appsettings given IOptions<Configuration> as injection. I have tried so many ways, but I couldnt figure it out please help.

        private readonly Configuration _config;
        private readonly string _connectionString;

        public QueueClientFactory(IOptions<Configuration> config)
        {
            _config = config.Value;
            var _connectionString = _config.GetSection("Queue:ConnectionString").Get<string>(); //but this is not available in Configuration rather in IConfiguration
}

Body:
You should create a class to hold the configuration section you want to use in QueueClientFactory.

Assuming your settings.json looks something like this:

...
"AllowedHosts": "*",
"Queue": {
    "ConnectionString": "connection;string;here;",
    "OtherProperty": "Something"
}
...

Create a model with matching names to bind to the configuration values:

public class QueueClientConfig
{
    public string ConnectionString { get; set; }
    // map any other properties you need
}

And in your Startup.cs/Program.cs class:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.Configure<QueueClientConfig>(_configuration.GetSection("Queue"));
    ...
}

Or if you're using .NET 6:

builder.Services.Configure<QueueClientConfig>(builder.Configuration.GetSection("Queue"));

Then in the QueueClientFactory you can access the configuration values:

private readonly QueueClientConfig queueClientConfig;

public QueueClientFactory(IOptions<QueueClientConfig> options)
{
    queueClientConfig = options.Value;
}

Alternatively, you should be able to pass IConfiguration to the factory and have DI handle it automatically:

private readonly IConfiguration _config;

public QueueClientFactory(IConfiguration config)
{
    _config = config;
    _connectionString = _config.GetSection("Queue:ConnectionString").Get<string>();
}


问:
Convert an Array to Comma separated String in JOLT
I am trying to convert an array to comma separated string using jolt transform.
Is there a way to achieve this ?

```<code>{
    "scores": [
        "a",
        "b",
        "c",
        "d",
        "e"
    ]
}
</code>```

Expected Output

```<code>{
    "scores": "a,b,c,d,e"
}
</code>```

答:
You can use join with modify-overwrite-beta operation.

```<code>[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "scores": "=join(', ',@(1,scores))"
    }
  }
]
</code>```

Body:
I am trying to convert an array to comma separated string using jolt transform.
Is there a way to achieve this ?

{
    "scores": [
        "a",
        "b",
        "c",
        "d",
        "e"
    ]
}

Expected Output

{
    "scores": "a,b,c,d,e"
}

Body:
You can use join with modify-overwrite-beta operation.

[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "scores": "=join(', ',@(1,scores))"
    }
  }
]


问:
Intellitrace fails when debugging Cannot debug some of the code in process w3wp.exe
I've recently upgraded from VS2015 Professional Update 2 to VS2015 Enterprise Update 2.  The process was rather buggy.

First I attempted to upgrade directly from Pro Update 2 to Ent Update 1, as that was the media I had.  This provided all sorts of install errors.

C++ redistro install failed (version wrong),
Connected Services (package failed)
Azure Connected Services (package failed)

Eventually I completely uninstalled Pro & C++ redistros (x86 & 64), rebooted and installed a fresh copy of Enterprise.  Installation went better as C++ didn't fail.  However, it left me in the same boat, with this error every time I start the debugger.

I've tried everything I can find:
- Unchecking "Enable the Visual Studio hosting process"
- Many uninstalls and re-installs.

If I knew how to "disable debugging the failed type(s)"  I would.

The only successful solution I've seen so far was:
"I solved it!  Reinstall windows and VS!"

答: As for the most problems, restarting my PC solved the problem.</p>


问:
Dynamic handler assignment in useEffect does not show update state in the handler
Here is my example:

```<code>const App = () => {
  const [elements, setElements] = useState<{ text: string; onClick: () => any }[]>([])

  useEffect(() => setElements([
    {
      text: 'Click me',
      onClick: handleClick,
    }
  ]), []);

  const handleClick = () => {
    // I want to do something with elements here
    console.log(elements); // logs []
  }

  // Currently updated elements
  console.log(elements);

  return (
    <>
      {elements.map((e, i) => (
        <button key={i} onClick={e.onClick}>
          {e.text}
        </button>
      ))
      }
    </>
  )
};
</code>```

I marked problematic part of the code with comment. Can someone explain why is this not working? Thanks in advance.

答:
Your component's handleClick function will have many handleClick functions declared within it throughout its "lifetime". Each time your component re-renders (and on the initial mount), you're re-defining your handleClick function. This is because each re-render causes your component's body to run again. Each time your handleClick function is defined, it "remember"s the variables defined within its surrounding scope at the time it was defined, such as the elements array. This idea of where a function can access the variables defined within its scope that it was defined in is called a closure.

In your code, your useEffect is saving the "first version" of your handleClick function that was created on the initial mount of your component. At that point your elements state was empty and so that version of your handeClick function will use the empty version of the elements array in subsequent re-renders. This is because, in future renders when elements does have values, your object within elements will hold a handleClick function that refers back to the original handleClick function (which only knows about the empty elements array).

I'm not sure if I would advise storing functions in state, as it can lead to issues like you're getting. Instead, I would suggest removing the onClick property from your objects and passing your e element from the .map() callback into handleClick (that is if you need to use e specifically). If you do this, then handleClick will be the same one as defined for the current render you're on, which will allow you to access elements correctly. Or if you really want, you can pass elements through and not rely on the value from the surrounding scope that it was defined in (however, depending on your actual use for this, there might be a more react-y way of doing this):

const {useEffect, useState} = React;
const App = () => {
  const [elements, setElements] = useState([]);

  useEffect(() => setElements([
    {
      text: 'Click me',
      onClick: handleClick,
    }
  ]), []);

  const handleClick = (elements) => {
    console.log(elements);
  }

  // Currently updated elements
  console.log(elements);

  return (
    <React.Fragment>
      {elements.map((e, i) => (
        <button key={i} onClick={() => e.onClick(elements)}>
          {e.text}
        </button>
      ))
      }
    </React.Fragment>
  )
};
ReactDOM.render(<App />, document.body);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script></code>```

Body:
Here is my example:

const App = () => {
  const [elements, setElements] = useState<{ text: string; onClick: () => any }[]>([])

  useEffect(() => setElements([
    {
      text: 'Click me',
      onClick: handleClick,
    }
  ]), []);

  const handleClick = () => {
    // I want to do something with elements here
    console.log(elements); // logs []
  }

  // Currently updated elements
  console.log(elements);

  return (
    <>
      {elements.map((e, i) => (
        <button key={i} onClick={e.onClick}>
          {e.text}
        </button>
      ))
      }
    </>
  )
};

I marked problematic part of the code with comment. Can someone explain why is this not working? Thanks in advance.

Body:
Your component's handleClick function will have many handleClick functions declared within it throughout its "lifetime". Each time your component re-renders (and on the initial mount), you're re-defining your handleClick function. This is because each re-render causes your component's body to run again. Each time your handleClick function is defined, it "remember"s the variables defined within its surrounding scope at the time it was defined, such as the elements array. This idea of where a function can access the variables defined within its scope that it was defined in is called a closure.

In your code, your useEffect is saving the "first version" of your handleClick function that was created on the initial mount of your component. At that point your elements state was empty and so that version of your handeClick function will use the empty version of the elements array in subsequent re-renders. This is because, in future renders when elements does have values, your object within elements will hold a handleClick function that refers back to the original handleClick function (which only knows about the empty elements array).

I'm not sure if I would advise storing functions in state, as it can lead to issues like you're getting. Instead, I would suggest removing the onClick property from your objects and passing your e element from the .map() callback into handleClick (that is if you need to use e specifically). If you do this, then handleClick will be the same one as defined for the current render you're on, which will allow you to access elements correctly. Or if you really want, you can pass elements through and not rely on the value from the surrounding scope that it was defined in (however, depending on your actual use for this, there might be a more react-y way of doing this):

const {useEffect, useState} = React;
const App = () => {
  const [elements, setElements] = useState([]);

  useEffect(() => setElements([
    {
      text: 'Click me',
      onClick: handleClick,
    }
  ]), []);

  const handleClick = (elements) => {
    console.log(elements);
  }

  // Currently updated elements
  console.log(elements);

  return (
    <React.Fragment>
      {elements.map((e, i) => (
        <button key={i} onClick={() => e.onClick(elements)}>
          {e.text}
        </button>
      ))
      }
    </React.Fragment>
  )
};
ReactDOM.render(<App />, document.body);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>


问:
ASP.NET Core - Get tuple with two values
I just want to get the user's role and ID from the user table. But I do not know why the following code gives an error!!!

public Tuple<Guid,Guid> GetUserId(string mobile)
{
    return _context.Users.Select(u => new Tuple<Guid,Guid,Boolean>(u.UserId,u.RoleId,u.Mobile == mobile));
}
```

I searched a lot but did not find an answer?

Error:

答:
You have problem with your method defíntion.
Your method's return type is
Tuple<Guid,Guid>  but you returnig values as Tuple<Guid,Guid,Boolean>  which it is not matching.

Just update the method return tpye tupple as:

```<code>public Tuple<Guid,Guid, Boolean> GetUserId(string mobile)
{
    return _context.Users.Select(u => new Tuple<Guid,Guid,Boolean>(u.UserId,u.RoleId,u.Mobile == mobile));
}
</code>```

Body:
I just want to get the user's role and ID from the user table. But I do not know why the following code gives an error!!!

public Tuple<Guid,Guid> GetUserId(string mobile)
{
    return _context.Users.Select(u => new Tuple<Guid,Guid,Boolean>(u.UserId,u.RoleId,u.Mobile == mobile));
}

I searched a lot but did not find an answer?

Error:

Body:
You have problem with your method defíntion.
Your method's return type is
Tuple<Guid,Guid>  but you returnig values as Tuple<Guid,Guid,Boolean>  which it is not matching.

Just update the method return tpye tupple as:

public Tuple<Guid,Guid, Boolean> GetUserId(string mobile)
{
    return _context.Users.Select(u => new Tuple<Guid,Guid,Boolean>(u.UserId,u.RoleId,u.Mobile == mobile));
}


问:
Changing markersize in geodataframeplot gives unexpected input error for plot(markersize=1)
I would like to plot similar data from separate (similar) using geodataframeplot. To improve the plot the markersize needs to be decreased for all points.

```<code>base=dbf['geometry'].plot(figsize = (10,10))
plt.tight_layout()

# Create user-defined bins
bins = [0.5,0.6,0.7,0.8,0.9,1.0]
ax2 = base
# Classify data with user-defined bins
q1 = mc.UserDefined(dbf1['column_1'], bins)
q2 = mc.UserDefined(dbf2['column_1'], bins)
q3 = mc.UserDefined(dbf3['column_1'], bins)
q4 = mc.UserDefined(dbf4['column_1'], bins)

# Plot data with user-difened bins
q1.plot(PS_Radarsat2, ax = ax2, legend = True, cmap="YlOrRd")
q2.plot(PS_Sentinel1_asc1, ax=ax2, legend = False, cmap = "YlOrRd")
q3.plot(PS_Sentinel1_asc2, ax=ax2, legend = False, cmap = "YlOrRd")
q4.plot(PS_Sentinel1_dsc1_IW1, ax=ax2, legend = False, cmap = "YlOrRd")
</code>```

The code above works well, but unlike other instances, the plot(markersize=1) results in an unexpected input argument for .plot(). Is it possible to change the markersize while using a colormap argument?

答:
you have not provided data / MWE.  So used natural earth to simulate

markersize does not apply to polygons, so it's not completely clear what you are trying to achieve with it

clearly the centroid of a polygon in a point.  This can be plotted as a marker with a marker size on the figure.

```<code>import geopandas as gpd
import matplotlib.pyplot as plt
import mapclassify as mc
import numpy as np

# need to know countries that make up natural earth...
dbf = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))

base=dbf['geometry'].plot(figsize = (10,10))
plt.tight_layout()

dbf["column_1"] = np.random.uniform(0.4,1, len(dbf))
dbf1 = dbf.sample(10)
dbf2 = dbf.sample(10)
dbf3 = dbf.sample(10)
dbf4 = dbf.sample(10)
PS_Radarsat2 = dbf1
PS_Sentinel1_asc1 = dbf2
PS_Sentinel1_asc2 = dbf3
PS_Sentinel1_dsc1_IW1 = dbf4

# Create user-defined bins
bins = [0.5,0.6,0.7,0.8,0.9,1.0]
ax2 = base
# Classify data with user-defined bins
q1 = mc.UserDefined(dbf1['column_1'], bins)
q2 = mc.UserDefined(dbf2['column_1'], bins)
q3 = mc.UserDefined(dbf3['column_1'], bins)
q4 = mc.UserDefined(dbf4['column_1'], bins)

# # Plot data with user-difened bins
q1.plot(PS_Radarsat2, ax = ax2, legend = True, cmap="YlOrRd")
q2.plot(PS_Sentinel1_asc1, ax=ax2, legend = False, cmap = "YlOrRd")
q3.plot(PS_Sentinel1_asc2, ax=ax2, legend = False, cmap = "YlOrRd")
q4.plot(PS_Sentinel1_dsc1_IW1, ax=ax2, legend = False, cmap = "YlOrRd")

dbf1["geometry"].centroid.plot(ax=ax2, markersize=300, color="pink")
dbf2["geometry"].centroid.plot(ax=ax2, markersize=200, color="green")
dbf3["geometry"].centroid.plot(ax=ax2, markersize=100, color="yellow")
dbf4["geometry"].centroid.plot(ax=ax2, markersize=50, color="orange")
</code>```

Body:
I would like to plot similar data from separate (similar) using geodataframeplot. To improve the plot the markersize needs to be decreased for all points.

base=dbf['geometry'].plot(figsize = (10,10))
plt.tight_layout()

# Create user-defined bins
bins = [0.5,0.6,0.7,0.8,0.9,1.0]
ax2 = base
# Classify data with user-defined bins
q1 = mc.UserDefined(dbf1['column_1'], bins)
q2 = mc.UserDefined(dbf2['column_1'], bins)
q3 = mc.UserDefined(dbf3['column_1'], bins)
q4 = mc.UserDefined(dbf4['column_1'], bins)

# Plot data with user-difened bins
q1.plot(PS_Radarsat2, ax = ax2, legend = True, cmap="YlOrRd")
q2.plot(PS_Sentinel1_asc1, ax=ax2, legend = False, cmap = "YlOrRd")
q3.plot(PS_Sentinel1_asc2, ax=ax2, legend = False, cmap = "YlOrRd")
q4.plot(PS_Sentinel1_dsc1_IW1, ax=ax2, legend = False, cmap = "YlOrRd")

The code above works well, but unlike other instances, the plot(markersize=1) results in an unexpected input argument for .plot(). Is it possible to change the markersize while using a colormap argument?

Body:
you have not provided data / MWE.  So used natural earth to simulate

markersize does not apply to polygons, so it's not completely clear what you are trying to achieve with it

clearly the centroid of a polygon in a point.  This can be plotted as a marker with a marker size on the figure.

import geopandas as gpd
import matplotlib.pyplot as plt
import mapclassify as mc
import numpy as np

# need to know countries that make up natural earth...
dbf = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))

base=dbf['geometry'].plot(figsize = (10,10))
plt.tight_layout()

dbf["column_1"] = np.random.uniform(0.4,1, len(dbf))
dbf1 = dbf.sample(10)
dbf2 = dbf.sample(10)
dbf3 = dbf.sample(10)
dbf4 = dbf.sample(10)
PS_Radarsat2 = dbf1
PS_Sentinel1_asc1 = dbf2
PS_Sentinel1_asc2 = dbf3
PS_Sentinel1_dsc1_IW1 = dbf4

# Create user-defined bins
bins = [0.5,0.6,0.7,0.8,0.9,1.0]
ax2 = base
# Classify data with user-defined bins
q1 = mc.UserDefined(dbf1['column_1'], bins)
q2 = mc.UserDefined(dbf2['column_1'], bins)
q3 = mc.UserDefined(dbf3['column_1'], bins)
q4 = mc.UserDefined(dbf4['column_1'], bins)

# # Plot data with user-difened bins
q1.plot(PS_Radarsat2, ax = ax2, legend = True, cmap="YlOrRd")
q2.plot(PS_Sentinel1_asc1, ax=ax2, legend = False, cmap = "YlOrRd")
q3.plot(PS_Sentinel1_asc2, ax=ax2, legend = False, cmap = "YlOrRd")
q4.plot(PS_Sentinel1_dsc1_IW1, ax=ax2, legend = False, cmap = "YlOrRd")

dbf1["geometry"].centroid.plot(ax=ax2, markersize=300, color="pink")
dbf2["geometry"].centroid.plot(ax=ax2, markersize=200, color="green")
dbf3["geometry"].centroid.plot(ax=ax2, markersize=100, color="yellow")
dbf4["geometry"].centroid.plot(ax=ax2, markersize=50, color="orange")


问:
How the define parser rule for empty array in Antlr 4.0
I have the following set of rules in my Antlr grammar file:

```<code>//myidl.g4

grammar myidl;

integerLiteral:
    value = DecimalLiteral # decimalNumberExpr
    | value = HexadecimalLiteral # hexadecimalNumberExpr
    ;

DecimalLiteral: DIGIT+;

HexadecimalLiteral: ('0x' | '0X') HEXADECIMALDIGIT+;

fragment DIGIT: [0-9];

fragment HEXADECIMALDIGIT: [0-9a-fA-F];

array:
    '[' ( integerLiteral ( ',' integerLiteral )* )* ']' // how to allow empty arrays like "[]"?
    ;
</code>```

The resulting parser works fine for arrays with elements, for example "[0x00]".
But when defining an empty array "[]", i get the error:
no viable alternative at input '[]'

The funny thing is that when defining the empty array with a space, like "[ ]", the parser eats it without error. Can somebody tell me whats wrong with my rules, and how to adjust the rules to allow empty arrays definition without spaces, "[]"?

I use ANTLR Parser Generator  Version 4.9.2

EDIT:
It turns out that I was using an old version of the parser due to configuration issue. |=( The above rules work just fine.

答:
You probably have defined a token in your lexer grammar that matches []:

```<code>SOME_RULE
 : '[]'
 ;
</code>```

remove that rule.

Body:
I have the following set of rules in my Antlr grammar file:

//myidl.g4

grammar myidl;

integerLiteral:
    value = DecimalLiteral # decimalNumberExpr
    | value = HexadecimalLiteral # hexadecimalNumberExpr
    ;

DecimalLiteral: DIGIT+;

HexadecimalLiteral: ('0x' | '0X') HEXADECIMALDIGIT+;

fragment DIGIT: [0-9];

fragment HEXADECIMALDIGIT: [0-9a-fA-F];

array:
    '[' ( integerLiteral ( ',' integerLiteral )* )* ']' // how to allow empty arrays like "[]"?
    ;

The resulting parser works fine for arrays with elements, for example "[0x00]".
But when defining an empty array "[]", i get the error:
no viable alternative at input '[]'

The funny thing is that when defining the empty array with a space, like "[ ]", the parser eats it without error. Can somebody tell me whats wrong with my rules, and how to adjust the rules to allow empty arrays definition without spaces, "[]"?

I use ANTLR Parser Generator  Version 4.9.2

EDIT:
It turns out that I was using an old version of the parser due to configuration issue. |=( The above rules work just fine.

Body:
You probably have defined a token in your lexer grammar that matches []:

SOME_RULE
 : '[]'
 ;

remove that rule.


问:
Is there a way to clear all data within a CSV file in order to fill it up again with new data?
I am trying to create an IOT weather station where in a Python file it would receive data from a temperature sensor and save it in a CSV along with the second(s) it was received.

Since this is going to be plotted in a graph in real time, I can't have it save new data without clearing the CSV file out first since if I did, the line in the graph will overlap, because of the eventual repetition of seconds in the CSV file.

This is a sample of what is saved in the CSV file:

Celcius,Time
56,20.50
57,20.50
58,20.50
59,20.50
00,20.50
```
<p>I want the code to clear the CSV file once the seconds reach 60 (or 00), so it can be repopulated with new data.</p>
<p>This is what I have come up with so far:</p>
```with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'a') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    info = {
        "Time": secondsNow[2],
        "Celcius": secondsNow[2]
    }
    if (secondsNow[2] == "00"):
        print("CLEAR CLEAR CLEAR")
        csv_file.close()
    else:
        csv_writer.writerow(info)
```

答: When you open a csv file in python and write something into, it automatically overwrites what was already written in the file.</p>

Body:
I am trying to create an IOT weather station where in a Python file it would receive data from a temperature sensor and save it in a CSV along with the second(s) it was received.

Since this is going to be plotted in a graph in real time, I can't have it save new data without clearing the CSV file out first since if I did, the line in the graph will overlap, because of the eventual repetition of seconds in the CSV file.

This is a sample of what is saved in the CSV file:

Celcius,Time
56,20.50
57,20.50
58,20.50
59,20.50
00,20.50

I want the code to clear the CSV file once the seconds reach 60 (or 00), so it can be repopulated with new data.

This is what I have come up with so far:

with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'a') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    info = {
        "Time": secondsNow[2],
        "Celcius": secondsNow[2]
    }
    if (secondsNow[2] == "00"):
        print("CLEAR CLEAR CLEAR")
        csv_file.close()
    else:
        csv_writer.writerow(info)


问:
CMDeviceMotion does not provide attitude info
For some reason my iPad2 is not providing motion attitude information. I am doing AFAIK precisely what people say to do but still... no data.

```<code>float angle = 0;
CMDeviceMotion *deviceMotion;
CMAttitude *attitude;
deviceMotion = motionManager.deviceMotion;
if (deviceMotion) {
    attitude = deviceMotion.attitude;

    [attitude multiplyByInverseOfAttitude:referenceAttitude];
    angle = [attitude roll];
} else {
    NSLog (@"Cannot get angles.");
}
</code>```

Earlier in my code I do this:

```<code>    motionManager = [[CMMotionManager alloc] init];
    if (motionManager.gyroAvailable) {
        [motionManager startGyroUpdates];
    }
</code>```

However I never get the angle. Help?

答:
You only get attitude if you use device motion updates, i.e. you have to call for initialisaiton:

```<code>if (![motionManager isDeviceMotionActive]) {
    [motionManager startDeviceMotionUpdates];
}
</code>```

And stopDeviceMotionUpdates when going to background.

Body:
For some reason my iPad2 is not providing motion attitude information. I am doing AFAIK precisely what people say to do but still... no data.

float angle = 0;
CMDeviceMotion *deviceMotion;
CMAttitude *attitude;
deviceMotion = motionManager.deviceMotion;
if (deviceMotion) {
    attitude = deviceMotion.attitude;

    [attitude multiplyByInverseOfAttitude:referenceAttitude];
    angle = [attitude roll];
} else {
    NSLog (@"Cannot get angles.");
}

Earlier in my code I do this:

    motionManager = [[CMMotionManager alloc] init];
    if (motionManager.gyroAvailable) {
        [motionManager startGyroUpdates];
    }

However I never get the angle. Help?

Body:
You only get attitude if you use device motion updates, i.e. you have to call for initialisaiton:

if (![motionManager isDeviceMotionActive]) {
    [motionManager startDeviceMotionUpdates];
}

And stopDeviceMotionUpdates when going to background.


答:
You need to calculate the difference between the consecutive IN's and OUT's. This can be done by joining the table with itself and get the rows where row number difference is 1.

Please try the postgres sql query below:

```<code>WITH student_cte AS (
    SELECT
        stuId,
        actions,
        recorded,
        row_number() over (partition by stuId order by recorded) as rn
    FROM
        student
)
select c1.stuId as StuID, SUM((COALESCE(c2.recorded, now()::timestamp) - c1.recorded)) as total_in_duration
FROM
student_cte c1
  LEFT JOIN
student_cte c2
on c1.stuId = c2.stuId and c1.rn + 1 = c2.rn
where c1.actions='IN'
GROUP BY c1.stuId;
</code>```

Title: Calculating total Hour spent by student in class room using PostgreSQL

Body:
A classroom records its student movement IN and Out of the classroom in a table as shown below:

+-------+---------+---------------------+
| stuId | actions | recorded            |
+-------+---------+---------------------+
| 1     | IN      | 2021-05-01 10:00:00 |
+-------+---------+---------------------+
| 1     | OUT     | 2021-05-01 14:00:00 |
+-------+---------+---------------------+
| 1     | IN      | 2021-05-01 16:00:00 |
+-------+---------+---------------------+
| 1     | OUT     | 2021-05-01 20:00:00 |
+-------+---------+---------------------+
| 2     | IN      | 2021-05-01 09:00:00 |
+-------+---------+---------------------+
| 2     | OUT     | 2021-05-01 13:00:00 |
+-------+---------+---------------------+
| 2     | IN      | 2021-05-01 15:00:00 |
+-------+---------+---------------------+

We have to calculate the amount of hour spent by each student inside the classroom.

Also, for student 2 the last action is 'IN'. So, that student is still studying inside the class. So we have to add this hour also while the student is still studying. We can use current time to calculate it.

What is the proper way to solve this problem statement?

Body:
You need to calculate the difference between the consecutive IN's and OUT's. This can be done by joining the table with itself and get the rows where row number difference is 1.

Please try the postgres sql query below:

WITH student_cte AS (
    SELECT
        stuId,
        actions,
        recorded,
        row_number() over (partition by stuId order by recorded) as rn
    FROM
        student
)
select c1.stuId as StuID, SUM((COALESCE(c2.recorded, now()::timestamp) - c1.recorded)) as total_in_duration
FROM
student_cte c1
  LEFT JOIN
student_cte c2
on c1.stuId = c2.stuId and c1.rn + 1 = c2.rn
where c1.actions='IN'
GROUP BY c1.stuId;


问:
Why is it faster to create a list of classes than a list of list of integers in C#?
Backgorund

Hi,

I am creating a game where the AI is collecting possible moves from positions which is done millions of times per turn. I am trying to figure out the fastest way to store these moves containing e.g. pieceFromSquare, pieceToSquare and other move related things.

Currently I have a Move class which contains public variables for the move as per below:

```<code>public class Move
{
    public int FromSquare;
    public int ToSquare;
    public int MoveType;

    public static Move GetMove(int fromSquare, int toSquare, int moveType)
    {
        Move move = new Move();

        move.FromSquare = fromSquare;
        move.ToSquare = toSquare;
        move.MoveType = moveType;

        return move;
    }
}
</code>```

When the AI finds a move it stores the move in a List. I was thinking if it would be faster to store the move as a list of integers instead so I ran a test:

Test

```<code>public void RunTimerTest()
    {
        // Function A
        startTime = DateTime.UtcNow;
        moveListA = new List<List<int>>();
        for (int i = 0; i < numberOfIterations; i++)
        {
            FunctionA();
        }
        PrintResult((float)Math.Round((DateTime.UtcNow - startTime).TotalSeconds, 2), "Function A");

        // Function B
        startTime = DateTime.UtcNow;
        moveListB = new List<Move>();
        for (int i = 0; i < numberOfIterations; i++)
        {
            FunctionB();
        }
        PrintResult((float)Math.Round((DateTime.UtcNow - startTime).TotalSeconds, 2), "Function B");
    }

    private void FunctionA()
    {
        moveListA.Add(new List<int>() { 1, 123, 10});
    }

    private void FunctionB()
    {
        moveListB.Add(Move.GetMove(1, 123, 10));
    }
</code>```

The test results in the following result when running over 10 million times:

Function A ran for: 4,58 s.

Function B ran for: 1,47 s.

So it is more than 3 times faster to create the class and populate its variables than to create a list of integers.

Questions

Why is it so much faster to create a class than a list of integers?

Is there an even faster way to store this type of data?

答:
As mentioned in the comments, the reasons are probably mostly due to the list example needing to allocate at least two objects, possibly more depending on how it is optimized.

For high performance code a common guideline is to avoid high frequency allocations. While allocations in c# are fast, they still take some time to manage. This often means sticking with fixed size arrays, or at least set the capacity of any lists on creation.

Another important point is using structs, they are stored directly in the list/array, instead of storing a reference to a separate object. This avoids some object overhead, removes the memory need of a separate reference, and ensures all values are stored sequentially in memory. All of this help ensure caches are used efficiently. Using a smaller datatype like short/ushort may also help if that is possible. Note that structs should preferably be immutable, and there are some keywords like 'ref' and 'in' that can help avoid the overhead of copying data.

In some specific cases it can be an idea to separate values into different arrays, i.e. one for all the FromSquare values, one for all the ToSquare values etc. This can be a benefit if an operation mostly uses only a single value, again benefiting from better cache usage. It might also make SIMD easier to apply, but that might not apply in this case.

Moreover, when when measuring performance, at least use a stopwatch. That is much more accurate than dateTime, and no harder to use. Benchmark.Net would be even better since that helps compensate for various sources of noise, and can benchmark for multiple platforms. A good profiler can also be useful since it can give hints at what takes most time, how much you are allocating etc.

Body:
Backgorund

Hi,

I am creating a game where the AI is collecting possible moves from positions which is done millions of times per turn. I am trying to figure out the fastest way to store these moves containing e.g. pieceFromSquare, pieceToSquare and other move related things.

Currently I have a Move class which contains public variables for the move as per below:

public class Move
{
    public int FromSquare;
    public int ToSquare;
    public int MoveType;

    public static Move GetMove(int fromSquare, int toSquare, int moveType)
    {
        Move move = new Move();

        move.FromSquare = fromSquare;
        move.ToSquare = toSquare;
        move.MoveType = moveType;

        return move;
    }
}

When the AI finds a move it stores the move in a List. I was thinking if it would be faster to store the move as a list of integers instead so I ran a test:

Test

public void RunTimerTest()
    {
        // Function A
        startTime = DateTime.UtcNow;
        moveListA = new List<List<int>>();
        for (int i = 0; i < numberOfIterations; i++)
        {
            FunctionA();
        }
        PrintResult((float)Math.Round((DateTime.UtcNow - startTime).TotalSeconds, 2), "Function A");

        // Function B
        startTime = DateTime.UtcNow;
        moveListB = new List<Move>();
        for (int i = 0; i < numberOfIterations; i++)
        {
            FunctionB();
        }
        PrintResult((float)Math.Round((DateTime.UtcNow - startTime).TotalSeconds, 2), "Function B");
    }

    private void FunctionA()
    {
        moveListA.Add(new List<int>() { 1, 123, 10});
    }

    private void FunctionB()
    {
        moveListB.Add(Move.GetMove(1, 123, 10));
    }

The test results in the following result when running over 10 million times:

Function A ran for: 4,58 s.

Function B ran for: 1,47 s.

So it is more than 3 times faster to create the class and populate its variables than to create a list of integers.

Questions

Why is it so much faster to create a class than a list of integers?

Is there an even faster way to store this type of data?