问:
Allow only two decimal number in flutter input?
I want only two digits after the decimal point in the flutter input.User can't add more than two digits after the decimal point.

答:
This worked for me (Feb/2022)

Restricts the text to 2 decimal point and have only 1 '.' (period)

0 will be automatically added to the start of the number if user go and manually remove the digit before the '.'

PS: A Slight edit to the answer

TextFormField

```<code>TextFormField(
          autofocus: false,
          keyboardType: TextInputType.number,
          controller: controller,
          inputFormatters: [
            DecimalTextInputFormatter(decimalRange: 2),
          ],
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please add amount.';
            }
            return null;
          },
</code>```

DecimalTextInputFormatter

```<code>import 'package:flutter/services.dart';
import 'dart:math' as math;

class DecimalTextInputFormatter extends TextInputFormatter {
  DecimalTextInputFormatter({required this.decimalRange})
      : assert(decimalRange > 0);

  final int decimalRange;

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    TextSelection newSelection = newValue.selection;
    String truncated = newValue.text;

    String value = newValue.text;

    if (value.contains(".") &&
        value.substring(value.indexOf(".") + 1).length > decimalRange) {
      truncated = oldValue.text;
      newSelection = oldValue.selection;
    } else if (value == ".") {
      truncated = "0.";

      newSelection = newValue.selection.copyWith(
        baseOffset: math.min(truncated.length, truncated.length + 1),
        extentOffset: math.min(truncated.length, truncated.length + 1),
      );
    } else if (value.contains(".")) {
      String tempValue = value.substring(value.indexOf(".") + 1);
      if (tempValue.contains(".")) {
        truncated = oldValue.text;
        newSelection = oldValue.selection;
      }
      if (value.indexOf(".") == 0) {
        truncated = "0" + truncated;
        newSelection = newValue.selection.copyWith(
          baseOffset: math.min(truncated.length, truncated.length + 1),
          extentOffset: math.min(truncated.length, truncated.length + 1),
        );
      }
    }
    if (value.contains(" ") || value.contains("-")) {
      truncated = oldValue.text;
      newSelection = oldValue.selection;
    }

    return TextEditingValue(
      text: truncated,
      selection: newSelection,
      composing: TextRange.empty,
    );
  }
}
</code>```

Body:
This worked for me (Feb/2022)

Restricts the text to 2 decimal point and have only 1 '.' (period)

0 will be automatically added to the start of the number if user go and manually remove the digit before the '.'

PS: A Slight edit to the answer

TextFormField

TextFormField(
          autofocus: false,
          keyboardType: TextInputType.number,
          controller: controller,
          inputFormatters: [
            DecimalTextInputFormatter(decimalRange: 2),
          ],
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please add amount.';
            }
            return null;
          },

DecimalTextInputFormatter

import 'package:flutter/services.dart';
import 'dart:math' as math;

class DecimalTextInputFormatter extends TextInputFormatter {
  DecimalTextInputFormatter({required this.decimalRange})
      : assert(decimalRange > 0);

  final int decimalRange;

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    TextSelection newSelection = newValue.selection;
    String truncated = newValue.text;

    String value = newValue.text;

    if (value.contains(".") &&
        value.substring(value.indexOf(".") + 1).length > decimalRange) {
      truncated = oldValue.text;
      newSelection = oldValue.selection;
    } else if (value == ".") {
      truncated = "0.";

      newSelection = newValue.selection.copyWith(
        baseOffset: math.min(truncated.length, truncated.length + 1),
        extentOffset: math.min(truncated.length, truncated.length + 1),
      );
    } else if (value.contains(".")) {
      String tempValue = value.substring(value.indexOf(".") + 1);
      if (tempValue.contains(".")) {
        truncated = oldValue.text;
        newSelection = oldValue.selection;
      }
      if (value.indexOf(".") == 0) {
        truncated = "0" + truncated;
        newSelection = newValue.selection.copyWith(
          baseOffset: math.min(truncated.length, truncated.length + 1),
          extentOffset: math.min(truncated.length, truncated.length + 1),
        );
      }
    }
    if (value.contains(" ") || value.contains("-")) {
      truncated = oldValue.text;
      newSelection = oldValue.selection;
    }

    return TextEditingValue(
      text: truncated,
      selection: newSelection,
      composing: TextRange.empty,
    );
  }
}


来源: stackexchange

问:
Difference in months between dates with different rows (same identifier) (in R)
```<code>
 cpf sep_month hire_month hire_year sep_day  hire_date   sep_date
4 123         4          2      2012       1 2012-02-01 2013-04-01
5 123         0          4      2013       1 2013-04-01       <NA>
6 122        10          9      2012       1 2012-09-01 2013-10-01
7 122         0         12      2013       1 2013-12-01       <NA>

structure(list(cpf = c(123L, 123L, 122L, 122L), sep_month = c(4L,
0L, 10L, 0L), hire_month = c(2L, 4L, 9L, 12L), hire_year = c(2012L,
2013L, 2012L, 2013L), sep_day = c(1L, 1L, 1L, 1L), hire_date = structure(c(15371,
15796, 15584, 16040), class = "Date"), sep_date = structure(c(15796,
NA, 15979, NA), class = "Date")), row.names = 4:7, class = "data.frame")

</code>```

In my dataset, each row is a job contract. I want to see the difference in months between sep_date and hire_date across different rows for the same CPF (identifier).
For example, individual 123 separated from its job on 2013-04. On the following row, he was hired (under a different contract/job) on 2013-04. My goal is to create a dummy equal to 1 for individuals who separated from a contract and found a job in the same or following month. That would be the case for individual 123, but not for individual 122.

I appreciate any help.

答:
dplyr

library(dplyr)
dat %>%
  group_by(cpf) %>%
  mutate(dummy = sapply(sep_date, function(z) any(!is.na(z) & z <= hire_date))) %>%
  ungroup()
# # A tibble: 4 x 8
#     cpf sep_month hire_month hire_year sep_day hire_date  sep_date   dummy
#   <int>     <int>      <int>     <int>   <int> <date>     <date>     <lgl>
# 1   123         4          2      2012       1 2012-02-01 2013-04-01 TRUE
# 2   123         0          4      2013       1 2013-04-01 NA         FALSE
# 3   122        10          9      2012       1 2012-09-01 2013-10-01 TRUE
# 4   122         0         12      2013       1 2013-12-01 NA         FALSE
```
<p>If you want <code>dummy</code> to be truly just <code>1</code>s and <code>0</code>s, then add a <code>+</code> before it, as in <code>dummy = +sapply(...)</code> (<code>+</code> is a shortcut to convert <code>logical</code> to <code>integer</code>).</p>
<h2>base R</h2>
<pre class="lang-r prettyprint-override"><code>dat$dummy <- ave(
  seq_along(dat$cpf), dat$cpf,
  FUN = function(i) sapply(dat$sep_date[i], function(z) any(!is.na(z) & z <= dat$hire_date[i])))
dat
#   cpf sep_month hire_month hire_year sep_day  hire_date   sep_date dummy
# 4 123         4          2      2012       1 2012-02-01 2013-04-01     1
# 5 123         0          4      2013       1 2013-04-01       <NA>     0
# 6 122        10          9      2012       1 2012-09-01 2013-10-01     1
# 7 122         0         12      2013       1 2013-12-01       <NA>     0
</code>```

This is a little uglier because ave doesn't like doing multi-column (multi-vector) stuff, but it gets the same results.

ContentLicense: CC BY-SA 4.0

Body:
 cpf sep_month hire_month hire_year sep_day  hire_date   sep_date
4 123         4          2      2012       1 2012-02-01 2013-04-01
5 123         0          4      2013       1 2013-04-01       <NA>
6 122        10          9      2012       1 2012-09-01 2013-10-01
7 122         0         12      2013       1 2013-12-01       <NA>

structure(list(cpf = c(123L, 123L, 122L, 122L), sep_month = c(4L,
0L, 10L, 0L), hire_month = c(2L, 4L, 9L, 12L), hire_year = c(2012L,
2013L, 2012L, 2013L), sep_day = c(1L, 1L, 1L, 1L), hire_date = structure(c(15371,
15796, 15584, 16040), class = "Date"), sep_date = structure(c(15796,
NA, 15979, NA), class = "Date")), row.names = 4:7, class = "data.frame")

In my dataset, each row is a job contract. I want to see the difference in months between sep_date and hire_date across different rows for the same CPF (identifier).
For example, individual 123 separated from its job on 2013-04. On the following row, he was hired (under a different contract/job) on 2013-04. My goal is to create a dummy equal to 1 for individuals who separated from a contract and found a job in the same or following month. That would be the case for individual 123, but not for individual 122.

I appreciate any help.

Body:
dplyr

library(dplyr)
dat %>%
  group_by(cpf) %>%
  mutate(dummy = sapply(sep_date, function(z) any(!is.na(z) & z <= hire_date))) %>%
  ungroup()
# # A tibble: 4 x 8
#     cpf sep_month hire_month hire_year sep_day hire_date  sep_date   dummy
#   <int>     <int>      <int>     <int>   <int> <date>     <date>     <lgl>
# 1   123         4          2      2012       1 2012-02-01 2013-04-01 TRUE
# 2   123         0          4      2013       1 2013-04-01 NA         FALSE
# 3   122        10          9      2012       1 2012-09-01 2013-10-01 TRUE
# 4   122         0         12      2013       1 2013-12-01 NA         FALSE

If you want dummy to be truly just 1s and 0s, then add a + before it, as in dummy = +sapply(...) (+ is a shortcut to convert logical to integer).

base R

dat$dummy <- ave(
  seq_along(dat$cpf), dat$cpf,
  FUN = function(i) sapply(dat$sep_date[i], function(z) any(!is.na(z) & z <= dat$hire_date[i])))
dat
#   cpf sep_month hire_month hire_year sep_day  hire_date   sep_date dummy
# 4 123         4          2      2012       1 2012-02-01 2013-04-01     1
# 5 123         0          4      2013       1 2013-04-01       <NA>     0
# 6 122        10          9      2012       1 2012-09-01 2013-10-01     1
# 7 122         0         12      2013       1 2013-12-01       <NA>     0

This is a little uglier because ave doesn't like doing multi-column (multi-vector) stuff, but it gets the same results.


问:
What IDE should I use for Linux module development?
I have Ubuntu 11.04 and am looking to start developing Linux modules. I use Visual Studio for C development in Windows, but I guess that's not an option for Linux. What would be a good IDE to work Linux modules ?</p>

答: Eclipse + CDT + at least a dual core processor and some Go of RAM and it will be a great adventure to navigate into the kernel sources.</p>

ContentLicense: CC BY-SA 3.0


答:
```<code>SELECT
        a.id,
        b.transdate,
        DATE_PART('day', b.transdate - a.datefrom) "B Value",
        DATE_PART('day', a.dateto - a.datefrom) "A Value",
        (DATE_PART('day', a.dateto - a.datefrom) * DATE_PART('day', b.transdate - a.datefrom)) "AxB Value"
FROM table_a a
JOIN table_b b ON a.id = b.id
</code>```

In PostgreSQL, if you subtract one datetime value from another you will get an INTERVAL in the form ddd days hh:mi:ss. You can then use the DATE_PART function to extract the number of full days in the interval.

Title: Get Value in Date Range with date parameter

Body:
Given 2 tables:

Table A

|id|datefrom  |dateto     |value|
|--|--------  |------     |-----|
|1 |2021-01-01|2021-01-07 |   7 |
|2 |2021-01-08|2021-01-15 |   9 |
|3 |2021-01-16|2021-01-23 |   4 |

Table B

|id|transdate  |value|
|--|--------   |-----|
|1 |2021-01-03 |   3 |
|2 |2021-01-10 |   6 |
|3 |2021-01-20 |   3 |

I want to produce the following View:

|id|transdate |B Value | A Value| AxB Value |
|--|--------- |--------|--------|-----------|
|1 |2021-01-03|    3   |    7   |     21    |
|2 |2021-01-10|    6   |    9   |     54    |
|3 |2021-01-20|    3   |    4   |     12    |

My Question, how to get Table A Value inside of that view, based on that transaction date within Table A Date From and Date To?

Body:
SELECT
        a.id,
        b.transdate,
        DATE_PART('day', b.transdate - a.datefrom) "B Value",
        DATE_PART('day', a.dateto - a.datefrom) "A Value",
        (DATE_PART('day', a.dateto - a.datefrom) * DATE_PART('day', b.transdate - a.datefrom)) "AxB Value"
FROM table_a a
JOIN table_b b ON a.id = b.id

In PostgreSQL, if you subtract one datetime value from another you will get an INTERVAL in the form ddd days hh:mi:ss. You can then use the DATE_PART function to extract the number of full days in the interval.


问:
npm Install : unable to resolve dependency tree
Eveytime i try npm install i go this errors it is a boilerplate project is downloaded from : https://aspnetboilerplate.com/Templates.
I cant generate node_modules folder or start the server it s only on these boilerpart projects.any suggestions please im really tired.
here is a screenshot of the issue issue Screenshot

also here is some versions of my environment:

```<code>npm: '8.3.1',node: '16.14.0',Angular CLI: 13.2.3

>   Package                      Version
> ------------------------------------------------------ @angular-devkit/architect    0.1302.3 (cli-only) @angular-devkit/core
> 13.2.3 (cli-only) @angular-devkit/schematics   13.2.3 (cli-only) @schematics/angular          13.2.3 (cli-only)
</code>```

答:
The problem solved ! .It was after running npm install --legacy-peer-deps before getting the error again,a bunch of warnings were shown telling me that the project must use

npm version : 6.11.0 and node version >=14.0 so i had to switch into those older versions and it s done .

Body:
Eveytime i try npm install i go this errors it is a boilerplate project is downloaded from : https://aspnetboilerplate.com/Templates.
I cant generate node_modules folder or start the server it s only on these boilerpart projects.any suggestions please im really tired.
here is a screenshot of the issue issue Screenshot

also here is some versions of my environment:

npm: '8.3.1',node: '16.14.0',Angular CLI: 13.2.3

>   Package                      Version
> ------------------------------------------------------ @angular-devkit/architect    0.1302.3 (cli-only) @angular-devkit/core
> 13.2.3 (cli-only) @angular-devkit/schematics   13.2.3 (cli-only) @schematics/angular          13.2.3 (cli-only)


问:
Dynamics 365 OData WebAPI request orderby child property not working?
I want to order the returned list based on a property from the child but I'm getting this error

{"error":{"code":"0x0","message":"Object reference not set to an instance of an object."}}

This request using the OOTB opportunity and account table gives me the error

https://xxx.api.crm.dynamics.com/api/data/v9.2/opportunities?$expand=parentaccountid&$top=5&$orderby=parentaccountid/name

I want to get a list of opportunities sorted by the associated account's name. Is this possible to do? Did I not have the right syntax?

答:
At least to my knowledge you cannot sort on related properties, the orderby clause only works with the properties of the main table you are fetching.

You can use it inside the expand clause, something like $expand=parentaccountid($orderby=name), but the order in this case is applied only to the expanded records (so it's useful more in a 1:N relationship) and not to the main records.


问:
Access Denied performing PUT file using S3 pre-signed URL
Problem: How can I successfully perform a PUT file request to a pre-signed URL where the bucket has the following permissions:

Block public access = off for all 4 options

Access Control List = Public Read

Bucket Policy = empty

CORS Configuration = PUT

Here is a concrete example of what I did...

I performed a POST to my presign endpoint...

```<code>> POST /dev/presign HTTP/2
> Host: 9xugkdzvch.execute-api.ap-southeast-1.amazonaws.com
> user-agent: insomnia/2020.2.2
> content-type: application/json
> accept: */*
> content-length: 51

* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!

| {
|   "name": "profile_1.png",
|   "type": "image/png"
| }
</code>```

it returned

```<code>{
  "statusCode": 200,
  "headers": {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Credentials": true
  },
  "body": {
    "error": false,
    "data": "https://profilephoto-upload-dev.s3.ap-southeast-1.amazonaws.com/profiles/profile_1.png?AWSAccessKeyId=ASIA4IWFXQ2GLT2FGUUA&Content-Type=image%2Fpng&Expires=1593475190&Signature=JO4pNtbXmb56OYiClZhil4hse0c%3D&x-amz-meta-username=foobar&x-amz-security-token=IQoJb3JpZ2luX2VjEIj%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaDmFwLXNvdXRoZWFzdC0xIkcwRQIhAP5kW%2Fj6Y5BiLgAhec3w6bv17CL8QuEabOy7hhhtK81JAiA7pS6IkGE3WtnIcD78%2BOytl1luSdLBkI9fg%2F2GzxpApirUBQghEAAaDDg0MzMwMjAxMjU1NiIMdbMwBimx3k0miN5lKrEFfUAFtMJep90tfYQqwW09Od1HTSaUKkVUqP0eOaQg89vEnplJ%2BCQwKopOF8Ed8AiFAFQ9qJcbtmg39wEqIBa5Z0oOdfDEphRXDmVWX%2BCQvdCCoPbbZeaK2tBg4PN2f%2FL8OBa4AebUMCwnVJVneA7Pf5p7hVKKeP%2BePDfMWYOpChS9smp0UjfoVSKYDDA1GDS4eE%2FTN02KjnLdVOWPqoAOm%2FurDzbs%2FYe8B2xnC6R0%2FpbMrj2j59bHB9d8f2GcKXOfiHpeKff%2BLNYYsSmEAApsiW2N05ZMTAWBZQTUyWy53jFhYrZU11uo8RlzKoJOiI6pNoufk4CtbdtVYLxdvQZuxQm7TRJNMLDAQQcL6qR07N0sxHMeo7IIe5QNLT%2B%2FUwqG4X3FJxhYHnSvP7CRT%2FtlS%2Fxutl3rNpthpxDplRBDMtc5rSig6H%2Bb9O1vFZKAG%2B%2F9J%2BE4sCWfckh7kANCYA%2BY3bDHvkTj%2BKKWckzpQB4yLyPD4L%2FbiUDm9T520C9ROwXXhMAun%2BI2hxidauOTkyx%2Bzny5M8zTMN8gvVcxlIHgQHCYy6776WdI2qk%2FmKxYM814s74zt4o3AhtIDTJfEJV0NriqcwxOzZqsnGXPBP9fxri5t57M%2B%2BeONpjcFJpRhj%2B1Os1omCe3CL1R84RsrVPfc8FzGu12yM15FeI0Qb5duqgH3kWdc6wEflRsGPWPfVqHdWfj8euhGQXwsE2m4tcglZdYCpxWfMnbF%2Foz8TOJv9b3ODFrYNTtaeG9arUbLZ8CPqWH8Nyag4MNRgZAZRJNHbc4eBKqi9YHp1p%2FCillnFgmoPMwccyziv%2BGAPkjtS9KCLb0XWEwJwJLgLWNllVka9g%2BlODt6HK2mPb0zPLpsQuDI5qQwnBlSWPbhqwpoWyatvmV7aPaeF3dJm5yBVKAMyAwqPbp9wU6zQLBnlCtwUNRh0HMSUwfPWoFlpweESBTUzjEQFRui7g874ksQtlF51dpUsdXF7JI1kV%2FWr8A%2BxhxlMEjxyhoTj70hUVO7V55I7Ppx3Iyz5AlBAoh2nu4NZccHY4JYjU3de%2FYWVa0jfBSxP0WU%2F5GHbwbENjCpgEMhpDVcFf409UN8ecQi53nQh8ytjsDJMTwYalBM8ys1BfXdvLMkL2dtBFTfHtVjIGtrOkTxfH3CtbT24CzAtWrXxBCY%2BDd97o3oi6ztloybTJtxhI8Zdb6vojsFm95QVmVAVO5PaeZ%2BgHOoqHFHJ%2BXG1kbV8OexmT1S1bAXuu%2Fa07HDjJzqBYovvzWa%2BaG9pG8SKiw0N%2Bb5mdxMDdcGEqVIMwUK7mf7sY06Z%2Fbl1SQvErfpEsgA67C1Qtrgb0fKetVMlQR4Zq%2F53H%2FrFrys2OAnPXUfVLiqWY%3D",
    "message": null
  }
}
</code>```

I then used the url within data to perform a PUT request and it failed with AccessDenied

```<code>PUT /profiles/profile_1.png?AWSAccessKeyId=ASIA4IWFXQ2GPP2VWPFE&Content-Type=image%2Fpng&Expires=1593513254&Signature=vmXn5%2Fk%2Bk3hh98B8OeNlU%2F8XetY%3D&x-amz-meta-username=foobar&x-amz-security-token=IQoJb3JpZ2luX2VjEJL%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaDmFwLXNvdXRoZWFzdC0xIkcwRQIhAK6oeGhiy%2BuWwonWYViWa5pzJxZlSwB5MWjuLcZas6NvAiBmArs%2B8noZacruG0dlWrUyIUm30WFLKUYACVW2xMCFmyrUBQgrEAAaDDg0MzMwMjAxMjU1NiIMgQFekIbk3lBaS%2BmyKrEFBrdMyiCwa1iKVcgFxO%2BW1RTCu5M9aKotfJtBCxtW8gGkUY8VsMsVLPYUDWrJU07z7QjdRIK5xR3%2BdWtkK%2FvW6ZULjqrtVwiDbwnncug7FvvzWBCzc2oOVUFenSBNXhr%2FGnlCbqk6mFyqkOtCeFffOYtls19tU56GsSa1aaTwdwQcRld02G1TJCgj6egjgxSoHqDFbntlHU84vWcW5wi1O4YX4NwAEhWmiLC%2BU6RsfbR0NA%2BzJHlRGShJhEAY1pxOmm3533DAzSjlhj3yvTJN8whT4jFUEvn0jWFCLb3u9rC99%2FwjgtPH0jlU%2BqESTP0VlATuCU%2F5by1iTyX4TLRFyF0vCqx5%2BEePH0SdZeVDEqi%2BIgXIkOGG8fzJQkxLu536uCioSojmRYqiG16Osu9mAiP08LEGsIquzsIoIZmWve3P56gwk0pM28TWYz%2BhZtynJCXAIDOtm1gZ7j14ho1SrpIazM6fJ95NgmuqJfud%2BIGbXdytPZQj1jRsj2fH3vlw66LTXN6AKBVPy6yTf45fMBfP2mywSZwkQtjEQ6hVN76nKD6Z1jZ%2F2Pbk%2FpFUwtcfYbGeKDIEpnV6h2%2BvsiaaNmos9eIYLkt6R9glYvInnIYvp6TOKJoicZgv%2BChr1lY8L728wCXnKLXxHTnv1YTnE5z%2FmtMbG4ZxYkj0ioaJt6kS2%2B3Lh%2BXdrbnwK7gbn3rFGT9EaTyeLSOymIB%2BHzAAfxB902g0c4jV6Em6B9xUxUgfXjHY1I5Gla1t36lEgAe7rlfngUlhoomJjDpMCw4IbzFnjvjXdAIzj7cJjmY%2FPxhdy4gp3pRvcgTkJ%2BV9DV8x2vMSgZS1qX5v%2FMQ%2BSQLStK5aY%2FjKqYkBt03102M1NovHpYiaV4XdE6%2F53unpdEyKtsKjUwYGLebd21kUhHkfoX4woqPs9wU6zQJwdh2wOJcRW9Wp6GmVLOyxfI23RxkAgygOjN5R1AUr%2F%2BehPrSr9iQsYjI%2FWzJqi7Ohzr3kZqjXuL4Yi1UKyRF6vyKckSDMQb371HypXkopMuoPxmNpZqI42IwO8%2BM0ktrJfnJ7Kp4i3EDw9eujy6Cuau5fsD8v6s0c3m5hNu1gmESfdmZr1%2BR%2FCVbifqgeLLwyGak96UyO%2BapQ4kOU6tu5uNskL1ewx%2F2K0esKq6qEz1IXA%2Fx5n5dioiom3GI9QVRfrtF7Z%2BhqBLipVfHMR2Pb4N3egoqBj80ux9u0UzYZ8rLst7Ns0tlJzmCHGxh0py9M7kUPAQmVMdQE4rAlP2FjMQiMWpOCiqo4uwADjKrlwinhSc98LPGYTxJ%2F8QveSfixbeZmgdC1gJkOAMUEdgnoh%2BeRB1dHR%2B3SavrFp1EIudMDIUxd4AxZSDYN%2F%2FY%3D HTTP/1.1
> Host: profilephoto-upload-dev.s3.ap-southeast-1.amazonaws.com
> User-Agent: insomnia/2020.2.2
> Content-Type: image/png
> Accept: */*
> Content-Length: 578256
</code>```
```<code><?xml version="1.0" encoding="UTF-8"?>
<Error>
  <Code>AccessDenied</Code>
  <Message>Access Denied</Message>
  <RequestId>A6037105527AC3DE</RequestId>
  <HostId>KqRDTOrRWDTjnQesY9ZIbBb95/lmqLmro7YLETogaA6qu4n0Jq8znwtExBxdpjDhgXr2Lg/MyqU=</HostId>
</Error>
</code>```

For the given:
Here is my presign code...

```<code>import S3 = require("aws-sdk/clients/s3")
import * as mime from "mime"

const createPresignedPost = async (key: string, contentType: string): Promise<string> => {
  const s3 = new S3()
  const params: S3.Types.PutObjectRequest = {
    Bucket: "profilephoto-upload-dev",
    Key: `profiles/${key}`,
    ContentType: contentType,
    Metadata: {username: "foobar"}
  }
  return s3.getSignedUrlPromise("putObject", params)
  .then(some => {
    console.log(`returned: ${some}`)
    return some
  })
}

app.post('/presign', async (req, res) => {
  const headers = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Credentials": true
  }
  try {
    const key = `${req.body['name']}`
    const mimeType = mime.getType(req.body['name'])!
    const presignedPostData = await createPresignedPost(key, mimeType)
    res.status(200).send({
      statusCode: 200,
      headers,
      body: {
        error: false,
        data: presignedPostData,
        message: null
      }
    })
  } catch (error) {
    console.trace(JSON.stringify(error))
    res.status(500).send({
      statusCode: 500,
      headers,
      body: {
        error: true,
        data: null,
        message: error.message
      }
    })
  }
})
</code>```

This express route belongs to a lambda created here...

```<code>  presignedpostdata:
    handler: ${self:custom.${self:custom.stage}.handler}
    role: arn:aws:iam::843302012556:role/service-role/auto_presignedpost_dev-role-w7qof39g
    events:
      - http:
          path: /presign
          method: post
          cors: true
</code>```

The role ARN mentioned has these permissions...

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws:s3:::profilephoto-upload-dev/*"
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": "logs:CreateLogGroup",
            "Resource": "*"
        }
    ]
}
</code>```

finally, the S3 bucket is created like so...

```<code>    ProfilePhotoBucket:
      Type: AWS::S3::Bucket
      Properties:
          BucketName: profilephoto-upload-${self:custom.stage}
          AccessControl: PublicRead
          CorsConfiguration:
              CorsRules:
              -   AllowedHeaders: ['*']
                  AllowedMethods: ['PUT']
                  AllowedOrigins: ['*']
</code>```

答:
In my case the problem was because the browser was sending additional headers like "Content-Type" but this header was not configured when generating the presigned URL.

The solution that I chose was to set the header to application/octet-stream at the moment of generating the presigned URL and on the browser I forced the Content-Type header to be application/octet-stream.

```<code>    s3_url = s3_client.generate_presigned_url(
        ClientMethod="put_object",
        Params={
            "Bucket": "my-bucket",
            "Key": f"some-key",
            "ContentType": "application/octet-stream"
        },
        ExpiresIn=24 * 60 * 60
    )
</code>```

Obviously this solution was the best for me at the moment.

Body:
Problem: How can I successfully perform a PUT file request to a pre-signed URL where the bucket has the following permissions:

Block public access = off for all 4 options

Access Control List = Public Read

Bucket Policy = empty

CORS Configuration = PUT

Here is a concrete example of what I did...

I performed a POST to my presign endpoint...

> POST /dev/presign HTTP/2
> Host: 9xugkdzvch.execute-api.ap-southeast-1.amazonaws.com
> user-agent: insomnia/2020.2.2
> content-type: application/json
> accept: */*
> content-length: 51

* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!

| {
|   "name": "profile_1.png",
|   "type": "image/png"
| }

it returned

{
  "statusCode": 200,
  "headers": {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Credentials": true
  },
  "body": {
    "error": false,
    "data": "https://profilephoto-upload-dev.s3.ap-southeast-1.amazonaws.com/profiles/profile_1.png?AWSAccessKeyId=ASIA4IWFXQ2GLT2FGUUA&Content-Type=image%2Fpng&Expires=1593475190&Signature=JO4pNtbXmb56OYiClZhil4hse0c%3D&x-amz-meta-username=foobar&x-amz-security-token=IQoJb3JpZ2luX2VjEIj%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaDmFwLXNvdXRoZWFzdC0xIkcwRQIhAP5kW%2Fj6Y5BiLgAhec3w6bv17CL8QuEabOy7hhhtK81JAiA7pS6IkGE3WtnIcD78%2BOytl1luSdLBkI9fg%2F2GzxpApirUBQghEAAaDDg0MzMwMjAxMjU1NiIMdbMwBimx3k0miN5lKrEFfUAFtMJep90tfYQqwW09Od1HTSaUKkVUqP0eOaQg89vEnplJ%2BCQwKopOF8Ed8AiFAFQ9qJcbtmg39wEqIBa5Z0oOdfDEphRXDmVWX%2BCQvdCCoPbbZeaK2tBg4PN2f%2FL8OBa4AebUMCwnVJVneA7Pf5p7hVKKeP%2BePDfMWYOpChS9smp0UjfoVSKYDDA1GDS4eE%2FTN02KjnLdVOWPqoAOm%2FurDzbs%2FYe8B2xnC6R0%2FpbMrj2j59bHB9d8f2GcKXOfiHpeKff%2BLNYYsSmEAApsiW2N05ZMTAWBZQTUyWy53jFhYrZU11uo8RlzKoJOiI6pNoufk4CtbdtVYLxdvQZuxQm7TRJNMLDAQQcL6qR07N0sxHMeo7IIe5QNLT%2B%2FUwqG4X3FJxhYHnSvP7CRT%2FtlS%2Fxutl3rNpthpxDplRBDMtc5rSig6H%2Bb9O1vFZKAG%2B%2F9J%2BE4sCWfckh7kANCYA%2BY3bDHvkTj%2BKKWckzpQB4yLyPD4L%2FbiUDm9T520C9ROwXXhMAun%2BI2hxidauOTkyx%2Bzny5M8zTMN8gvVcxlIHgQHCYy6776WdI2qk%2FmKxYM814s74zt4o3AhtIDTJfEJV0NriqcwxOzZqsnGXPBP9fxri5t57M%2B%2BeONpjcFJpRhj%2B1Os1omCe3CL1R84RsrVPfc8FzGu12yM15FeI0Qb5duqgH3kWdc6wEflRsGPWPfVqHdWfj8euhGQXwsE2m4tcglZdYCpxWfMnbF%2Foz8TOJv9b3ODFrYNTtaeG9arUbLZ8CPqWH8Nyag4MNRgZAZRJNHbc4eBKqi9YHp1p%2FCillnFgmoPMwccyziv%2BGAPkjtS9KCLb0XWEwJwJLgLWNllVka9g%2BlODt6HK2mPb0zPLpsQuDI5qQwnBlSWPbhqwpoWyatvmV7aPaeF3dJm5yBVKAMyAwqPbp9wU6zQLBnlCtwUNRh0HMSUwfPWoFlpweESBTUzjEQFRui7g874ksQtlF51dpUsdXF7JI1kV%2FWr8A%2BxhxlMEjxyhoTj70hUVO7V55I7Ppx3Iyz5AlBAoh2nu4NZccHY4JYjU3de%2FYWVa0jfBSxP0WU%2F5GHbwbENjCpgEMhpDVcFf409UN8ecQi53nQh8ytjsDJMTwYalBM8ys1BfXdvLMkL2dtBFTfHtVjIGtrOkTxfH3CtbT24CzAtWrXxBCY%2BDd97o3oi6ztloybTJtxhI8Zdb6vojsFm95QVmVAVO5PaeZ%2BgHOoqHFHJ%2BXG1kbV8OexmT1S1bAXuu%2Fa07HDjJzqBYovvzWa%2BaG9pG8SKiw0N%2Bb5mdxMDdcGEqVIMwUK7mf7sY06Z%2Fbl1SQvErfpEsgA67C1Qtrgb0fKetVMlQR4Zq%2F53H%2FrFrys2OAnPXUfVLiqWY%3D",
    "message": null
  }
}

I then used the url within data to perform a PUT request and it failed with AccessDenied

PUT /profiles/profile_1.png?AWSAccessKeyId=ASIA4IWFXQ2GPP2VWPFE&Content-Type=image%2Fpng&Expires=1593513254&Signature=vmXn5%2Fk%2Bk3hh98B8OeNlU%2F8XetY%3D&x-amz-meta-username=foobar&x-amz-security-token=IQoJb3JpZ2luX2VjEJL%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaDmFwLXNvdXRoZWFzdC0xIkcwRQIhAK6oeGhiy%2BuWwonWYViWa5pzJxZlSwB5MWjuLcZas6NvAiBmArs%2B8noZacruG0dlWrUyIUm30WFLKUYACVW2xMCFmyrUBQgrEAAaDDg0MzMwMjAxMjU1NiIMgQFekIbk3lBaS%2BmyKrEFBrdMyiCwa1iKVcgFxO%2BW1RTCu5M9aKotfJtBCxtW8gGkUY8VsMsVLPYUDWrJU07z7QjdRIK5xR3%2BdWtkK%2FvW6ZULjqrtVwiDbwnncug7FvvzWBCzc2oOVUFenSBNXhr%2FGnlCbqk6mFyqkOtCeFffOYtls19tU56GsSa1aaTwdwQcRld02G1TJCgj6egjgxSoHqDFbntlHU84vWcW5wi1O4YX4NwAEhWmiLC%2BU6RsfbR0NA%2BzJHlRGShJhEAY1pxOmm3533DAzSjlhj3yvTJN8whT4jFUEvn0jWFCLb3u9rC99%2FwjgtPH0jlU%2BqESTP0VlATuCU%2F5by1iTyX4TLRFyF0vCqx5%2BEePH0SdZeVDEqi%2BIgXIkOGG8fzJQkxLu536uCioSojmRYqiG16Osu9mAiP08LEGsIquzsIoIZmWve3P56gwk0pM28TWYz%2BhZtynJCXAIDOtm1gZ7j14ho1SrpIazM6fJ95NgmuqJfud%2BIGbXdytPZQj1jRsj2fH3vlw66LTXN6AKBVPy6yTf45fMBfP2mywSZwkQtjEQ6hVN76nKD6Z1jZ%2F2Pbk%2FpFUwtcfYbGeKDIEpnV6h2%2BvsiaaNmos9eIYLkt6R9glYvInnIYvp6TOKJoicZgv%2BChr1lY8L728wCXnKLXxHTnv1YTnE5z%2FmtMbG4ZxYkj0ioaJt6kS2%2B3Lh%2BXdrbnwK7gbn3rFGT9EaTyeLSOymIB%2BHzAAfxB902g0c4jV6Em6B9xUxUgfXjHY1I5Gla1t36lEgAe7rlfngUlhoomJjDpMCw4IbzFnjvjXdAIzj7cJjmY%2FPxhdy4gp3pRvcgTkJ%2BV9DV8x2vMSgZS1qX5v%2FMQ%2BSQLStK5aY%2FjKqYkBt03102M1NovHpYiaV4XdE6%2F53unpdEyKtsKjUwYGLebd21kUhHkfoX4woqPs9wU6zQJwdh2wOJcRW9Wp6GmVLOyxfI23RxkAgygOjN5R1AUr%2F%2BehPrSr9iQsYjI%2FWzJqi7Ohzr3kZqjXuL4Yi1UKyRF6vyKckSDMQb371HypXkopMuoPxmNpZqI42IwO8%2BM0ktrJfnJ7Kp4i3EDw9eujy6Cuau5fsD8v6s0c3m5hNu1gmESfdmZr1%2BR%2FCVbifqgeLLwyGak96UyO%2BapQ4kOU6tu5uNskL1ewx%2F2K0esKq6qEz1IXA%2Fx5n5dioiom3GI9QVRfrtF7Z%2BhqBLipVfHMR2Pb4N3egoqBj80ux9u0UzYZ8rLst7Ns0tlJzmCHGxh0py9M7kUPAQmVMdQE4rAlP2FjMQiMWpOCiqo4uwADjKrlwinhSc98LPGYTxJ%2F8QveSfixbeZmgdC1gJkOAMUEdgnoh%2BeRB1dHR%2B3SavrFp1EIudMDIUxd4AxZSDYN%2F%2FY%3D HTTP/1.1
> Host: profilephoto-upload-dev.s3.ap-southeast-1.amazonaws.com
> User-Agent: insomnia/2020.2.2
> Content-Type: image/png
> Accept: */*
> Content-Length: 578256

<?xml version="1.0" encoding="UTF-8"?>
<Error>
  AccessDenied
  <Message>Access Denied</Message>
  <RequestId>A6037105527AC3DE</RequestId>
  <HostId>KqRDTOrRWDTjnQesY9ZIbBb95/lmqLmro7YLETogaA6qu4n0Jq8znwtExBxdpjDhgXr2Lg/MyqU=</HostId>
</Error>

For the given:
Here is my presign code...

import S3 = require("aws-sdk/clients/s3")
import * as mime from "mime"

const createPresignedPost = async (key: string, contentType: string): Promise<string> => {
  const s3 = new S3()
  const params: S3.Types.PutObjectRequest = {
    Bucket: "profilephoto-upload-dev",
    Key: `profiles/${key}`,
    ContentType: contentType,
    Metadata: {username: "foobar"}
  }
  return s3.getSignedUrlPromise("putObject", params)
  .then(some => {
    console.log(`returned: ${some}`)
    return some
  })
}

app.post('/presign', async (req, res) => {
  const headers = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Credentials": true
  }
  try {
    const key = `${req.body['name']}`
    const mimeType = mime.getType(req.body['name'])!
    const presignedPostData = await createPresignedPost(key, mimeType)
    res.status(200).send({
      statusCode: 200,
      headers,
      body: {
        error: false,
        data: presignedPostData,
        message: null
      }
    })
  } catch (error) {
    console.trace(JSON.stringify(error))
    res.status(500).send({
      statusCode: 500,
      headers,
      body: {
        error: true,
        data: null,
        message: error.message
      }
    })
  }
})

This express route belongs to a lambda created here...

  presignedpostdata:
    handler: ${self:custom.${self:custom.stage}.handler}
    role: arn:aws:iam::843302012556:role/service-role/auto_presignedpost_dev-role-w7qof39g
    events:
      - http:
          path: /presign
          method: post
          cors: true

The role ARN mentioned has these permissions...

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws:s3:::profilephoto-upload-dev/*"
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": "logs:CreateLogGroup",
            "Resource": "*"
        }
    ]
}

finally, the S3 bucket is created like so...

    ProfilePhotoBucket:
      Type: AWS::S3::Bucket
      Properties:
          BucketName: profilephoto-upload-${self:custom.stage}
          AccessControl: PublicRead
          CorsConfiguration:
              CorsRules:
              -   AllowedHeaders: ['*']
                  AllowedMethods: ['PUT']
                  AllowedOrigins: ['*']

Body:
In my case the problem was because the browser was sending additional headers like "Content-Type" but this header was not configured when generating the presigned URL.

The solution that I chose was to set the header to application/octet-stream at the moment of generating the presigned URL and on the browser I forced the Content-Type header to be application/octet-stream.

    s3_url = s3_client.generate_presigned_url(
        ClientMethod="put_object",
        Params={
            "Bucket": "my-bucket",
            "Key": f"some-key",
            "ContentType": "application/octet-stream"
        },
        ExpiresIn=24 * 60 * 60
    )

Obviously this solution was the best for me at the moment.


问:
How and where to validate uniqueness of attribute/property in ASP.NET Core MVC using Entity Framework Core 6
I want to check, that users table records does not have specific email already stored.

If there is, then ModelState.IsValid returns false in controller action.

I understand need of unique constraint and I understand issues with race conditions. Those are not my concern right now.

At this point I just want to make ModelState.IsValid to return false after querying data in right place and making model invalid.

Should I implement such validation:

in DbContext?

in my entity classes (User / Company etc.)?

in SomeCustomValidation class?

directly in controller (since there I can already query the database...)

somewhere else...

And nice bonus would be create solution reusable across all entities :)

How should I do it?

答:
You can custom validation attribute like below:

```<code>public class TestEmailAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value,
        ValidationContext validationContext)
    {
        var context = (YourDbContext)validationContext.GetService(typeof(YourDbContext));
        if(!context.User.Any(a=>a.Email==value.ToString()))
        {
            return ValidationResult.Success;
        }
        return new ValidationResult("Email exists");
    }
}
</code>```

Model:

```<code>public class User
{
    public int Id { get; set; }
    [TestEmail]
    public string Email { get; set; }
}
</code>```

View(Test.cshtml):

```<code>@model User
<form method="post" asp-action="Test" asp-controller="Home">
    <div class="form-group">
        <input asp-for="Email" />
        <span asp-validation-for="Email" class="text-danger"></span>
    </div>

    <input type="submit" value="Post"/>
</form>
</code>```

Controller：

```<code>//GET render the Test.cshtml
public async Task<IActionResult> Test()
{
    return View();
}
[HttpPost]
public async Task<IActionResult> Test(User user)
{
    if(!ModelState.IsValid)
    {
        return View(user);
    }
    return RedirectToAction("Index");
}
</code>```

Body:
You can custom validation attribute like below:

public class TestEmailAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value,
        ValidationContext validationContext)
    {
        var context = (YourDbContext)validationContext.GetService(typeof(YourDbContext));
        if(!context.User.Any(a=>a.Email==value.ToString()))
        {
            return ValidationResult.Success;
        }
        return new ValidationResult("Email exists");
    }
}

Model:

public class User
{
    public int Id { get; set; }
    [TestEmail]
    public string Email { get; set; }
}

View(Test.cshtml):

@model User
<form method="post" asp-action="Test" asp-controller="Home">
    <div class="form-group">
        <input asp-for="Email" />
        <span asp-validation-for="Email" class="text-danger"></span>
    </div>

    <input type="submit" value="Post"/>
</form>

Controller：

//GET render the Test.cshtml
public async Task<IActionResult> Test()
{
    return View();
}
[HttpPost]
public async Task<IActionResult> Test(User user)
{
    if(!ModelState.IsValid)
    {
        return View(user);
    }
    return RedirectToAction("Index");
}


问:
How to start a background process in Python?
I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.</p>

答: I haven't tried this yet but using .pyw files instead of .py files should help. pyw files dosen't have a console so in theory it should not appear and work like a background process.</p>


问:
How can I return an optional instead of throwing an exception?
I have a method that can possibly throw an error. This exception is out of my control, as it is an IO exception, not a exception I am throwing. Instead of adding a throws statement to my method or fitting it in a try and catch block, would I be able to return an optional via this method?

Summary: I have a method to return a value T, except to get to that value, I have to add a try/catch block or throws statement to my method. Can I return an Optional of type T instead of throwing this error?

答:
You can use code like this to wrap code that returns a value with something that captures exceptions and returns an empty optional:

```<code>import java.util.Optional;
import java.util.function.Supplier;

@FunctionalInterface
public interface ThrowingSupplier<T> extends Supplier<Optional<T>> {
    @Override
    default Optional<T> get() {
        return getCapturingExceptions(this);
    }

    T getOrThrow() throws Exception;

    static <U> Optional<U> getCapturingExceptions(ThrowingSupplier<U> supplier) {
        try {
            return Optional.ofNullable(supplier.getOrThrow());
        } catch (Exception e) {
            e.printStackTrace();
            return Optional.empty();
        }
    }
}
</code>```

Examples of use:

```<code>import org.junit.Test;

import java.util.Optional;

import static org.junit.Assert.assertEquals;

public class ThrowingSupplierTest {
    @Test
    public void testSuccessfulSupplier() {
        assertEquals(
                Optional.of("Successful"),
                ThrowingSupplier.getCapturingExceptions(() -> "Successful")
        );
    }

    @Test
    public void testThrowingSupplier() {
        assertEquals(
                Optional.empty(),
                ThrowingSupplier.getCapturingExceptions(() -> {
                    throw new Exception("Expected failure; will be logged but test should pass");
                })
        );
    }
}
</code>```

This has all of the disadvantages outlined in Jim Garrison's answer, and I would agree with him that it is usually better to allow exceptions to propagate (wrapping in an unchecked exception when necessary). Still, this  is sometimes useful. For example, if you need to implement an interface that doesn't allow for a checked exception, and allowing an unchecked exception to propagate up the call stack would have undesirable effect such as killing a thread that doesn't handle them properly. To that end, this example implements Supplier (which cannot throw an unchecked exception) and can be used anywhere that interface is expected.

A few changes you might want to make:

This logs caught exceptions using e.printStackTrace(). It is important not to completely lose the exception message and stack trace, but if your application uses a logging framework, you might prefer to log the exception using that.

It uses Optional.ofNullable on the assumption that the wrapped code might return null, which isn't allowed in an Optional. This means that it might return an empty Optional even if no exception occurred. If the original code is not expected to return null, this could be changed to Optional.of. However if the wrapped code does return null in that case, Optional.of will throw a NullPointerException, which will be caught by the catch block and result in an empty Optional returned regardless.

It should also be noted that if the wrapped code returns an Optional type itself, this will be wrapped in another Optional layer. Getting the underlying value will require unwrapping it twice.

Body:
You can use code like this to wrap code that returns a value with something that captures exceptions and returns an empty optional:

import java.util.Optional;
import java.util.function.Supplier;

@FunctionalInterface
public interface ThrowingSupplier<T> extends Supplier<Optional<T>> {
    @Override
    default Optional<T> get() {
        return getCapturingExceptions(this);
    }

    T getOrThrow() throws Exception;

    static <U> Optional<U> getCapturingExceptions(ThrowingSupplier<U> supplier) {
        try {
            return Optional.ofNullable(supplier.getOrThrow());
        } catch (Exception e) {
            e.printStackTrace();
            return Optional.empty();
        }
    }
}

Examples of use:

import org.junit.Test;

import java.util.Optional;

import static org.junit.Assert.assertEquals;

public class ThrowingSupplierTest {
    @Test
    public void testSuccessfulSupplier() {
        assertEquals(
                Optional.of("Successful"),
                ThrowingSupplier.getCapturingExceptions(() -> "Successful")
        );
    }

    @Test
    public void testThrowingSupplier() {
        assertEquals(
                Optional.empty(),
                ThrowingSupplier.getCapturingExceptions(() -> {
                    throw new Exception("Expected failure; will be logged but test should pass");
                })
        );
    }
}

This has all of the disadvantages outlined in Jim Garrison's answer, and I would agree with him that it is usually better to allow exceptions to propagate (wrapping in an unchecked exception when necessary). Still, this  is sometimes useful. For example, if you need to implement an interface that doesn't allow for a checked exception, and allowing an unchecked exception to propagate up the call stack would have undesirable effect such as killing a thread that doesn't handle them properly. To that end, this example implements Supplier (which cannot throw an unchecked exception) and can be used anywhere that interface is expected.

A few changes you might want to make:

This logs caught exceptions using e.printStackTrace(). It is important not to completely lose the exception message and stack trace, but if your application uses a logging framework, you might prefer to log the exception using that.

It uses Optional.ofNullable on the assumption that the wrapped code might return null, which isn't allowed in an Optional. This means that it might return an empty Optional even if no exception occurred. If the original code is not expected to return null, this could be changed to Optional.of. However if the wrapped code does return null in that case, Optional.of will throw a NullPointerException, which will be caught by the catch block and result in an empty Optional returned regardless.

It should also be noted that if the wrapped code returns an Optional type itself, this will be wrapped in another Optional layer. Getting the underlying value will require unwrapping it twice.


问:
Mongodb for projects with many to many relationships
I'm at the beginning of starting a project for learning backend development with a bit of frontend development. For that, I wanted to create a project around cooking recipes. The plan was to create an admin REST API that would be later used by a custom CMS to create, edit, delete,... recipes and a public api for a mobile app where your users can discover cooking recipes.
Simplicity wise, I thought about choosing Mongodb as the database. While creating a Mongodb schema, I came up with this idea:

Three main collections

// Recipes (SKETCH!)
{
 id: ObjectId,
 title: {
  en: string,  // Multiple languages
  de: string,
  fr: string,
 },
 description: {
  en: string,  // Multiple languages
  de: string,
  fr: string,
 },
 author: ObjectId, // Id of the author inside the authors collection
 imageUrl: string,
 ...
 ingredients:
[
 //Ids of the ingredients inside the ingredients collection
 {
  id: ObjectId,
  amount: number,
 },
{
  id: ObjectId,
  amount: number,
 }
 ...
],
 steps: {
  en: [],
  de: [],
  fr: []
 }
}
```
<pre class="lang-js prettyprint-override"><code>// Author (SKETCH!)
{
 id: ObjectId,
 name: string,
 imageUrl: string,
 description: {
  en: string, // multiple languages
  de: string,
  fr: string,
 }
}
</code>```

// Ingredients (SKETCH!)
{
 id: ObjectId,
 name: {
  en: string,
  de: string,
  fr: string
 }
 imageUrl: string,
 // Based on 100g
 protein: number,
 carbs: number,
 calories: number,
}
```

My goal with this structure is to get the ingredients and the authors seperate from the recipes in order to update them independently. So, for example, when I edit my "tomato" ingredient, all recipes that contain this ingredient get updated too, in the sense that they only contain the ids of the ingredients. The same goes for the author.
Now I'm asking myself if this kind of structure isn't more suited to a sql database.
Would this structure make any significant performance/cost difference between a sql and a nosql/mongodb database?
Just as an example, if I had a recipe that contains 20 ingredients, wouldn't that be
20(Ingredients) + 1 (author) + 1 (recipe itself) = 22 documents reads to get a whole recipe(is sql much faster here)? Is that fast enough or does that even make sense cost/ performance wise?

And one last question: how many concurrent connections would be possible with a Mongodb database?

答:
My goal with this structure is to get the ingredients and the authors seperate from the recipes in order to update them independently.

That does not exclude the option to keep the data embedded in the recipes collection. You can keep a separate authors and ingredients collections AND also embed the fields needed in the recipe doc.

After some relevant author update you can issue recipes.updateMany({"author.id": authorId}, { $set: { author: author.profile}})

The idea is that author is not going to change very frequently, or at least the  relevant data for recipes (basic profile info excluding birthdate, address, etc).

Also the authors collection can include a list of the last 10 recipes, for example with only title, and date,...

And one last question: how many concurrent connections would be possible with a Mongodb database?

No need to worry about that, it can handle as many as you need by adding hardware.

Body:
I'm at the beginning of starting a project for learning backend development with a bit of frontend development. For that, I wanted to create a project around cooking recipes. The plan was to create an admin REST API that would be later used by a custom CMS to create, edit, delete,... recipes and a public api for a mobile app where your users can discover cooking recipes.
Simplicity wise, I thought about choosing Mongodb as the database. While creating a Mongodb schema, I came up with this idea:

Three main collections

// Recipes (SKETCH!)
{
 id: ObjectId,
 title: {
  en: string,  // Multiple languages
  de: string,
  fr: string,
 },
 description: {
  en: string,  // Multiple languages
  de: string,
  fr: string,
 },
 author: ObjectId, // Id of the author inside the authors collection
 imageUrl: string,
 ...
 ingredients:
[
 //Ids of the ingredients inside the ingredients collection
 {
  id: ObjectId,
  amount: number,
 },
{
  id: ObjectId,
  amount: number,
 }
 ...
],
 steps: {
  en: [],
  de: [],
  fr: []
 }
}

// Author (SKETCH!)
{
 id: ObjectId,
 name: string,
 imageUrl: string,
 description: {
  en: string, // multiple languages
  de: string,
  fr: string,
 }
}

// Ingredients (SKETCH!)
{
 id: ObjectId,
 name: {
  en: string,
  de: string,
  fr: string
 }
 imageUrl: string,
 // Based on 100g
 protein: number,
 carbs: number,
 calories: number,
}

My goal with this structure is to get the ingredients and the authors seperate from the recipes in order to update them independently. So, for example, when I edit my "tomato" ingredient, all recipes that contain this ingredient get updated too, in the sense that they only contain the ids of the ingredients. The same goes for the author.
Now I'm asking myself if this kind of structure isn't more suited to a sql database.
Would this structure make any significant performance/cost difference between a sql and a nosql/mongodb database?
Just as an example, if I had a recipe that contains 20 ingredients, wouldn't that be
20(Ingredients) + 1 (author) + 1 (recipe itself) = 22 documents reads to get a whole recipe(is sql much faster here)? Is that fast enough or does that even make sense cost/ performance wise?

And one last question: how many concurrent connections would be possible with a Mongodb database?


问:
How to switch elements in data.frame according to size?
I am looking for an R function that allows swapping two elements in a data frame under a certain constraint.

For example:

If I have a dataframe (5rows, 5cols) and I want that all elements in column 2 that are greater than the corresponding elements in column 3 to be swapped. As a result, all the elements of column 2 greater than those of column 3 would move to column 3 and vice-versa.

Your help is much appreciated.

答:
Reproducible sample data:

set.seed(42)
dat <- as.data.frame(matrix(sample(10, size=25, replace=TRUE), nrow=5))
dat
#   V1 V2 V3 V4 V5
# 1  1  4  7 10  4
# 2  5  2  4  2  5
# 3  1 10  9  3  5
# 4  9  1  5  9  4
# 5 10  8  4  9  2
```
<p>Working solution:</p>
<pre class="lang-r prettyprint-override"><code>dat[c("V1", "V2")] <- lapply(list(pmin, pmax), function(fun) do.call(fun, dat[c("V1", "V2")]))
dat
#   V1 V2 V3 V4 V5
# 1  1  4  7 10  4
# 2  2  5  4  2  5
# 3  1 10  9  3  5
# 4  1  9  5  9  4
# 5  8 10  4  9  2
</code>```

Body:
Reproducible sample data:

set.seed(42)
dat <- as.data.frame(matrix(sample(10, size=25, replace=TRUE), nrow=5))
dat
#   V1 V2 V3 V4 V5
# 1  1  4  7 10  4
# 2  5  2  4  2  5
# 3  1 10  9  3  5
# 4  9  1  5  9  4
# 5 10  8  4  9  2

Working solution:

dat[c("V1", "V2")] <- lapply(list(pmin, pmax), function(fun) do.call(fun, dat[c("V1", "V2")]))
dat
#   V1 V2 V3 V4 V5
# 1  1  4  7 10  4
# 2  2  5  4  2  5
# 3  1 10  9  3  5
# 4  1  9  5  9  4
# 5  8 10  4  9  2


问:
How to force the android system to open only my app based on the registered intent filter
Issue:
I've been working on an app that listens to a certain kind of intents depending on a given link format. My intent filter works as expected, I'm just wondering whether it's possible to force the android system to bypass the kind of dialog below and open only my app.

答:
you force user to use a specific browser by this:</p>
```<code>String packageName = "com.android.yourBrowser";
String className = "com.android.browser.YourBrowserActivity";
Intent internetIntent = new Intent(Intent.ACTION_VIEW);
internetIntent.addCategory(Intent.CATEGORY_LAUNCHER);
internetIntent.setClassName(packageName, className);
</code>```

Body:
you force user to use a specific browser by this:

String packageName = "com.android.yourBrowser";
String className = "com.android.browser.YourBrowserActivity";
Intent internetIntent = new Intent(Intent.ACTION_VIEW);
internetIntent.addCategory(Intent.CATEGORY_LAUNCHER);
internetIntent.setClassName(packageName, className);


问:
How to convert Instant to joda DateTime?
How to convert Instant(java.time.Instant) to joda DateTime (org.joda.time.DateTime)? Or rather, what's the best way to do this?</p>

答:
tl;dr

```<code>new DateTime( myInstant.toEpochMilli() )
</code>```

java.time replaces Joda-Time

Do you understand that java.time is the successor to Joda-Time? If you have java.time at your disposal, there should be no need to use Joda-Time. The same man, Stephen Colebourne, led both projects, taking lessons learned from Joda-Time to design java.time in JSR 310.

Convert by way of count of milliseconds

But to answer your Question directly: Extract from the Instant object a count of milliseconds since the first moment of 1970 in UTC. Use that count to construct a DateTime object.

Beware of potential data loss. An Instant may contain microseconds or nanoseconds. These will be ignored, of course, when extracting milliseconds.

```<code>java.time.Instant myInstant = Instant.now() ;
long millis = myInstant.toEpochMilli() ;
org.joda.time.DateTime dt = new DateTime( millis ) ;
</code>```

In java.time, an Instant is always in UTC. To match that on your DateTime, pass the UTC constant to this other constructor.

```<code>DateTime dt = new DateTime( millis , DateTimeZone.UTC ) ;
</code>```

Body:
tl;dr

new DateTime( myInstant.toEpochMilli() )

java.time replaces Joda-Time

Do you understand that java.time is the successor to Joda-Time? If you have java.time at your disposal, there should be no need to use Joda-Time. The same man, Stephen Colebourne, led both projects, taking lessons learned from Joda-Time to design java.time in JSR 310.

Convert by way of count of milliseconds

But to answer your Question directly: Extract from the Instant object a count of milliseconds since the first moment of 1970 in UTC. Use that count to construct a DateTime object.

Beware of potential data loss. An Instant may contain microseconds or nanoseconds. These will be ignored, of course, when extracting milliseconds.

java.time.Instant myInstant = Instant.now() ;
long millis = myInstant.toEpochMilli() ;
org.joda.time.DateTime dt = new DateTime( millis ) ;

In java.time, an Instant is always in UTC. To match that on your DateTime, pass the UTC constant to this other constructor.

DateTime dt = new DateTime( millis , DateTimeZone.UTC ) ;


问:
I want to define a variable with superglobal scope in php
I want to define a variable in php with in a global scope. That variable should be accessible for each user, so it should not depend on the session.

I want to do something like the following: I have a php script, and that script usually takes about 5 to 15 minutes to execute, but it can take more than one hour in some special cases. This script is being run using a cron job with a 15 minutes interval. This script can also be run manually by any user.

Now it's possible to run any number of scripts at the same time. I want to limit this number of scripts.

So, I want a variable to store the number of currently executing scripts. I don't want to use a DB or files to store a single value.

Thanks in advance.

答:
check if limit is reached

when user access script, add him to DB

when user exists (or script ends), remove him from DB

there's no way to save this somewhere else for everyone without file nor DB


问:
How can I prevent my Ionic App from detecting missing peer dependencies in node_modules
I have built a mobile app using Typescript React and Ionic. Using Appflow to deploy to a mobile device results in my build failing due to warnings regarding peer dependencies from MongoDB. I installed the peer dependencies, one of which is snappy - which has resulted in further missing dependencies that I cannot install due to them being platform specific. I have tried adding the node_modules file to my .eslintignore, but it still detects them as missing and due to the CI being set as treating warnings as errors, it breaks the build.

```<code>[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.android-arm64.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.darwin-arm64.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.darwin-x64.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.freebsd-x64.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.linux-arm-gnueabihf.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.linux-arm64-gnu.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.linux-arm64-musl.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.linux-x64-gnu.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.linux-x64-musl.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.win32-arm64-msvc.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.win32-ia32-msvc.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.win32-x64-msvc.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-android-arm64' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-darwin-arm64' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-darwin-x64' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-freebsd-x64' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-linux-arm-gnueabihf' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-linux-arm64-gnu' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-linux-arm64-musl' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-linux-x64-gnu' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-linux-x64-musl' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-win32-arm64-msvc' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-win32-ia32-msvc' in 'D:\Projects\app\node_modules\snappy'
</code>```

this is the build result

How can I either stop my Appflow CI from detecting this as an error, install the missing dependencies, or stop the warnings being returned from the node_modules file?

答:
The unresolved peer dependencies are still an issue, but I resolved the problem by disabling the CI in my build script by simply changing:

```<code>"scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "eject": "react-scripts eject"
    },
</code>```

to:

```<code>"scripts": {
    "start": "react-scripts start",
    "build": "CI=false react-scripts build",
    "eject": "react-scripts eject"
},
</code>```

in my package.json file. I still think that resolving the peer dependencies would have been a better solution, but this did the trick for now

Body:
I have built a mobile app using Typescript React and Ionic. Using Appflow to deploy to a mobile device results in my build failing due to warnings regarding peer dependencies from MongoDB. I installed the peer dependencies, one of which is snappy - which has resulted in further missing dependencies that I cannot install due to them being platform specific. I have tried adding the node_modules file to my .eslintignore, but it still detects them as missing and due to the CI being set as treating warnings as errors, it breaks the build.

[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.android-arm64.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.darwin-arm64.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.darwin-x64.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.freebsd-x64.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.linux-arm-gnueabihf.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.linux-arm64-gnu.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.linux-arm64-musl.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.linux-x64-gnu.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.linux-x64-musl.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.win32-arm64-msvc.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.win32-ia32-msvc.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve './snappy.win32-x64-msvc.node' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-android-arm64' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-darwin-arm64' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-darwin-x64' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-freebsd-x64' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-linux-arm-gnueabihf' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-linux-arm64-gnu' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-linux-arm64-musl' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-linux-x64-gnu' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-linux-x64-musl' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-win32-arm64-msvc' in 'D:\Projects\app\node_modules\snappy'
[react-scripts] ./node_modules/snappy/index.js
[react-scripts] Module not found: Can't resolve '@napi-rs/snappy-win32-ia32-msvc' in 'D:\Projects\app\node_modules\snappy'

this is the build result

How can I either stop my Appflow CI from detecting this as an error, install the missing dependencies, or stop the warnings being returned from the node_modules file?

Body:
The unresolved peer dependencies are still an issue, but I resolved the problem by disabling the CI in my build script by simply changing:

"scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "eject": "react-scripts eject"
    },

to:

"scripts": {
    "start": "react-scripts start",
    "build": "CI=false react-scripts build",
    "eject": "react-scripts eject"
},

in my package.json file. I still think that resolving the peer dependencies would have been a better solution, but this did the trick for now


问:
How to get all objects inside an array JSON in a C# controller
How do I retrieve all of the [names] that are part of the object called [items] in this JSON scenario below in C# ?

I am using a shopping cart api and want to show the customer all of the items listed off that were part of the order once they get to the thank you page. The parent object I am looking at in the api is called items and it has child object data such as price of each item, name of each item and product image of each item etc.....

In my controller I was doing this below when I only needed to retrieve simple info like the order only has 1 invoiceNumber, 1 payment method, 1 shipping method, 1 promo code etc.. This code below works and gets me that data in that simple scenario below.

```<code> using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            var obj = JObject.Parse(result);

            //Order Info
            string invoiceNumber = (string)obj["invoiceNumber"];
            string email = (string)obj["email"];
            string paymentMethod = (string)obj["paymentMethod"];
            string shippingMethod = (string)obj["shippingMethod"];

            //Discount info
            string amountSaved = (string)obj["discounts"][0]["amountSaved"];
            string promoCode = (string)obj["discounts"][0]["code"];
</code>```

But now I need to tap into an object called [items] (the data for the items that were part of the order) that is going to have many names of items depending on the number of individual items that were part of the customer order. This is what I attempted but then realized that it would only return one record based on what number I used inside the brackets.

```<code>string items = (string)obj["items"][0]["name"]; //This returned the product at index 0
string items = (string)obj["items"][1]["name"]; //This returned the product at index 1
string items = (string)obj["items"][2]["name"]; //This returned the product at index 2
</code>```

How do I write the syntax so that I can grab ALL of the name objects that currently reside in the item object for exaple? I know it has something to do with deserialize objects and list but I do not know the syntax and how to approach.

Any suggestions on how I can get this done?

答:
the simpliest way

```<code>List<string> names = obj["items"].Select(x => (string) x["name"] ).ToList();
</code>```

test

```<code>Console.WriteLine( string.Join(",",names)); // prod1,prod2
</code>```

more complicated way is to create a c# class and deserialize data. But in this case you will be able to use Linq for queries and search

```<code> List<Item>  items = obj["items"].Select(x => x.ToObject<Item>()).ToList()

public class Item
{
    public string name { get; set; }
    public double price { get; set; }
    public int quantity { get; set; }
}
</code>```

result (in json format)

```<code>[
  {
    "name": "prod1",
    "price": 12.99,
    "quantity": 4
  },
  {
    "name": "prod2",
    "price": 17.65,
    "quantity": 1
  }
]
</code>```

Body:
How do I retrieve all of the [names] that are part of the object called [items] in this JSON scenario below in C# ?

I am using a shopping cart api and want to show the customer all of the items listed off that were part of the order once they get to the thank you page. The parent object I am looking at in the api is called items and it has child object data such as price of each item, name of each item and product image of each item etc.....

In my controller I was doing this below when I only needed to retrieve simple info like the order only has 1 invoiceNumber, 1 payment method, 1 shipping method, 1 promo code etc.. This code below works and gets me that data in that simple scenario below.

 using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            var obj = JObject.Parse(result);

            //Order Info
            string invoiceNumber = (string)obj["invoiceNumber"];
            string email = (string)obj["email"];
            string paymentMethod = (string)obj["paymentMethod"];
            string shippingMethod = (string)obj["shippingMethod"];

            //Discount info
            string amountSaved = (string)obj["discounts"][0]["amountSaved"];
            string promoCode = (string)obj["discounts"][0]["code"];

But now I need to tap into an object called [items] (the data for the items that were part of the order) that is going to have many names of items depending on the number of individual items that were part of the customer order. This is what I attempted but then realized that it would only return one record based on what number I used inside the brackets.

string items = (string)obj["items"][0]["name"]; //This returned the product at index 0
string items = (string)obj["items"][1]["name"]; //This returned the product at index 1
string items = (string)obj["items"][2]["name"]; //This returned the product at index 2

How do I write the syntax so that I can grab ALL of the name objects that currently reside in the item object for exaple? I know it has something to do with deserialize objects and list but I do not know the syntax and how to approach.

Any suggestions on how I can get this done?

Body:
the simpliest way

List<string> names = obj["items"].Select(x => (string) x["name"] ).ToList();

test

Console.WriteLine( string.Join(",",names)); // prod1,prod2

more complicated way is to create a c# class and deserialize data. But in this case you will be able to use Linq for queries and search

 List<Item>  items = obj["items"].Select(x => x.ToObject<Item>()).ToList()

public class Item
{
    public string name { get; set; }
    public double price { get; set; }
    public int quantity { get; set; }
}

result (in json format)

[
  {
    "name": "prod1",
    "price": 12.99,
    "quantity": 4
  },
  {
    "name": "prod2",
    "price": 17.65,
    "quantity": 1
  }
]


答:
This query will match each table_a entry to every table_b transaction, based only on the transaction date being BETWEEN datefrom and dateto. table_a.id is ignored.

SELECT
    table_b.id,
    table_b.transdate,
    table_b.value AS "b_value",
    table_a.value AS "a_value",
    table_a.value * table_b.value AS "ab_value"
FROM table_b
LEFT JOIN table_a
    ON table_b.transdate BETWEEN table_a.datefrom AND table_a.dateto;
```
<p>Output:</p>
```| id  | transdate                | b_value | a_value | ab_value |
| --- | ------------------------ | ------- | ------- | -------- |
| 1   | 2021-01-03T00:00:00.000Z | 3       | 7       | 21       |
| 2   | 2021-01-10T00:00:00.000Z | 6       | 9       | 54       |
| 3   | 2021-01-20T00:00:00.000Z | 3       | 4       | 12       |
```

db-fiddle here

Body:
This query will match each table_a entry to every table_b transaction, based only on the transaction date being BETWEEN datefrom and dateto. table_a.id is ignored.

SELECT
    table_b.id,
    table_b.transdate,
    table_b.value AS "b_value",
    table_a.value AS "a_value",
    table_a.value * table_b.value AS "ab_value"
FROM table_b
LEFT JOIN table_a
    ON table_b.transdate BETWEEN table_a.datefrom AND table_a.dateto;

Output:

| id  | transdate                | b_value | a_value | ab_value |
| --- | ------------------------ | ------- | ------- | -------- |
| 1   | 2021-01-03T00:00:00.000Z | 3       | 7       | 21       |
| 2   | 2021-01-10T00:00:00.000Z | 6       | 9       | 54       |
| 3   | 2021-01-20T00:00:00.000Z | 3       | 4       | 12       |

db-fiddle here


问:
inset shadow white space
I'm actually trying to do a website by myself for my classes and I have an inset border shadow problem with an input like there is some white space between the input and the shadow I think. So if it's possible to have some help.

Here's the code: https://jsfiddle.net/LeLicorne_/62xsn1gz/

:root {
  --primary-color: #252525;
  --secondary-color: #181818;
}

/*---------------------------------------------------------------------------------*/

body {
  margin: 0;
  padding: 0;
  background: #333333;
}

/*---------------------------------------------------------------------------------*/

a {
  text-decoration: none;
}

.right {
  display: flex;
  padding: 0;
  margin: 0;
  height: 100vh;
  width: border-box;
}

.right .contact {
  background: none;
  position: absolute;
  margin-top: 0;
}

.right .contact .loc {
  position: absolute;
  height: 100%;
  width: 100%;
  left: 0px;
  top: 0;
}

.right .contact .loc .contactleft {
  position: absolute;
  width: 765px;
  height: 600px;
  left: 115px;
  top: 0;
  background: var(--primary-color);
  box-shadow: 0px 0px 5px 5px var(--primary-color);
  border-radius: 20px;
}

.right .contact .loc .contactleft label {
  display: block;
  font-size: 40px;
  margin: 20px;
  font-family: Roboto;
  font-style: normal;
  font-weight: 500;
  color: white;
  align-items: center;
}

.right .contact .loc .contactleft #name {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 35px;
  border-radius: 10px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft #email {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 35px;
  border-radius: 10px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft #message {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 150px;
  border-radius: 10px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft .sendmessage {
  display: block;
}

/*---------------------------------------------------------------------------------*/

@keyframes yellow {
  0% {
    color: white;
    background: var(--primary-color);
    box-shadow: 0px 0px 5px 5px var(--primary-color);
  }
  50% {
    color: yellow;
    background: var(--secondary-color);
    box-shadow: 0px 0px 5px 5px var(--secondary-color);
  }
  100% {
    color: white;
    background: var(--primary-color);
    box-shadow: 0px 0px 5px 5px var(--primary-color);
  }
}

/*---------------------------------------------------------------------------------*/

/* Ensemble */

::-webkit-scrollbar {
  width: 10px;
}

/* Track */

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* Handle */

::-webkit-scrollbar-thumb {
  background: #888;
  -webkit-border-radius: 5px;
  border-radius: 5px;
}

/* Handle hover */

::-webkit-scrollbar-thumb:hover {
  background: #555;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charaset="utf-8">
  <link rel="stylesheet" href="css/style.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Lo Re Baptiste</title>
  <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
  <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>
</head>

<body>

  <div class="right">
    <div id="contact" class="contact">
      <div class="loc">
        <form class="contactleft" action="#home">
          <label for="name">Name</label>
          <input type="text" id="name" name="name"></input>
          <label for="email">Email</label>
          <input type="email" id="email" name="email"></input>
          <label for="message">Message</label>
          <textarea id="message" name="message"></textarea>
        </form>
      </div>
    </div>
  </div>

</body></code>```

The white space from the input

答:
Remove border-radius: 10px; on all inputs and #message

:root {
  --primary-color: #252525;
  --secondary-color: #181818;
}

/*---------------------------------------------------------------------------------*/

body {
  margin: 0;
  padding: 0;
  background: #333333;
}

/*---------------------------------------------------------------------------------*/

a {
  text-decoration: none;
}

.right {
  display: flex;
  padding: 0;
  margin: 0;
  height: 100vh;
  width: border-box;
}

.right .contact {
  background: none;
  position: absolute;
  margin-top: 0;
}

.right .contact .loc {
  position: absolute;
  height: 100%;
  width: 100%;
  left: 0px;
  top: 0;
}

.right .contact .loc .contactleft {
  position: absolute;
  width: 765px;
  height: 600px;
  left: 115px;
  top: 0;
  background: var(--primary-color);
  box-shadow: 0px 0px 5px 5px var(--primary-color);
  border-radius: 20px;
}

.right .contact .loc .contactleft label {
  display: block;
  font-size: 40px;
  margin: 20px;
  font-family: Roboto;
  font-style: normal;
  font-weight: 500;
  color: white;
  align-items: center;
}

.right .contact .loc .contactleft #name {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 35px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft #email {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 35px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft #message {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 150px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft .sendmessage {
  display: block;
}

/*---------------------------------------------------------------------------------*/

@keyframes yellow {
  0% {
    color: white;
    background: var(--primary-color);
    box-shadow: 0px 0px 5px 5px var(--primary-color);
  }
  50% {
    color: yellow;
    background: var(--secondary-color);
    box-shadow: 0px 0px 5px 5px var(--secondary-color);
  }
  100% {
    color: white;
    background: var(--primary-color);
    box-shadow: 0px 0px 5px 5px var(--primary-color);
  }
}

/*---------------------------------------------------------------------------------*/

/* Ensemble */

::-webkit-scrollbar {
  width: 10px;
}

/* Track */

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* Handle */

::-webkit-scrollbar-thumb {
  background: #888;
  -webkit-border-radius: 5px;
  border-radius: 5px;
}

/* Handle hover */

::-webkit-scrollbar-thumb:hover {
  background: #555;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charaset="utf-8">
  <link rel="stylesheet" href="css/style.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Lo Re Baptiste</title>
  <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
  <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>
</head>

<body>

  <div class="right">
    <div id="contact" class="contact">
      <div class="loc">
        <form class="contactleft" action="#home">
          <label for="name">Name</label>
          <input type="text" id="name" name="name"></input>
          <label for="email">Email</label>
          <input type="email" id="email" name="email"></input>
          <label for="message">Message</label>
          <textarea id="message" name="message"></textarea>
        </form>
      </div>
    </div>
  </div>

</body></code>```

Title: inset shadow white space

Body:
I'm actually trying to do a website by myself for my classes and I have an inset border shadow problem with an input like there is some white space between the input and the shadow I think. So if it's possible to have some help.

Here's the code: https://jsfiddle.net/LeLicorne_/62xsn1gz/

:root {
  --primary-color: #252525;
  --secondary-color: #181818;
}

/*---------------------------------------------------------------------------------*/

body {
  margin: 0;
  padding: 0;
  background: #333333;
}

/*---------------------------------------------------------------------------------*/

a {
  text-decoration: none;
}

.right {
  display: flex;
  padding: 0;
  margin: 0;
  height: 100vh;
  width: border-box;
}

.right .contact {
  background: none;
  position: absolute;
  margin-top: 0;
}

.right .contact .loc {
  position: absolute;
  height: 100%;
  width: 100%;
  left: 0px;
  top: 0;
}

.right .contact .loc .contactleft {
  position: absolute;
  width: 765px;
  height: 600px;
  left: 115px;
  top: 0;
  background: var(--primary-color);
  box-shadow: 0px 0px 5px 5px var(--primary-color);
  border-radius: 20px;
}

.right .contact .loc .contactleft label {
  display: block;
  font-size: 40px;
  margin: 20px;
  font-family: Roboto;
  font-style: normal;
  font-weight: 500;
  color: white;
  align-items: center;
}

.right .contact .loc .contactleft #name {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 35px;
  border-radius: 10px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft #email {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 35px;
  border-radius: 10px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft #message {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 150px;
  border-radius: 10px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft .sendmessage {
  display: block;
}

/*---------------------------------------------------------------------------------*/

@keyframes yellow {
  0% {
    color: white;
    background: var(--primary-color);
    box-shadow: 0px 0px 5px 5px var(--primary-color);
  }
  50% {
    color: yellow;
    background: var(--secondary-color);
    box-shadow: 0px 0px 5px 5px var(--secondary-color);
  }
  100% {
    color: white;
    background: var(--primary-color);
    box-shadow: 0px 0px 5px 5px var(--primary-color);
  }
}

/*---------------------------------------------------------------------------------*/

/* Ensemble */

::-webkit-scrollbar {
  width: 10px;
}

/* Track */

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* Handle */

::-webkit-scrollbar-thumb {
  background: #888;
  -webkit-border-radius: 5px;
  border-radius: 5px;
}

/* Handle hover */

::-webkit-scrollbar-thumb:hover {
  background: #555;
}

<!DOCTYPE html>

  <meta charaset="utf-8">
  <link rel="stylesheet" href="css/style.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Lo Re Baptiste</title>

        <form class="contactleft" action="#home">
          Name
          <input type="text" id="name" name="name"></input>
          Email
          <input type="email" id="email" name="email"></input>
          Message
          <textarea id="message" name="message"></textarea>
        </form>

The white space from the input

Body:
Remove border-radius: 10px; on all inputs and #message

:root {
  --primary-color: #252525;
  --secondary-color: #181818;
}

/*---------------------------------------------------------------------------------*/

body {
  margin: 0;
  padding: 0;
  background: #333333;
}

/*---------------------------------------------------------------------------------*/

a {
  text-decoration: none;
}

.right {
  display: flex;
  padding: 0;
  margin: 0;
  height: 100vh;
  width: border-box;
}

.right .contact {
  background: none;
  position: absolute;
  margin-top: 0;
}

.right .contact .loc {
  position: absolute;
  height: 100%;
  width: 100%;
  left: 0px;
  top: 0;
}

.right .contact .loc .contactleft {
  position: absolute;
  width: 765px;
  height: 600px;
  left: 115px;
  top: 0;
  background: var(--primary-color);
  box-shadow: 0px 0px 5px 5px var(--primary-color);
  border-radius: 20px;
}

.right .contact .loc .contactleft label {
  display: block;
  font-size: 40px;
  margin: 20px;
  font-family: Roboto;
  font-style: normal;
  font-weight: 500;
  color: white;
  align-items: center;
}

.right .contact .loc .contactleft #name {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 35px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft #email {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 35px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft #message {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 90%;
  height: 150px;
  border: none;
  font-size: 20px;
  box-shadow: inset 0px 0px 5px 5px var(--secondary-color);
  background: white;
}

.right .contact .loc .contactleft .sendmessage {
  display: block;
}

/*---------------------------------------------------------------------------------*/

@keyframes yellow {
  0% {
    color: white;
    background: var(--primary-color);
    box-shadow: 0px 0px 5px 5px var(--primary-color);
  }
  50% {
    color: yellow;
    background: var(--secondary-color);
    box-shadow: 0px 0px 5px 5px var(--secondary-color);
  }
  100% {
    color: white;
    background: var(--primary-color);
    box-shadow: 0px 0px 5px 5px var(--primary-color);
  }
}

/*---------------------------------------------------------------------------------*/

/* Ensemble */

::-webkit-scrollbar {
  width: 10px;
}

/* Track */

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* Handle */

::-webkit-scrollbar-thumb {
  background: #888;
  -webkit-border-radius: 5px;
  border-radius: 5px;
}

/* Handle hover */

::-webkit-scrollbar-thumb:hover {
  background: #555;
}

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

<head>
  <meta charaset="utf-8">
  <link rel="stylesheet" href="css/style.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Lo Re Baptiste</title>
  <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
  <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>
</head>

<body>

  <div class="right">
    <div id="contact" class="contact">
      <div class="loc">
        <form class="contactleft" action="#home">
          <label for="name">Name</label>
          <input type="text" id="name" name="name"></input>
          <label for="email">Email</label>
          <input type="email" id="email" name="email"></input>
          <label for="message">Message</label>
          <textarea id="message" name="message"></textarea>
        </form>
      </div>
    </div>
  </div>

</body>


问:
In JavaScript, how can I update each element of an array the same way without using a loop?
For example, if I have an array:

```<code>movies = ["Spider Man", "Avatar", "Titantic", "Avengers"]
</code>```

How do I turn the movies array into

```<code>[{title: "Spider Man"}, {title: "Avatar"}, {title: "Titantic"}, {title:"Avengers"}]
</code>```

without using a loop? Is it possible to do it in O(1)?

In the same way, If I have an integer array and need to increment every element by one, can I do it without a loop?

答:
It is impossible.

If your input set contains N elements, you cannot create a different structure of N other elements without a loop. Any algorithm that isn't hard-coded to the input array will require an O(n) loop.

The only (cheating) O(1) approach would be something like

```<code>const transformMovies = () => [{title: "Spider Man"}, {title: "Avatar"}, {title: "Titantic"}, {title:"Avengers"}];
</code>```

which of course only works for one possible input, and not for the general problem.

Body:
For example, if I have an array:

movies = ["Spider Man", "Avatar", "Titantic", "Avengers"]

How do I turn the movies array into

[{title: "Spider Man"}, {title: "Avatar"}, {title: "Titantic"}, {title:"Avengers"}]

without using a loop? Is it possible to do it in O(1)?

In the same way, If I have an integer array and need to increment every element by one, can I do it without a loop?

Body:
It is impossible.

If your input set contains N elements, you cannot create a different structure of N other elements without a loop. Any algorithm that isn't hard-coded to the input array will require an O(n) loop.

The only (cheating) O(1) approach would be something like

const transformMovies = () => [{title: "Spider Man"}, {title: "Avatar"}, {title: "Titantic"}, {title:"Avengers"}];

which of course only works for one possible input, and not for the general problem.


答:
Use between to match the date ranged in A:

```<code>select
  b.id,
  b.transdate,
  b.value as b_value,
  a.value as a_value,
  b.value * a.value as a_x_b_value
from table_b b
join table_a a on a.id = b.id
  and b.transdate between a.datefrom and a.dateto
</code>```

If there is a possibility there won't be a matching row in A, use a left join with a default of (say) 1 for the A value:

```<code>select
  b.id,
  b.transdate,
  b.value as b_value,
  a.value as a_value,
  b.value * coalesce(a.value, 1) as a_x_b_value
from table_b b
left join table_a a on a.id = b.id
  and b.transdate between a.datefrom and a.dateto
</code>```

Body:
Given 2 tables:

Table A

|id|datefrom  |dateto     |value|
|--|--------  |------     |-----|
|1 |2021-01-01|2021-01-07 |   7 |
|2 |2021-01-08|2021-01-15 |   9 |
|3 |2021-01-16|2021-01-23 |   4 |

Table B

|id|transdate  |value|
|--|--------   |-----|
|1 |2021-01-03 |   3 |
|2 |2021-01-10 |   6 |
|3 |2021-01-20 |   3 |

I want to produce the following View:

|id|transdate |B Value | A Value| AxB Value |
|--|--------- |--------|--------|-----------|
|1 |2021-01-03|    3   |    7   |     21    |
|2 |2021-01-10|    6   |    9   |     54    |
|3 |2021-01-20|    3   |    4   |     12    |

My Question, how to get Table A Value inside of that view, based on that transaction date within Table A Date From and Date To?

Body:
Use between to match the date ranged in A:

select
  b.id,
  b.transdate,
  b.value as b_value,
  a.value as a_value,
  b.value * a.value as a_x_b_value
from table_b b
join table_a a on a.id = b.id
  and b.transdate between a.datefrom and a.dateto

If there is a possibility there won't be a matching row in A, use a left join with a default of (say) 1 for the A value:

select
  b.id,
  b.transdate,
  b.value as b_value,
  a.value as a_value,
  b.value * coalesce(a.value, 1) as a_x_b_value
from table_b b
left join table_a a on a.id = b.id
  and b.transdate between a.datefrom and a.dateto


问:
How do you control size of imported SVG's in Three.js?
I am importing an SVG using the SVGLoader and turning each path into a mesh that is then put into a group. When I do so, the group is much larger than I would like it to be. Rather than scaling, I'd like to import it at the correct size to begin with. When I change the width and height attributes on the SVG: <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25"> nothing changes with respect to the size of the rendered meshes. I haven't seen anything actually describing how SVG sizes are determined by the loader. Is it a viewbox? Is there something special that has to be done?

答: In your 3d world, you can only change the size of your object by Object3D.scale.set(x, y, z),and the x, y, z value determine the size of your mesh in you 3d world. When you change the width and height attributes on the SVG, you can only change the resolution but not the size


问:
Using AES as a portable RNG with a truly random seed?
I am writing a service where a deterministic RNG is needed across multiple platforms that don't share a codebase (except for maybe C). The random numbers need to be exactly 128 bits long. Given a pre-negotiated truly random number, is it OK if I use AES to generate a sequence of random numbers? How it would work is I would encrypt the seed to get the first random number, encrypt the first random number to get the second, etc.

Basically:

```<code>rand[0] = truly_random_number;
rand[1] = AES(truly_random_number);
rand[2] = AES(AES(truly_random_number));
rand[n] = AES(AES(AES...AES(truly_random_number...))) //n times
</code>```

One argument AES here is defined as the plaintext always being all zeroes.

The clients will share their sequence number as they communicate, so it should be possible for any of them to deterministically reconstruct the needed result.

Is this a proper use of AES? Can I use something faster for this, like SHA-256 and truncate the result? Should I just find a C implementation of some RNG and use that instead? I am leaning toward AES because the platforms I am targeting have AES accelerators, so the speed should not be much of an issue.

答:
Given a pre-negotiated truly random number, is it OK if I use AES to generate a sequence of random numbers?

Yes; that's exactly what, at its core, symmetric cryptography is.

However, it's inappropriate to be using a custom construction like this one:

```<code>rand[n] = AES(AES(AES...AES(truly_random_number...))) //n times
</code>```

Instead, just use an established construction like Counter mode.

```<code>AES_ctr128_encrypt(all_zeroes, rand+n, 16, truly_random_number, &n, ecount_buf, 1)
</code>```

(The above snippet elides some serious detail. I don't know what library you're actually using. Hand-cranking AES in C is not easy.)

Python example of using AES in Counter mode as an RNG:

import Crypto.Cipher.AES

def rand_block(key: bytes, offset: int, *, nonce=b''):
    c = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CTR, nonce=nonce, initial_value=offset)
    return c.encrypt(bytes(Crypto.Cipher.AES.block_size))

# test value:
assert int.to_bytes(179565763088325722286336838177169761478, 16, 'little') == \
       rand_block(bytes.fromhex('000102030405060708090A0B0C0D0E0F'), 99)
```

Body:
I am writing a service where a deterministic RNG is needed across multiple platforms that don't share a codebase (except for maybe C). The random numbers need to be exactly 128 bits long. Given a pre-negotiated truly random number, is it OK if I use AES to generate a sequence of random numbers? How it would work is I would encrypt the seed to get the first random number, encrypt the first random number to get the second, etc.

Basically:

rand[0] = truly_random_number;
rand[1] = AES(truly_random_number);
rand[2] = AES(AES(truly_random_number));
rand[n] = AES(AES(AES...AES(truly_random_number...))) //n times

One argument AES here is defined as the plaintext always being all zeroes.

The clients will share their sequence number as they communicate, so it should be possible for any of them to deterministically reconstruct the needed result.

Is this a proper use of AES? Can I use something faster for this, like SHA-256 and truncate the result? Should I just find a C implementation of some RNG and use that instead? I am leaning toward AES because the platforms I am targeting have AES accelerators, so the speed should not be much of an issue.

Body:
Given a pre-negotiated truly random number, is it OK if I use AES to generate a sequence of random numbers?

Yes; that's exactly what, at its core, symmetric cryptography is.

However, it's inappropriate to be using a custom construction like this one:

rand[n] = AES(AES(AES...AES(truly_random_number...))) //n times

Instead, just use an established construction like Counter mode.

AES_ctr128_encrypt(all_zeroes, rand+n, 16, truly_random_number, &n, ecount_buf, 1)

(The above snippet elides some serious detail. I don't know what library you're actually using. Hand-cranking AES in C is not easy.)

Python example of using AES in Counter mode as an RNG:

import Crypto.Cipher.AES

def rand_block(key: bytes, offset: int, *, nonce=b''):
    c = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CTR, nonce=nonce, initial_value=offset)
    return c.encrypt(bytes(Crypto.Cipher.AES.block_size))

# test value:
assert int.to_bytes(179565763088325722286336838177169761478, 16, 'little') == \
       rand_block(bytes.fromhex('000102030405060708090A0B0C0D0E0F'), 99)


Title: How to switch elements in data.frame according to size?

Body:
I am looking for an R function that allows swapping two elements in a data frame under a certain constraint.

For example:

If I have a dataframe (5rows, 5cols) and I want that all elements in column 2 that are greater than the corresponding elements in column 3 to be swapped. As a result, all the elements of column 2 greater than those of column 3 would move to column 3 and vice-versa.

Your help is much appreciated.

Body:
You can use

set.seed(123)
x = as.data.frame(matrix(sample(1:25), nrow = 5))
#   V1 V2 V3 V4 V5
# 1 15 18  9 25  2
# 2 19 11 21 17 16
# 3 14  5 24  1  7
# 4  3 23 20 12  8
# 5 10  6 22 13  4

x[, 2:3] = t(apply(x[, 2:3], 1, sort))
#   V1 V2 V3 V4 V5
# 1 15  9 18 25  2
# 2 19 11 21 17 16
# 3 14  5 24  1  7
# 4  3 20 23 12  8
# 5 10  6 22 13  4