问:
'npm start' does not work anymore
My npm start does not work anymore, but I still worked with it yesterday. I also haven't changed anything, as far as I'm concerned. I'm using it to start up my react starter kit (facebooks official starterkit). What could it be?

```<code>> apicalltestapp@0.1.0 start /Users/.../reactapp
> react-scripts start

module.js:457
    throw err;
    ^

Error: Cannot find module 'cross-spawn'
    at Function.Module._resolveFilename (module.js:455:15)
    at Function.Module._load (module.js:403:25)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/reactapp/node_modules/.bin/react-scripts:2:13)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)

npm ERR! Darwin 15.6.0
npm ERR! argv "/Users/dswork/.nvm/versions/node/v6.7.0/bin/node" "/Users/dswork/.nvm/versions/node/v6.7.0/bin/npm" "start"
npm ERR! node v6.7.0
npm ERR! npm  v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! apicalltestapp@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the apicalltestapp@0.1.0 start script 'react-scripts start'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the apicalltestapp package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     react-scripts start
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs apicalltestapp
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls apicalltestapp
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/dswork/Coding/reactcafe/npm-debug.log
</code>```

here is the npm-debug.log:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/Users/dswork/.nvm/versions/node/v6.7.0/bin/node',
1 verbose cli   '/Users/dswork/.nvm/versions/node/v6.7.0/bin/npm',
1 verbose cli   'start' ]
2 info using npm@3.10.8
3 info using node@v6.7.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle apicalltestapp@0.1.0~prestart: apicalltestapp@0.1.0
6 silly lifecycle apicalltestapp@0.1.0~prestart: no script for prestart, continuing
7 info lifecycle apicalltestapp@0.1.0~start: apicalltestapp@0.1.0
8 verbose lifecycle apicalltestapp@0.1.0~start: unsafe-perm in lifecycle true
9 verbose lifecycle apicalltestapp@0.1.0~start: PATH: /Users/dswork/.nvm/versions/node/v6.7.0/lib/node_modules/npm/bin/node-gyp-bin:/Users/dswork/Coding/reactcafe/node_modules/.bin:/Users/dswork/.nvm/versions/node/v6.7.0/bin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
10 verbose lifecycle apicalltestapp@0.1.0~start: CWD: /Users/dswork/Coding/reactcafe
11 silly lifecycle apicalltestapp@0.1.0~start: Args: [ '-c', 'react-scripts start' ]
12 silly lifecycle apicalltestapp@0.1.0~start: Returned: code: 1  signal: null
13 info lifecycle apicalltestapp@0.1.0~start: Failed to exec start script
14 verbose stack Error: apicalltestapp@0.1.0 start: `react-scripts start`
14 verbose stack Exit status 1
14 verbose stack     at EventEmitter.<anonymous> (/Users/dswork/.nvm/versions/node/v6.7.0/lib/node_modules/npm/lib/utils/lifecycle.js:255:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:191:7)
14 verbose stack     at ChildProcess.<anonymous> (/Users/dswork/.nvm/versions/node/v6.7.0/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:191:7)
14 verbose stack     at maybeClose (internal/child_process.js:877:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid apicalltestapp@0.1.0
16 verbose cwd /Users/dswork/Coding/reactcafe
17 error Darwin 15.6.0
18 error argv "/Users/dswork/.nvm/versions/node/v6.7.0/bin/node" "/Users/dswork/.nvm/versions/node/v6.7.0/bin/npm" "start"
19 error node v6.7.0
20 error npm  v3.10.8
21 error code ELIFECYCLE
22 error apicalltestapp@0.1.0 start: `react-scripts start`
22 error Exit status 1
23 error Failed at the apicalltestapp@0.1.0 start script 'react-scripts start'.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the apicalltestapp package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error     react-scripts start
23 error You can get information on how to open an issue for this project with:
23 error     npm bugs apicalltestapp
23 error Or if that isn't available, you can get their info via:
23 error     npm owner ls apicalltestapp
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]
</code>```

答:
If nothing else helps,

create a new text file in project folder with the name .env

add SKIP_PREFLIGHT_CHECK=true

This will simply ignore the error and let you start with React :)

Title: 'npm start' does not work anymore

Body:
My npm start does not work anymore, but I still worked with it yesterday. I also haven't changed anything, as far as I'm concerned. I'm using it to start up my react starter kit (facebooks official starterkit). What could it be?

> apicalltestapp@0.1.0 start /Users/.../reactapp
> react-scripts start

module.js:457
    throw err;
    ^

Error: Cannot find module 'cross-spawn'
    at Function.Module._resolveFilename (module.js:455:15)
    at Function.Module._load (module.js:403:25)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/reactapp/node_modules/.bin/react-scripts:2:13)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)

npm ERR! Darwin 15.6.0
npm ERR! argv "/Users/dswork/.nvm/versions/node/v6.7.0/bin/node" "/Users/dswork/.nvm/versions/node/v6.7.0/bin/npm" "start"
npm ERR! node v6.7.0
npm ERR! npm  v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! apicalltestapp@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the apicalltestapp@0.1.0 start script 'react-scripts start'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the apicalltestapp package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     react-scripts start
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs apicalltestapp
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls apicalltestapp
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/dswork/Coding/reactcafe/npm-debug.log

here is the npm-debug.log:

0 info it worked if it ends with ok
1 verbose cli [ '/Users/dswork/.nvm/versions/node/v6.7.0/bin/node',
1 verbose cli   '/Users/dswork/.nvm/versions/node/v6.7.0/bin/npm',
1 verbose cli   'start' ]
2 info using npm@3.10.8
3 info using node@v6.7.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle apicalltestapp@0.1.0~prestart: apicalltestapp@0.1.0
6 silly lifecycle apicalltestapp@0.1.0~prestart: no script for prestart, continuing
7 info lifecycle apicalltestapp@0.1.0~start: apicalltestapp@0.1.0
8 verbose lifecycle apicalltestapp@0.1.0~start: unsafe-perm in lifecycle true
9 verbose lifecycle apicalltestapp@0.1.0~start: PATH: /Users/dswork/.nvm/versions/node/v6.7.0/lib/node_modules/npm/bin/node-gyp-bin:/Users/dswork/Coding/reactcafe/node_modules/.bin:/Users/dswork/.nvm/versions/node/v6.7.0/bin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
10 verbose lifecycle apicalltestapp@0.1.0~start: CWD: /Users/dswork/Coding/reactcafe
11 silly lifecycle apicalltestapp@0.1.0~start: Args: [ '-c', 'react-scripts start' ]
12 silly lifecycle apicalltestapp@0.1.0~start: Returned: code: 1  signal: null
13 info lifecycle apicalltestapp@0.1.0~start: Failed to exec start script
14 verbose stack Error: apicalltestapp@0.1.0 start: `react-scripts start`
14 verbose stack Exit status 1
14 verbose stack     at EventEmitter.<anonymous> (/Users/dswork/.nvm/versions/node/v6.7.0/lib/node_modules/npm/lib/utils/lifecycle.js:255:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:191:7)
14 verbose stack     at ChildProcess.<anonymous> (/Users/dswork/.nvm/versions/node/v6.7.0/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:191:7)
14 verbose stack     at maybeClose (internal/child_process.js:877:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid apicalltestapp@0.1.0
16 verbose cwd /Users/dswork/Coding/reactcafe
17 error Darwin 15.6.0
18 error argv "/Users/dswork/.nvm/versions/node/v6.7.0/bin/node" "/Users/dswork/.nvm/versions/node/v6.7.0/bin/npm" "start"
19 error node v6.7.0
20 error npm  v3.10.8
21 error code ELIFECYCLE
22 error apicalltestapp@0.1.0 start: `react-scripts start`
22 error Exit status 1
23 error Failed at the apicalltestapp@0.1.0 start script 'react-scripts start'.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the apicalltestapp package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error     react-scripts start
23 error You can get information on how to open an issue for this project with:
23 error     npm bugs apicalltestapp
23 error Or if that isn't available, you can get their info via:
23 error     npm owner ls apicalltestapp
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]


来源: stackexchange

问:
IIS - Allow IP range for a web application
I want to allow IP range to access my application on IIS. This IP range is owned by third party provider which sends me callback requests. They gave me an IP range to allow. This IP range is XXX.XXX.XXX.0/24. How should I fill these values to allow this range?

答:
To create a rule for a range of IP addresses, select the IP address range, and enter the subnet and subnet mask in the provided textboxes. For example, to permit access to all IP addresses in the range from 192.168.8.0 to 192.168.8.8 then enter the subnet as 192.168.8.0 and subnet mask as the 255.0.0.0.

To calculate the subnet mask you could use the subnet mask online calculator it is easy to use and get the exact value:

https://www.subnetonline.com/pages/subnet-calculators/subnetmask-calculator.php

If you do not have much idea about the subnet mask and its configuration you could use the iis URL rewrite rule by following below steps:

1)First, download and install iis URL rewrite extension from the below link:

https://www.iis.net/downloads/microsoft/url-rewrite

2)Open iis manager and select your site.

3)From the pane, double-click the URL Rewrite icon.

4)On the URL Rewrite pane, on the Actions section in the upper right corner, click Add Rule(s) to create the first rule (i.e. to allow internal access).

5)add the blank rule as shown below:

6)Now click on apply go back and click on add rule.

7)Click on the requests blocking rule:

8) In the Add Request Blocking Rule dialog, select IP Address from the Block access based on dropdown

Select Matches the Pattern from the Block request that dropdown

Enter the first internal Pattern (IP Address) to allow, using " * " (asterisk) to enable a wildcard

Select Wildcards from the Using dropdown, if enabling wildcards

Click OK

Click ok and refresh your site.

your rule will look like below in web.config file:

```<code><rule name="Allow rule" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <conditions>
                    <add input="{REMOTE_ADDR}" pattern="159.247.25.*" />
                    <add input="{REMOTE_ADDR}" pattern="10.1.*.*" />
                    <add input="{REMOTE_ADDR}" pattern="127.0.0.1" />
                </conditions>
                <action type="None" />
            </rule>
            <rule name="RequestBlockingRule1" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <conditions>
                    <add input="{REMOTE_ADDR}" pattern="*" />
                </conditions>
                <action type="CustomResponse" statusCode="403" statusReason="Forbidden: Access is denied." statusDescription="You do not have permission to view this directory or page using the credentials that you supplied." />
            </rule>
</code>```

for more detail please refer below link:

IP Address and Domain Restrictions

IIS ban IP range

Understanding TCP/IP addressing and subnetting basics

ContentLicense: CC BY-SA 4.0

Body:
To create a rule for a range of IP addresses, select the IP address range, and enter the subnet and subnet mask in the provided textboxes. For example, to permit access to all IP addresses in the range from 192.168.8.0 to 192.168.8.8 then enter the subnet as 192.168.8.0 and subnet mask as the 255.0.0.0.

To calculate the subnet mask you could use the subnet mask online calculator it is easy to use and get the exact value:

https://www.subnetonline.com/pages/subnet-calculators/subnetmask-calculator.php

If you do not have much idea about the subnet mask and its configuration you could use the iis URL rewrite rule by following below steps:

1)First, download and install iis URL rewrite extension from the below link:

https://www.iis.net/downloads/microsoft/url-rewrite

2)Open iis manager and select your site.

3)From the pane, double-click the URL Rewrite icon.

4)On the URL Rewrite pane, on the Actions section in the upper right corner, click Add Rule(s) to create the first rule (i.e. to allow internal access).

5)add the blank rule as shown below:

6)Now click on apply go back and click on add rule.

7)Click on the requests blocking rule:

8) In the Add Request Blocking Rule dialog, select IP Address from the Block access based on dropdown

Select Matches the Pattern from the Block request that dropdown

Enter the first internal Pattern (IP Address) to allow, using " * " (asterisk) to enable a wildcard

Select Wildcards from the Using dropdown, if enabling wildcards

Click OK

Click ok and refresh your site.

your rule will look like below in web.config file:

<rule name="Allow rule" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <conditions>
                    <add input="{REMOTE_ADDR}" pattern="159.247.25.*" />
                    <add input="{REMOTE_ADDR}" pattern="10.1.*.*" />
                    <add input="{REMOTE_ADDR}" pattern="127.0.0.1" />
                </conditions>
                <action type="None" />
            </rule>
            <rule name="RequestBlockingRule1" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <conditions>
                    <add input="{REMOTE_ADDR}" pattern="*" />
                </conditions>
                <action type="CustomResponse" statusCode="403" statusReason="Forbidden: Access is denied." statusDescription="You do not have permission to view this directory or page using the credentials that you supplied." />
            </rule>

for more detail please refer below link:

IP Address and Domain Restrictions

IIS ban IP range

Understanding TCP/IP addressing and subnetting basics


问:
UPDATE-FROM clause in jOOQ throws an exception for comparing data types
I have a problem when accessing values in UPDATE-FROM clause in jOOQ. I want to convert following PostgreSQL query:

```<code>UPDATE book
SET amount = bat.amount
FROM (
    VALUES (2, 136),(5, 75)
) AS bat(book_id, amount)
WHERE book.book_id = bat.book_id;
</code>```

VALUES inside of FROM-clause are being created from Map bookIdsAmountMap parameter and I am trying to perform that this way:
This is what I have done in my code so far (by Lukas Eder answer suggestion) made in this question:

```<code>Row2<Long,Integer> array[] = new Row2[bookIdAmountMap.size()];
int i = 0;
for (Map.Entry<Long, Integer> pair : bookIdAmountMap.entrySet()) {
    array[i] = DSL.row(pair.getKey(), pair.getValue());
    i++;
}
Table<Record2<Long, Integer>> bat = DSL.values(array);
bat = bat.as("bat", "book_id", "amount");
Field<Long> bookIdField = DSL.field(DSL.name("bat", "book_id"), Long.class);
Field<Integer> amountField = DSL.field(DSL.name("bat", "amount"), Integer.class);

ctx.update(BOOK).set(BOOK.AMOUNT, amountField).from(bat) // same result as if I am using in .from(bat.as("bat", "book_id", "amount"))
                .where(BOOK.BOOK_ID.eq(bookIdField));
</code>```

When I execute Java code I get following exception:

operator does not exist: bigint = text

Any help/advice on solving this issue is greatly appreciated. :)

答:
This issue seems related to a known issue where PostgreSQL cannot guess the right data type from a jOOQ VALUES expression. I will need to investigate this further, and will update my answer.

A workaround is to cast your bind values to the appropriate data type explicitly:

array[i] = DSL.row(
  DSL.val(pair.getKey()).cast(SQLDataType.BIGINT),
  DSL.val(pair.getValue()).cast(SQLDataType.INTEGER)
);
```

Body:
I have a problem when accessing values in UPDATE-FROM clause in jOOQ. I want to convert following PostgreSQL query:

UPDATE book
SET amount = bat.amount
FROM (
    VALUES (2, 136),(5, 75)
) AS bat(book_id, amount)
WHERE book.book_id = bat.book_id;

VALUES inside of FROM-clause are being created from Map bookIdsAmountMap parameter and I am trying to perform that this way:
This is what I have done in my code so far (by Lukas Eder answer suggestion) made in this question:

Row2<Long,Integer> array[] = new Row2[bookIdAmountMap.size()];
int i = 0;
for (Map.Entry<Long, Integer> pair : bookIdAmountMap.entrySet()) {
    array[i] = DSL.row(pair.getKey(), pair.getValue());
    i++;
}
Table<Record2<Long, Integer>> bat = DSL.values(array);
bat = bat.as("bat", "book_id", "amount");
Field<Long> bookIdField = DSL.field(DSL.name("bat", "book_id"), Long.class);
Field<Integer> amountField = DSL.field(DSL.name("bat", "amount"), Integer.class);

ctx.update(BOOK).set(BOOK.AMOUNT, amountField).from(bat) // same result as if I am using in .from(bat.as("bat", "book_id", "amount"))
                .where(BOOK.BOOK_ID.eq(bookIdField));

When I execute Java code I get following exception:

operator does not exist: bigint = text

Any help/advice on solving this issue is greatly appreciated. :)


问:
Group the csv file by list
Hi I'm struggling with my csv file and want to group it by it's mode.
Here's me csv file:

[Temperature],[Fan],[Mode],[Louver],[Swing]

```<code>16, auto,   cool,   auto,   auto,
16, auto,   cool,   auto,   auto,
16, auto,   cool,   auto,   auto,
16, auto,   cool,   auto,   off,
16, auto,   cool,   auto,   auto,
16, auto,   cool,   off,    auto,
16, auto,   cool,   auto,   auto,
16, high,   cool,   auto,   auto,
16, med,    cool,   auto,   auto,
16, low,    cool,   auto,   auto,
16, auto,   cool,   auto,   auto,
17, auto,   cool,   auto,   auto,
18, auto,   cool,   auto,   auto,
19, auto,   cool,   auto,   auto,
20, auto,   cool,   auto,   auto,
21, auto,   cool,   auto,   auto,
22, auto,   cool,   auto,   auto,
23, auto,   cool,   auto,   auto,
24, auto,   cool,   auto,   auto,
25, auto,   cool,   auto,   auto,
26, auto,   cool,   auto,   auto,
27, auto,   cool,   auto,   auto,
28, auto,   cool,   auto,   auto,
29, auto,   cool,   auto,   auto,
30, auto,   cool,   auto,   auto,
29, auto,   cool,   auto,   auto,
28, auto,   cool,   auto,   auto,
27, auto,   cool,   auto,   auto,
2,  auto,   dry,    auto,   auto,
1,  auto,   dry,    auto,   auto,
0,  auto,   dry,    auto,   auto,
-1, auto,   dry,    auto,   auto,
-2, auto,   dry,    auto,   auto,
2,  auto,   auto,   auto,   auto,
1,  auto,   auto,   auto,   auto,
0,  auto,   auto,   auto,   auto,
-1, auto,   auto,   auto,   auto,
-2, auto,   auto,   auto,   auto,
</code>```

I want to have an output like this and program it using python

[Mode], [Temperature], [Fan], [Louver], [Swing]

```<code>['dry'], ['2', '1', '0', '-1', '-2'], ['auto'], ['auto'], ['auto']
['auto'], ['2', '1', '0', '-1', '-2'], ['auto'], ['auto'], ['auto']
['cool'], ['16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30'], ['auto', 'high', 'med', 'low'], ['auto', 'off'], ['auto', 'off']
</code>```

答:
python's pandas library is the answer.

```<code>import pandas as pd
df = pd.read_csv(your_csv_path)
grouped = df.groupby([Mode]) # you can group them in the sequence you like
</code>```

you can access elements of this groupby object, simply by grouped.get_group(['dry']) or whatever you may wish

Title: Group the csv file by list

Body:
Hi I'm struggling with my csv file and want to group it by it's mode.
Here's me csv file:

[Temperature],[Fan],[Mode],[Louver],[Swing]

16, auto,   cool,   auto,   auto,
16, auto,   cool,   auto,   auto,
16, auto,   cool,   auto,   auto,
16, auto,   cool,   auto,   off,
16, auto,   cool,   auto,   auto,
16, auto,   cool,   off,    auto,
16, auto,   cool,   auto,   auto,
16, high,   cool,   auto,   auto,
16, med,    cool,   auto,   auto,
16, low,    cool,   auto,   auto,
16, auto,   cool,   auto,   auto,
17, auto,   cool,   auto,   auto,
18, auto,   cool,   auto,   auto,
19, auto,   cool,   auto,   auto,
20, auto,   cool,   auto,   auto,
21, auto,   cool,   auto,   auto,
22, auto,   cool,   auto,   auto,
23, auto,   cool,   auto,   auto,
24, auto,   cool,   auto,   auto,
25, auto,   cool,   auto,   auto,
26, auto,   cool,   auto,   auto,
27, auto,   cool,   auto,   auto,
28, auto,   cool,   auto,   auto,
29, auto,   cool,   auto,   auto,
30, auto,   cool,   auto,   auto,
29, auto,   cool,   auto,   auto,
28, auto,   cool,   auto,   auto,
27, auto,   cool,   auto,   auto,
2,  auto,   dry,    auto,   auto,
1,  auto,   dry,    auto,   auto,
0,  auto,   dry,    auto,   auto,
-1, auto,   dry,    auto,   auto,
-2, auto,   dry,    auto,   auto,
2,  auto,   auto,   auto,   auto,
1,  auto,   auto,   auto,   auto,
0,  auto,   auto,   auto,   auto,
-1, auto,   auto,   auto,   auto,
-2, auto,   auto,   auto,   auto,

I want to have an output like this and program it using python

[Mode], [Temperature], [Fan], [Louver], [Swing]

['dry'], ['2', '1', '0', '-1', '-2'], ['auto'], ['auto'], ['auto']
['auto'], ['2', '1', '0', '-1', '-2'], ['auto'], ['auto'], ['auto']
['cool'], ['16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30'], ['auto', 'high', 'med', 'low'], ['auto', 'off'], ['auto', 'off']

Body:
python's pandas library is the answer.

import pandas as pd
df = pd.read_csv(your_csv_path)
grouped = df.groupby([Mode]) # you can group them in the sequence you like

you can access elements of this groupby object, simply by grouped.get_group(['dry']) or whatever you may wish


问:
In css, how we can fixed width(in full 100% not in px) of a div which have property is position fixed
In css, how we can fixed width(in full 100% not in px) of a div which have property is position fixed inside the  div which already used postion absolute property.

let me know about its. this issue I am facing for long time.Is there any solution of this?

答:
I'm not sure if this is what you want but I find a solution on this post : Set width of a "Position: fixed" div relative to parent div

It use width:inherit

.parent {
  background-color: red;
  width: 200px;
  height: 200px;
  position: absolute;
  left: 20px;
  top: 20px;
}

.child {
  background-color: blue;
  position: fixed;
  width:inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">test</div>
</div></code>```

Body:
I'm not sure if this is what you want but I find a solution on this post : Set width of a "Position: fixed" div relative to parent div

It use width:inherit

.parent {
  background-color: red;
  width: 200px;
  height: 200px;
  position: absolute;
  left: 20px;
  top: 20px;
}

.child {
  background-color: blue;
  position: fixed;
  width:inherit;
}

<div class="parent">
  <div class="child">test</div>
</div>


问:
javafx.scene.control.Dialog<R> won't close on pressing "x"
If I just create an empty class extending from javafx.scene.control.Dialog<R>, it won't close when I'm pressing the "x" button in the top right corner.

How do I implement this behaviour? The API seems to tell me that I need to implement a close button. But in my case I don't want a close button, I just want to close the window with the x button or by pressing ESC. Is this possible?

答:
I have faced this situation with alerts with the below code.

```<code>Alert alert = new Alert(Alert.AlertType.NONE);
     alert.setTitle("Export Successful");
     alert.setContentText("All the posts have been exported to Posts.txt file
 successfully");
    alert.show();
</code>```

The only workaround would be to create an alert or dialog with a button in it like below.

```<code>Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setTitle("Export Successful");
    alert.setContentText("All the posts have been exported to Posts.txt file
successfully");
    alert.showAndWait();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have faced this situation with alerts with the below code.

Alert alert = new Alert(Alert.AlertType.NONE);
     alert.setTitle("Export Successful");
     alert.setContentText("All the posts have been exported to Posts.txt file
 successfully");
    alert.show();

The only workaround would be to create an alert or dialog with a button in it like below.

Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setTitle("Export Successful");
    alert.setContentText("All the posts have been exported to Posts.txt file
successfully");
    alert.showAndWait();


问:
What's the difference between "number" and Number in javascript when iterating over an object?
here's an object.

```<code>let menu = {
  width: 200,
  height: 300,
  title: "My menu"
};
</code>```

that's the right code

```<code>function multiplyNumeric(obj) {
  for (let key in obj) {
    if (typeof obj[key] == 'number') {
      obj[key] *= 2;
    }
  }
}
</code>```

and here's my code

```<code>function multiplyNumeric(obj) {
      for (let key in obj) {
        if (typeof(obj[key]) === Number) {
          obj[key] *= 2;
        }
      }
    }
</code>```

Please tell me what makes the difference?

答:
The Number() is Javascript function converts the object argument to a number that represents the object's value.
If the value cannot be converted to a legal number, NaN is returned.

typeof(obj[key]) function returns, what kind of type the value is, like 'number' and string etc

Body:
here's an object.

let menu = {
  width: 200,
  height: 300,
  title: "My menu"
};

that's the right code

function multiplyNumeric(obj) {
  for (let key in obj) {
    if (typeof obj[key] == 'number') {
      obj[key] *= 2;
    }
  }
}

and here's my code

function multiplyNumeric(obj) {
      for (let key in obj) {
        if (typeof(obj[key]) === Number) {
          obj[key] *= 2;
        }
      }
    }

Please tell me what makes the difference?


问:
Get List of Last 15 Days Date in SQL
Could SQL get list of date of last 15 days date in a single query?

We can get today date with

select current_date()

We also can get last 15 days date with

select date_add(current_date(), -15)

But how to show the list of last 15 days date?
For example the output is

```<code>2020-05-17,
2020-05-18,
2020-05-19,
2020-05-20,
2020-05-21,
2020-05-22,
2020-05-23,
2020-05-24,
2020-05-25,
2020-05-26,
2020-05-27,
2020-05-28,
2020-05-29,
2020-05-30,
2020-05-31
</code>```

答:
WITH
cte AS ( SELECT 1 num UNION ALL SELECT 2 UNION ALL ... UNION ALL SELECT 15 )
SELECT DATEADD(CURRENT_DATE(), -num)
FROM cte;
```

<p>Or, for example</p>

<pre class="lang-sql prettyprint-override"><code>WITH
cte1 AS ( SELECT 1 num UNION ALL
          SELECT 2 UNION ALL
          SELECT 3 UNION ALL
          SELECT 4 UNION ALL
          SELECT 5 ),
cte2 AS ( SELECT 0 num
          UNION ALL SELECT 1
          UNION ALL SELECT 2 )
SELECT DATEADD(CURRENT_DATE(), -cte1.num - cte2.num * 5)
FROM cte1, cte2;
</code>```

Title: Get List of Last 15 Days Date in SQL

Body:
Could SQL get list of date of last 15 days date in a single query?

We can get today date with

select current_date()

We also can get last 15 days date with

select date_add(current_date(), -15)

But how to show the list of last 15 days date?
For example the output is

2020-05-17,
2020-05-18,
2020-05-19,
2020-05-20,
2020-05-21,
2020-05-22,
2020-05-23,
2020-05-24,
2020-05-25,
2020-05-26,
2020-05-27,
2020-05-28,
2020-05-29,
2020-05-30,
2020-05-31

Body:
WITH
cte AS ( SELECT 1 num UNION ALL SELECT 2 UNION ALL ... UNION ALL SELECT 15 )
SELECT DATEADD(CURRENT_DATE(), -num)
FROM cte;

Or, for example

WITH
cte1 AS ( SELECT 1 num UNION ALL
          SELECT 2 UNION ALL
          SELECT 3 UNION ALL
          SELECT 4 UNION ALL
          SELECT 5 ),
cte2 AS ( SELECT 0 num
          UNION ALL SELECT 1
          UNION ALL SELECT 2 )
SELECT DATEADD(CURRENT_DATE(), -cte1.num - cte2.num * 5)
FROM cte1, cte2;


问:
How to write a dockerfile in CentOS7 from scratch
I need to build an image on an application for CentOS7 . Following the docker documentation I have performed following steps:

Installed docker on my centos7 machine

Created new folder

Now I want to start writing the docker file for application xyz.  My questions are :

Do I need to create a new file name xyz.dockerfile ( touch xyz.dockerfile and them vim ) and then start writing a command ? or simple create a new dockerfile ( touch dockerfile)

How can I display comments while for multiple operations while executing this dockerfile ?

What will be CMD parameters if first task I need to perform is download yum repository ( rpm -ivh abc.rpm) in my dockerfile?

Any help will be appreciated. Thank you.

答:
Thank you @DavidMaze and @hdhruna for your help.

so for my first question, I understood that dockerfile doesn't have any extension. I have looked into various links :

How to name Dockerfiles

What is the .dockerfile extension?

it was helpful


问:
How to wait for onPaint to finish painting (C#)
Hi based on the thread here: How to create a jpg image dynamically in memory with .NET?

I have this method:

```<code>        int maxVal = 50;
        int maxXCells = r.Next(maxVal);
        int maxYCells = r.Next(maxVal);
        int cellXPosition = r.Next(maxVal);
        int cellYPosition = r.Next(maxVal);
        int boxSize = 10;

        Graphics fg = this.CreateGraphics();

        using (var bmp = new System.Drawing.Bitmap(maxXCells * boxSize + 1, maxYCells * boxSize + 1))
        {

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.Yellow);
                Pen pen = new Pen(Color.Black);
                pen.Width = 1;

                //Draw red rectangle to go behind cross
                Rectangle rect = new Rectangle(boxSize * (cellXPosition - 1), boxSize * (cellYPosition - 1), boxSize, boxSize);
                g.FillRectangle(new SolidBrush(Color.Red), rect);

                //Draw cross
                g.DrawLine(pen, boxSize * (cellXPosition - 1), boxSize * (cellYPosition - 1), boxSize * cellXPosition, boxSize * cellYPosition);
                g.DrawLine(pen, boxSize * (cellXPosition - 1), boxSize * cellYPosition, boxSize * cellXPosition, boxSize * (cellYPosition - 1));

                //Draw horizontal lines
                for (int i = 0; i <= maxXCells; i++)
                {
                    g.DrawLine(pen, (i * boxSize), 0, i * boxSize, boxSize * maxYCells);
                }

                //Draw vertical lines
                for (int i = 0; i <= maxYCells; i++)
                {
                    g.DrawLine(pen, 0, (i * boxSize), boxSize * maxXCells, i * boxSize);
                }
            }
            fg.DrawImage(bmp, 0, 0);
            fg.Dispose();

        }
</code>```

It fires based on the random event (can be many times in a second). What should I do, to  draw a new image only after current drawing has finished? At the moment, I can seen, that if the event to run this method fires faster than drawing has finished, the screen flickers. What are the common solution to avoiding drawing before previous drawing has finished?

This what I included in OnPaint method:

```<code>   protected override void OnPaint(System.Windows.Forms.PaintEventArgs pe)
    {
        finishedInvalidating = false;
        fg = this.CreateGraphics();
        lock (bmp)
        {
            fg.DrawImage(bmp, 0, 0);
        }
        fg.Dispose();
        finishedInvalidating = true;
</code>```

But this does not solve the problem

---------------------- update ------------------

```<code> public partial class LadderFrm : Form
{
    Bitmap bmp;

    int numCols = 3;
    int colWidth = 100;
    int numRows = 30;
    int rowHeight = 20;
    bool finishedInvalidating = false;

    decimal lastprice;

    public LadderFrm()
    {
        bmp = new System.Drawing.Bitmap(numCols * colWidth + 1, numRows * rowHeight + 1);
        prepareLadderGraphics();
    }

    // prepare initial ladder background
    private void prepareLadderGraphics()
    {

        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.Clear(Color.LightGray);
            Pen pen = new Pen(Color.Black);
            pen.Width = 1;

            // drawCells
            for (int i = 0; i < numCols; i++)
            {
                for (int j = 0; j < numRows; j++)
                {
                    Rectangle rect = new Rectangle(i * colWidth, j * rowHeight, colWidth, rowHeight);
                    g.DrawRectangle(pen, rect);
                }
            }
            g.Dispose();
        }

    }

    protected override void OnPaint(System.Windows.Forms.PaintEventArgs pe)
    {
        Graphics fg = this.CreateGraphics();
        lock (fg)
        {
            lock (bmp)
            {
                fg.DrawImage(bmp, 0, 0);
            }
        }
        fg.Dispose();
    }

    public void OrderBookUpdateFn(OrderBookEvent orderBookEvent)
    {

        if (lastprice != orderBookEvent.ValuationAskPrice)
        {
            lastprice = orderBookEvent.ValuationAskPrice;
            lock (bmp)
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    Pen pen = new Pen(Color.Black);
                    pen.Width = 1;
                    for (int i = 0; i < numRows; i++)
                    {
                        Rectangle rect = new Rectangle(colWidth + 1, i*rowHeight + 1, colWidth - 1, rowHeight - 1);
                        g.FillRectangle(new SolidBrush(Color.LightGray), rect);
                        g.DrawString(lastPrice.ToString(), new Font(FontFamily.GenericSansSerif, 10), new SolidBrush(Color.Black), new Point(colWidth + 1, i*rowHeight + 1));
                    }
                    g.Dispose();
                }
                this.Invalidate(new Rectangle(0, 0, 1, 1));
            }
    }
}
</code>```

Above code works, pretty well, however I am not sure if its correct. This is just for test purpose. Method OrderBookUpdateFn(OrderBookEvent orderBookEvent) gets fired very often (sometimes tens of times a second).

答:
You could try overriding the OnPaint method, call base.OnPaint(); and then do your manual painting after.</p>

```<code>protected override void OnPaint(PaintEventArgs e)
{
   // call base
   base.OnPaint(e);

   // Do your stuff after the rest has been painted
   if(this.picture != null && this.pictureLocation != Point.Empty)
   {
      e.Graphics.DrawImage(this.picture, this.pictureLocation);
   }
}
</code>```

Body:
Hi based on the thread here: How to create a jpg image dynamically in memory with .NET?

I have this method:

        int maxVal = 50;
        int maxXCells = r.Next(maxVal);
        int maxYCells = r.Next(maxVal);
        int cellXPosition = r.Next(maxVal);
        int cellYPosition = r.Next(maxVal);
        int boxSize = 10;

        Graphics fg = this.CreateGraphics();

        using (var bmp = new System.Drawing.Bitmap(maxXCells * boxSize + 1, maxYCells * boxSize + 1))
        {

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.Yellow);
                Pen pen = new Pen(Color.Black);
                pen.Width = 1;

                //Draw red rectangle to go behind cross
                Rectangle rect = new Rectangle(boxSize * (cellXPosition - 1), boxSize * (cellYPosition - 1), boxSize, boxSize);
                g.FillRectangle(new SolidBrush(Color.Red), rect);

                //Draw cross
                g.DrawLine(pen, boxSize * (cellXPosition - 1), boxSize * (cellYPosition - 1), boxSize * cellXPosition, boxSize * cellYPosition);
                g.DrawLine(pen, boxSize * (cellXPosition - 1), boxSize * cellYPosition, boxSize * cellXPosition, boxSize * (cellYPosition - 1));

                //Draw horizontal lines
                for (int i = 0; i <= maxXCells; i++)
                {
                    g.DrawLine(pen, (i * boxSize), 0, i * boxSize, boxSize * maxYCells);
                }

                //Draw vertical lines
                for (int i = 0; i <= maxYCells; i++)
                {
                    g.DrawLine(pen, 0, (i * boxSize), boxSize * maxXCells, i * boxSize);
                }
            }
            fg.DrawImage(bmp, 0, 0);
            fg.Dispose();

        }

It fires based on the random event (can be many times in a second). What should I do, to  draw a new image only after current drawing has finished? At the moment, I can seen, that if the event to run this method fires faster than drawing has finished, the screen flickers. What are the common solution to avoiding drawing before previous drawing has finished?

This what I included in OnPaint method:

   protected override void OnPaint(System.Windows.Forms.PaintEventArgs pe)
    {
        finishedInvalidating = false;
        fg = this.CreateGraphics();
        lock (bmp)
        {
            fg.DrawImage(bmp, 0, 0);
        }
        fg.Dispose();
        finishedInvalidating = true;

But this does not solve the problem

---------------------- update ------------------

 public partial class LadderFrm : Form
{
    Bitmap bmp;

    int numCols = 3;
    int colWidth = 100;
    int numRows = 30;
    int rowHeight = 20;
    bool finishedInvalidating = false;

    decimal lastprice;

    public LadderFrm()
    {
        bmp = new System.Drawing.Bitmap(numCols * colWidth + 1, numRows * rowHeight + 1);
        prepareLadderGraphics();
    }

    // prepare initial ladder background
    private void prepareLadderGraphics()
    {

        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.Clear(Color.LightGray);
            Pen pen = new Pen(Color.Black);
            pen.Width = 1;

            // drawCells
            for (int i = 0; i < numCols; i++)
            {
                for (int j = 0; j < numRows; j++)
                {
                    Rectangle rect = new Rectangle(i * colWidth, j * rowHeight, colWidth, rowHeight);
                    g.DrawRectangle(pen, rect);
                }
            }
            g.Dispose();
        }

    }

    protected override void OnPaint(System.Windows.Forms.PaintEventArgs pe)
    {
        Graphics fg = this.CreateGraphics();
        lock (fg)
        {
            lock (bmp)
            {
                fg.DrawImage(bmp, 0, 0);
            }
        }
        fg.Dispose();
    }

    public void OrderBookUpdateFn(OrderBookEvent orderBookEvent)
    {

        if (lastprice != orderBookEvent.ValuationAskPrice)
        {
            lastprice = orderBookEvent.ValuationAskPrice;
            lock (bmp)
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    Pen pen = new Pen(Color.Black);
                    pen.Width = 1;
                    for (int i = 0; i < numRows; i++)
                    {
                        Rectangle rect = new Rectangle(colWidth + 1, i*rowHeight + 1, colWidth - 1, rowHeight - 1);
                        g.FillRectangle(new SolidBrush(Color.LightGray), rect);
                        g.DrawString(lastPrice.ToString(), new Font(FontFamily.GenericSansSerif, 10), new SolidBrush(Color.Black), new Point(colWidth + 1, i*rowHeight + 1));
                    }
                    g.Dispose();
                }
                this.Invalidate(new Rectangle(0, 0, 1, 1));
            }
    }
}

Above code works, pretty well, however I am not sure if its correct. This is just for test purpose. Method OrderBookUpdateFn(OrderBookEvent orderBookEvent) gets fired very often (sometimes tens of times a second).

Body:
You could try overriding the OnPaint method, call base.OnPaint(); and then do your manual painting after.

protected override void OnPaint(PaintEventArgs e)
{
   // call base
   base.OnPaint(e);

   // Do your stuff after the rest has been painted
   if(this.picture != null && this.pictureLocation != Point.Empty)
   {
      e.Graphics.DrawImage(this.picture, this.pictureLocation);
   }
}


问:
How to update a label text with button inside a collection view in swift 4
I have a collection view inside a table view. There are two plus minus buttons in collection view cell. Now i have to update a label on the plus minus buttons action which is outside of table view. Thanks in advance.

I have to update a Slot: (label) by clicking on plus minus button.

I tried something like this with the delegate protocol.

I declare a delegate in my collection view class.

```<code> protocol SlotsCollectionViewCellDelegate: NSObjectProtocol {
func didTapOnIncrement(Int: Int)
func didTapOnDecrement(Int: Int)
</code>```

}

//after that,

```<code> var delegate: SlotsCollectionViewCellDelegate?

 @IBAction func plusBtnAction(_ sender: Any) {
     self.delegate?.didTapOnIncrement(Int: cartCount)
  }

   @IBAction func minusBtnAction(_ sender: Any) {
     delegate?.didTapOnDecrement(cell: self)
   }
</code>```

And in my Main View Controller

```<code>extension MainViewController: SlotsCollectionViewCellDelegate {

func didTapOnIncrement(Int: Int) {
       cartSlot_lbl.text = Int.description
     }

     func didTapOnDecrement(Int: Int) {
         cartSlot_lbl.text = Int.description
     }
</code>```

}

答:
I think delegates are the right choice for that. If it didn't work, please explain why and show some code, you probably forgot to set a delegate reference.

Anyway, here's some more thoughts:

You could use a Reactive Pattern, so that you create a Relay to store your current values, manipulate them by providing input (times etc.) and subscribe to them from the Class where the "Spot:" Label is implemented. Whenever your model changes, your  Spot Label will also be changed.

You could also implement something using Notifications. Basically speaking, the difference to using a reactive pattern is not that big, you simply have to care about the "notify" part yourself. Assuming you have something like a Singleton Pattern applied where you store your entire State (selected dates/times, slots etc.), you could do that like this:

extension Notification.Name {
    static let modelDidChange = Notification.Name("modelDidChange")
}
// where your model lies
struct YourModel {
    var slots: Int = 0

    static var singletonInstance: YourModel = YourModel() {
        // use the didSet block to react to changes made to the model
        didSet {
            // send a notification so all subscriber know something has changed
            NotificationCenter.default.post(.modelDidChange)
        }
    }
}

class YourViewControllerWhereTheLabelIs: UIViewController {
    // ...
    var slotLabel: UILabel?

    // ...
    init() {
        // wherever you initialize your viewcontroller,
        // you could also do it in viewWillAppear
        // subscribe to the notification to react to changes
        NotificationCenter.default.addObserver(self, selector: #selector(modelDidChange), name: .modelDidChange, object: nil)
    }

    deinit {
        // just don't forget to unsubscribe
        NotificationCenter.default.removeObserver(self)
    }

    @objc func modelDidChange() {
        // update your label here, this is called whenever YourModel.singletonInstance is changed
        self.slotLabel?.text = YourModel.singletonInstance.slots
    }
}

```

Hope that helps you or gives you an idea. If I can be of more help just let me know.

Body:
I have a collection view inside a table view. There are two plus minus buttons in collection view cell. Now i have to update a label on the plus minus buttons action which is outside of table view. Thanks in advance.

I have to update a Slot: (label) by clicking on plus minus button.

I tried something like this with the delegate protocol.

I declare a delegate in my collection view class.

 protocol SlotsCollectionViewCellDelegate: NSObjectProtocol {
func didTapOnIncrement(Int: Int)
func didTapOnDecrement(Int: Int)

}

//after that,

 var delegate: SlotsCollectionViewCellDelegate?

 @IBAction func plusBtnAction(_ sender: Any) {
     self.delegate?.didTapOnIncrement(Int: cartCount)
  }

   @IBAction func minusBtnAction(_ sender: Any) {
     delegate?.didTapOnDecrement(cell: self)
   }

And in my Main View Controller

extension MainViewController: SlotsCollectionViewCellDelegate {

func didTapOnIncrement(Int: Int) {
       cartSlot_lbl.text = Int.description
     }

     func didTapOnDecrement(Int: Int) {
         cartSlot_lbl.text = Int.description
     }

}

Body:
I think delegates are the right choice for that. If it didn't work, please explain why and show some code, you probably forgot to set a delegate reference.

Anyway, here's some more thoughts:

You could use a Reactive Pattern, so that you create a Relay to store your current values, manipulate them by providing input (times etc.) and subscribe to them from the Class where the "Spot:" Label is implemented. Whenever your model changes, your  Spot Label will also be changed.

You could also implement something using Notifications. Basically speaking, the difference to using a reactive pattern is not that big, you simply have to care about the "notify" part yourself. Assuming you have something like a Singleton Pattern applied where you store your entire State (selected dates/times, slots etc.), you could do that like this:

extension Notification.Name {
    static let modelDidChange = Notification.Name("modelDidChange")
}
// where your model lies
struct YourModel {
    var slots: Int = 0

    static var singletonInstance: YourModel = YourModel() {
        // use the didSet block to react to changes made to the model
        didSet {
            // send a notification so all subscriber know something has changed
            NotificationCenter.default.post(.modelDidChange)
        }
    }
}

class YourViewControllerWhereTheLabelIs: UIViewController {
    // ...
    var slotLabel: UILabel?

    // ...
    init() {
        // wherever you initialize your viewcontroller,
        // you could also do it in viewWillAppear
        // subscribe to the notification to react to changes
        NotificationCenter.default.addObserver(self, selector: #selector(modelDidChange), name: .modelDidChange, object: nil)
    }

    deinit {
        // just don't forget to unsubscribe
        NotificationCenter.default.removeObserver(self)
    }

    @objc func modelDidChange() {
        // update your label here, this is called whenever YourModel.singletonInstance is changed
        self.slotLabel?.text = YourModel.singletonInstance.slots
    }
}

Hope that helps you or gives you an idea. If I can be of more help just let me know.


问:
How to count substrings separarted by a delimitter in a dataframe column and push the value into a new column?
So, I have a dataframe like this

```<code>In [1]: df = pd.DataFrame([['indiejesse.d@gmail.com; pamelasilvera69@gmail.com; kristinestringer69@gmail.com', 'conference meeting ...']], columns=['CC', 'Body'])
</code>```

The column "CC" contains a list of emails separated by ";". I want to iterate through the "CC" column, count the number of emails separated by ";" in each of the rows and add a new column let's say "CC_count" after CC which contains the number CC emails of each row.

How do I do this?

答:
You could just count the amount of ; with str.count, add one and assign to a new column:

```<code>df['CC_count'] = df.CC.str.count(';').add(1)
</code>```

```<code>print(df)
                                               CC                    Body  \
0  indiejesse.d@gmail.com; pamelasilvera69@gmail....  conference meeting ...

   CC_count
0         3
</code>```

Body:
So, I have a dataframe like this

In [1]: df = pd.DataFrame([['indiejesse.d@gmail.com; pamelasilvera69@gmail.com; kristinestringer69@gmail.com', 'conference meeting ...']], columns=['CC', 'Body'])

The column "CC" contains a list of emails separated by ";". I want to iterate through the "CC" column, count the number of emails separated by ";" in each of the rows and add a new column let's say "CC_count" after CC which contains the number CC emails of each row.

How do I do this?

Body:
You could just count the amount of ; with str.count, add one and assign to a new column:

df['CC_count'] = df.CC.str.count(';').add(1)

print(df)
                                               CC                    Body  \
0  indiejesse.d@gmail.com; pamelasilvera69@gmail....  conference meeting ...

   CC_count
0         3


问:
Popup on mousehovor in Table - Angular
Added a class in

```<code>< td > <span class = "only-show-on-hover" > </ span > </ td >
</code>```

Code for the css class

```<code>td span.only-show-on-hover { visibility : hidden ; } td:hover span.only-show-on-hover { visibility : visible ; }
</code>```

Code for diaglog box

```<code>< div class = "bg-white mpd-container brs-6 p-2 pl-4" > < div class = "d-flex" > < div class = "mpd-pic" > < img width = "50" class = "mr-2 mt-2 " src = "assets/images/dummy-user.svg" alt = "" /> </ div > </ div > < div class = "d-flex my-2" > < div class = "profile-completion " > completion will go here </ div > </ div > </ div >
</code>```

How to open popup as given in image

I tried to add the dialogue box but it is showing inside td. I have show like popup as given in image

答:
```<code><td [ngbPopover]="popContent" [container]="'body'" triggers="mouseenter:mouseleave">Primary Role</td>

<ng-template #popContent>
<span>Profile</span>
<span>Academic Qualification</span>
<span>Technical Learning (2 Mandatory)</span>
</ng-template>
</code>```

for Reference : link
Working: Example

Title: Popup on mousehovor in Table - Angular

Body:
Added a class in

Code for the css class

td span.only-show-on-hover { visibility : hidden ; } td:hover span.only-show-on-hover { visibility : visible ; }

Code for diaglog box

 completion will go here

How to open popup as given in image

I tried to add the dialogue box but it is showing inside td. I have show like popup as given in image

Body:
<td [ngbPopover]="popContent" [container]="'body'" triggers="mouseenter:mouseleave">Primary Role</td>

<ng-template #popContent>
<span>Profile</span>
<span>Academic Qualification</span>
<span>Technical Learning (2 Mandatory)</span>
</ng-template>

for Reference : link
Working: Example


问:
Don't understand this TypeError while parsing json list
I have a json URL, I'm trying to parse it with Python, the output of the url looks like this:

```<code>"data": [
        {
            "config": {
                "add": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "append": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "http_method": null,
                "remove": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "rename": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "replace": {
                    "body": [],
                    "headers": [
                        "Host: jupyter.bbs-edsapp-p001.bbs.aphp.fr"
                    ],
                    "querystring": [],
                    "uri": null
                }
            },
            "consumer": null,
</code>```

My python script is :

```<code>import requests
import json

response = json.loads(requests.get("http://127.0.0.1:8001/services/6ca6c203-d3b6-46c7-94d6-cad435bbfd97/plugins").text)
for p in response['data']['config']['replace']:
    print('back: ' + headers[0])
    #print('name: ' + p['name'])
    #print(p['name'])
</code>```

I get this error:

for p in response['data']['config']['add']:
  TypeError: list indices must be integers or slices, not str.
```

答:
As response['data']is a list (not a dict), you should write response['data'][0]['config']['add'].

Of course, once you have seen it work, you should do better than putting a [0] blindly. For example,

iterate on the list elements

do some checks (is response['data'] a list, and does it contain exactly one element?)

Body:
I have a json URL, I'm trying to parse it with Python, the output of the url looks like this:

"data": [
        {
            "config": {
                "add": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "append": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "http_method": null,
                "remove": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "rename": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "replace": {
                    "body": [],
                    "headers": [
                        "Host: jupyter.bbs-edsapp-p001.bbs.aphp.fr"
                    ],
                    "querystring": [],
                    "uri": null
                }
            },
            "consumer": null,

My python script is :

import requests
import json

response = json.loads(requests.get("http://127.0.0.1:8001/services/6ca6c203-d3b6-46c7-94d6-cad435bbfd97/plugins").text)
for p in response['data']['config']['replace']:
    print('back: ' + headers[0])
    #print('name: ' + p['name'])
    #print(p['name'])

I get this error:

for p in response['data']['config']['add']:
  TypeError: list indices must be integers or slices, not str.


问:
Time-based style changer how can I do it
Can someone explain me how to do a Time-based style changer in Javascript ? I've tried to do a test but it doesn't work. It only change the style when I manually modify in the code ">" to "<" in the if statement
This is the code I used</p>

```<code>var myDate = new Date();

        if(myDate.getHours() < 11.25) {

            document.getElementById('box').style.backgroundColor = "red";

        } else {

            document.getElementById('box').style.backgroundColor = "black";

        }
</code>```

答:
To further elabourate on my comment: getHours() returns an integer only, so it will always return 11 or 12 (and etc.), and never a fraction of an hour:

An integer number, between 0 and 23, representing the hour for the given date according to local time.

Therefore, comparing it against a non-integer value doesn't make a lot of sense in your case.

If you want to set up the if statement such that a certain style should be applied before a quarter past 11, then you need to compare it against getMinutes() too. This is assuming that by 11.25 you mean 11 hour + 0.25 hour, where 0.25h = 15mins:

```<code>if (myDate.getHours() === 11 && myDate.getMinutes() < 15 || myDate.getHours() < 11) {
  // Logic here
}
</code>```

Body:
Can someone explain me how to do a Time-based style changer in Javascript ? I've tried to do a test but it doesn't work. It only change the style when I manually modify in the code ">" to "<" in the if statement
This is the code I used

var myDate = new Date();

        if(myDate.getHours() < 11.25) {

            document.getElementById('box').style.backgroundColor = "red";

        } else {

            document.getElementById('box').style.backgroundColor = "black";

        }

Body:
To further elabourate on my comment: getHours() returns an integer only, so it will always return 11 or 12 (and etc.), and never a fraction of an hour:

An integer number, between 0 and 23, representing the hour for the given date according to local time.

Therefore, comparing it against a non-integer value doesn't make a lot of sense in your case.

If you want to set up the if statement such that a certain style should be applied before a quarter past 11, then you need to compare it against getMinutes() too. This is assuming that by 11.25 you mean 11 hour + 0.25 hour, where 0.25h = 15mins:

if (myDate.getHours() === 11 && myDate.getMinutes() < 15 || myDate.getHours() < 11) {
  // Logic here
}


答:
response['data'] is a list. If you only expect a single entry, you can use response['data'][0]['config']['add'].

I don't know whether there are other entries in data. You may want to check specifically which entry of the data contains config.
E.g.

```<code>for entry in response['data']:
   if 'config' in entry:
      replace_entry = entry['config']['replace']
      # Get the host header entry
      headers = replace_entry['headers']
      host = [h for h in headers if h.startswith('Host: ')][0]
</code>```

Title: Don't understand this TypeError while parsing json list

Body:
response['data'] is a list. If you only expect a single entry, you can use response['data'][0]['config']['add'].

I don't know whether there are other entries in data. You may want to check specifically which entry of the data contains config.
E.g.

for entry in response['data']:
   if 'config' in entry:
      replace_entry = entry['config']['replace']
      # Get the host header entry
      headers = replace_entry['headers']
      host = [h for h in headers if h.startswith('Host: ')][0]


问:
React Native cannot update State Hook with data from AsyncStorage
Hello im currently learning AsyncStorage in react native.
so i write some state like this

```<code>const [isLoading,setIsLoading] = useState(true)
const [id, setId] = useState(null)
</code>```

i set it null because i want to get the id from AsyncStorage, so i write a simple function to get and set the value  like this :

```<code>async function getAsyncStorageId(){
  const userId = await AsyncStorage.getItem('id')
  console.log('user id from AsyncStorage is: ',userId)
  setId(userId)
  console.log('state hooks id : ',id)
}
</code>```

and i put it into useEffect Hooks

```<code> useEffect(()=>{
  getAsyncStorageId()
 },[])
</code>```

so i test my code the id state wont update it stay null, but the console.log(userId) have an id value.

```<code>user id from AsyncStorage is:  6
state hooks id :  null
</code>```

i dont know why i cant set the state with value from the asyncstorage

=======================
*edit : this is the code that i used to set the id in AsyncStorage.
i put this code in my Login Screen, so when the user succesfully login i store the id, username, token, and role in async storage

```<code>const login = async () => {
try {
  let response = await axios.post(`${url}/users/login`, {
    email: props.email,
    password: props.password,
  });
  let loginData = response.data;
  console.log(loginData,'sukses login')
  setAsyncStorage('token',loginData.token)
  loginData.name === null ? setAsyncStorage('name', 'pengguna') : setAsyncStorage('name',loginData.name)
  setAsyncStorage('role', loginData.role)
  setAsyncStorage('id', loginData.id)

  props.navigation.navigate("Artikel",{
    id:loginData.id,
    token:loginData.token,
    name:loginData.name
  })

} catch (error) {
  console.log('error login',props.email,props.password);
  alert(error.response.data.message)
}
</code>```

};

export const setAsyncStorage = async (key, value) => {
  try {
    await AsyncStorage.setItem(`${key}`, `${value}`);
  } catch (error) {
    console.log(error);
  }
};```
</div>
</div>
</p>

<p>=============== update 2=========================</p>

<p>so i've tried change id value in login function into string like this </p>

```const login = async () => {
try {
  let response = await axios.post(`${url}/users/login`, {
    email: props.email,
    password: props.password,
  });
  let loginData = response.data;
  console.log(loginData,'sukses login')
  setAsyncStorage('token',loginData.token)
  loginData.name === null ? setAsyncStorage('name', 'pengguna') : setAsyncStorage('name',loginData.name)
  setAsyncStorage('role', loginData.role)
  setAsyncStorage('id', loginData.id.toString())

  props.navigation.navigate("Artikel",{
    id:loginData.id,
    token:loginData.token,
    name:loginData.name
  })

} catch (error) {
  console.log('error login',props.email,props.password);
  alert(error.response.data.message)
}
```

<p>};</p>

<p>============================
and here is the full code in my profile screen page, so i've tried using setTimeout to console.log(id) and run function to get user id, but still no luck</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import React, { useState, useEffect } from 'react'
import { KeyboardAvoidingView, Text, View, AsyncStorage } from 'react-native'

import ProfileForms from './ProfileForms/ProfileForms'
import axios from 'axios'
import styles from "../styles";
import {url} from '../config/variables'
import { ScrollView } from 'react-native-gesture-handler';

export default function ProfileScreen (){
  const [isLoading,setIsLoading] = useState(true)
  const [id, setId] = useState(null)
  const [name, setName] = useState(null)

  async function getAsyncStorageId(){
    const userId = await AsyncStorage.getItem('id')
    console.log('user id from AsyncStorage is: ',userId)
    await setId(userId)
    console.log('state hooks id : ',id)
  }

  async function getUserData(){
    console.log('getting userr data')
    try {
      let result = await axios.get(`${url}/users/${id}`)
      console.log(result.data)
      setName(result.data.name)
      setIsLoading(false)
    } catch (error) {
      console.log(error)
    }
  }

  function test(){
    getAsyncStorageId()
    setTimeout(() => {
      console.log(id)
      getUserData()
    }, 5000);
  }

  useEffect(()=>{
    test()
  },[])

  return(
    <ScrollView>
    <KeyboardAvoidingView behavior={Platform.OS == "ios"? "padding" : "height"} style={styles.container}>
      {
        !isLoading &&
        <ProfileForms
          id={id}
          name={name}
          setName={setName}
        />
      }
      {
        isLoading &&
        <View>
          <Text>Loading</Text>
        </View>
      }
    </KeyboardAvoidingView>
    </ScrollView>
  )
}</code>```

=============== update again =================

so i created a variable and i replace my id state with this variable and it works.. for the moment i think im gonna stick with this

```<code>let desperateId = null

async function getAsyncStorageId(){
  const userId = await AsyncStorage.getItem('id')
  console.log('user id from AsyncStorage is: ',userId)
  desperateId=userId
  await setId(userId)
  console.log('state hooks id : ',id)
}
</code>```

答:
I think you can only store the string type in AsyncStorage. Try setting the value like this.

```<code>AsyncStorage.setItem('id', '5')
</code>```

In your case, it would be like this

```<code>setAsyncStorage('id', JSON.stringify(loginData.id))
</code>```

Update:

```<code>const [id, setId] = useState('')
</code>```

Body:
Hello im currently learning AsyncStorage in react native.
so i write some state like this

const [isLoading,setIsLoading] = useState(true)
const [id, setId] = useState(null)

i set it null because i want to get the id from AsyncStorage, so i write a simple function to get and set the value  like this :

async function getAsyncStorageId(){
  const userId = await AsyncStorage.getItem('id')
  console.log('user id from AsyncStorage is: ',userId)
  setId(userId)
  console.log('state hooks id : ',id)
}

and i put it into useEffect Hooks

 useEffect(()=>{
  getAsyncStorageId()
 },[])

so i test my code the id state wont update it stay null, but the console.log(userId) have an id value.

user id from AsyncStorage is:  6
state hooks id :  null

i dont know why i cant set the state with value from the asyncstorage

=======================
*edit : this is the code that i used to set the id in AsyncStorage.
i put this code in my Login Screen, so when the user succesfully login i store the id, username, token, and role in async storage

const login = async () => {
try {
  let response = await axios.post(`${url}/users/login`, {
    email: props.email,
    password: props.password,
  });
  let loginData = response.data;
  console.log(loginData,'sukses login')
  setAsyncStorage('token',loginData.token)
  loginData.name === null ? setAsyncStorage('name', 'pengguna') : setAsyncStorage('name',loginData.name)
  setAsyncStorage('role', loginData.role)
  setAsyncStorage('id', loginData.id)

  props.navigation.navigate("Artikel",{
    id:loginData.id,
    token:loginData.token,
    name:loginData.name
  })

} catch (error) {
  console.log('error login',props.email,props.password);
  alert(error.response.data.message)
}

};

export const setAsyncStorage = async (key, value) => {
  try {
    await AsyncStorage.setItem(`${key}`, `${value}`);
  } catch (error) {
    console.log(error);
  }
};

=============== update 2=========================

so i've tried change id value in login function into string like this

const login = async () => {
try {
  let response = await axios.post(`${url}/users/login`, {
    email: props.email,
    password: props.password,
  });
  let loginData = response.data;
  console.log(loginData,'sukses login')
  setAsyncStorage('token',loginData.token)
  loginData.name === null ? setAsyncStorage('name', 'pengguna') : setAsyncStorage('name',loginData.name)
  setAsyncStorage('role', loginData.role)
  setAsyncStorage('id', loginData.id.toString())

  props.navigation.navigate("Artikel",{
    id:loginData.id,
    token:loginData.token,
    name:loginData.name
  })

} catch (error) {
  console.log('error login',props.email,props.password);
  alert(error.response.data.message)
}

};

============================
and here is the full code in my profile screen page, so i've tried using setTimeout to console.log(id) and run function to get user id, but still no luck

import React, { useState, useEffect } from 'react'
import { KeyboardAvoidingView, Text, View, AsyncStorage } from 'react-native'

import ProfileForms from './ProfileForms/ProfileForms'
import axios from 'axios'
import styles from "../styles";
import {url} from '../config/variables'
import { ScrollView } from 'react-native-gesture-handler';

export default function ProfileScreen (){
  const [isLoading,setIsLoading] = useState(true)
  const [id, setId] = useState(null)
  const [name, setName] = useState(null)

  async function getAsyncStorageId(){
    const userId = await AsyncStorage.getItem('id')
    console.log('user id from AsyncStorage is: ',userId)
    await setId(userId)
    console.log('state hooks id : ',id)
  }

  async function getUserData(){
    console.log('getting userr data')
    try {
      let result = await axios.get(`${url}/users/${id}`)
      console.log(result.data)
      setName(result.data.name)
      setIsLoading(false)
    } catch (error) {
      console.log(error)
    }
  }

  function test(){
    getAsyncStorageId()
    setTimeout(() => {
      console.log(id)
      getUserData()
    }, 5000);
  }

  useEffect(()=>{
    test()
  },[])

  return(
    <ScrollView>
    <KeyboardAvoidingView behavior={Platform.OS == "ios"? "padding" : "height"} style={styles.container}>
      {
        !isLoading &&
        <ProfileForms
          id={id}
          name={name}
          setName={setName}
        />
      }
      {
        isLoading &&
        <View>
          <Text>Loading</Text>
        </View>
      }
    </KeyboardAvoidingView>
    </ScrollView>
  )
}

=============== update again =================

so i created a variable and i replace my id state with this variable and it works.. for the moment i think im gonna stick with this

let desperateId = null

async function getAsyncStorageId(){
  const userId = await AsyncStorage.getItem('id')
  console.log('user id from AsyncStorage is: ',userId)
  desperateId=userId
  await setId(userId)
  console.log('state hooks id : ',id)
}

Body:
I think you can only store the string type in AsyncStorage. Try setting the value like this.

AsyncStorage.setItem('id', '5')

In your case, it would be like this

setAsyncStorage('id', JSON.stringify(loginData.id))

Update:

const [id, setId] = useState('')


答:
You can group the items by this key and then use the first item in each group (assuming l is your list).

```<code>import itertools
keyfunc = lambda x: x.split(";", 1)[1]
[next(g) for k, g in itertools.groupby(sorted(l, key=keyfunc), keyfunc)]
</code>```

Title: What is an easy way to remove duplicates from only part of the string in Python?

Body:
I have a list of strings that goes like this:

1;213;164
2;213;164
3;213;164
4;213;164
5;213;164
6;213;164
7;213;164
8;213;164
9;145;112
10;145;112
11;145;112
12;145;112
13;145;112
14;145;112
15;145;112
16;145;112
17;145;112
1001;1;151
1002;2;81
1003;3;171
1004;4;31

I would like to remove all duplicates where second 2 numbers are the same. So after running it through program I would get something like this:

1;213;164
9;145;112
1001;1;151
1002;2;81
1003;3;171
1004;4;31

But something like

8;213;164
15;145;112
1001;1;151
1002;2;81
1003;3;171
1004;4;31

would also be correct.

Body:
You can group the items by this key and then use the first item in each group (assuming l is your list).

import itertools
keyfunc = lambda x: x.split(";", 1)[1]
[next(g) for k, g in itertools.groupby(sorted(l, key=keyfunc), keyfunc)]


答:
Here is a code on the few first items, just switch my list with yours:

```<code>x = [
'7;213;164',
'8;213;164',
'9;145;112',
'10;145;112',
'11;145;112',
]
new_list = []
for i in x:
    check = True
    s_part = i[i.find(';'):]
    for j in new_list:
        if s_part in j:
            check = False
    if check == True:
        new_list.append(i)

print(new_list)
</code>```

Output:

```<code>['7;213;164', '9;145;112']
</code>```

Body:
Here is a code on the few first items, just switch my list with yours:

x = [
'7;213;164',
'8;213;164',
'9;145;112',
'10;145;112',
'11;145;112',
]
new_list = []
for i in x:
    check = True
    s_part = i[i.find(';'):]
    for j in new_list:
        if s_part in j:
            check = False
    if check == True:
        new_list.append(i)

print(new_list)

Output:

['7;213;164', '9;145;112']


问:
remove duplicates in python
I'm looking to remove the names that are repeated.

My code is connected to retrieve information from SQL server to Python.

```<code>def get_all_artist():
    query="SELECT artist_name FROM Sheet1"
    all_artist = execute_read_query (conn, query)
    for artist_record in all_artist:
        print(str(artist_record[0]))
    return (all_artist)
</code>```

The artist_name that I am retrieving on SQL are:

```<code>BTS
BTS
BTS
TWICE
TWICE
TWICE
TWICE
TWICE
HEIZE
HEIZE
KHALID
KHALID
KHALID
ERIC CHOU
ERIC CHOU
ERIC CHOU
SAM SMITH
SAM SMITH
SAM SMITH
AGUST D
</code>```

However, I'd only like to remove the duplicates on Python without removing any rows in my SQL table:

```<code>BTS
TWICE
HEIZE
KHALID
ERIC CHOU
SAM SMITH
AGUST D
</code>```

答:
Use distinct:

```<code>select distinct artist_name from sheet1
</code>```

Title: remove duplicates in python

Body:
I'm looking to remove the names that are repeated.

My code is connected to retrieve information from SQL server to Python.

def get_all_artist():
    query="SELECT artist_name FROM Sheet1"
    all_artist = execute_read_query (conn, query)
    for artist_record in all_artist:
        print(str(artist_record[0]))
    return (all_artist)

The artist_name that I am retrieving on SQL are:

BTS
BTS
BTS
TWICE
TWICE
TWICE
TWICE
TWICE
HEIZE
HEIZE
KHALID
KHALID
KHALID
ERIC CHOU
ERIC CHOU
ERIC CHOU
SAM SMITH
SAM SMITH
SAM SMITH
AGUST D

However, I'd only like to remove the duplicates on Python without removing any rows in my SQL table:

BTS
TWICE
HEIZE
KHALID
ERIC CHOU
SAM SMITH
AGUST D

Body:
Use distinct:

select distinct artist_name from sheet1


问:
How does grpc-web security work in production?
I'm using envoy proxy between Go server with gRPC and my Flutter web app. I can use TLS between envoy and Go server, that's fine, but my concern is between envoy and my web app. How can I protect this connection? What is the best way? </p>

答: There is no perfect solution currently. Only thing you can hope for is browsers to support GRPC. Current situation demands that you host proxy and web app on same server so that there is no external access. If proxy and web app are on different servers it depends on security of proxy provider.


问:
Scipy ODR results with huge relative errors for sd_beta

When running the ODR algorithm on some experiment data, I've been asked to run it with the following model:

It is clear that this fitting function is containing a redundant degree of freedom.

When I run the fitting on my experiment data I get enormous relative errors of beta, starting from 8000% relative error.

When I try to run the fitting again but with a fitting function that doesn't have a redundant degree of freedom, such as:

I don't get this kind of problem.

Why is this happening? Why the ODR algorithm is so sensitive for redundant degrees of freedom? I wasn't able to answer these questions to my supervisors. An answer will be much appreciated.

Reproducing code example:

from scipy.odr import RealData, Model, ODR

def func1(a, x):
    return a[0] * (x + a[1]) / (a[3] * (x + a[1]) + a[1] * x) + a[2]

def func2(a, x):
    return a[0] / (x + a[1]) + a[2]

# fmt: off
zx = [
    1911.125, 2216.95, 2707.71, 3010.225, 3410.612, 3906.015, 4575.105, 5517.548,
    6918.481,
]
dx = [
    0.291112577, 0.321695254, 0.370771197, 0.401026507, 0.441068641, 0.490601621,
    0.557573268, 0.651755155, 0.79184836,
]
zy = [
    0.000998056, 0.000905647, 0.000800098, 0.000751041, 0.000699982, 0.000650532,
    0.000600444, 0.000550005, 0.000500201,
]
dy = [
    5.49029e-07, 5.02824e-07, 4.5005e-07, 4.25532e-07, 3.99991e-07, 3.75266e-07,
    3.50222e-07, 3.25003e-07, 3.00101e-07,
]
# fmt: on

data = RealData(x=zx, y=zy, sx=dx, sy=dy)

print("Func 1")
print("======")
beta01 = [
    1.46,
    4775.4,
    0.01,
    1000,
]
model1 = Model(func1)
odr1 = ODR(data, model1, beta0=beta01)
result1 = odr1.run()
print("beta", result1.beta)
print("sd beta", result1.sd_beta)
print("relative", result1.sd_beta / result1.beta * 100)

print()
print()

print("Func 2")
print("======")
beta02 = [
    1,
    1,
    1,
]
model2 = Model(func2)
odr2 = ODR(data, model2, beta0=beta02)
result2 = odr2.run()
print("beta", result2.beta)
print("sd beta", result2.sd_beta)
print("relative", result2.sd_beta / result2.beta * 100)
```

<p>This prints out:</p>

```Func 1
======
beta [ 1.30884537e+00 -2.82585952e+03  7.79755196e-04  9.47943376e+01]
sd beta [1.16144608e+02 3.73765816e+06 6.12613738e-01 4.20775596e+03]
relative [   8873.82193523 -132266.24068473   78564.88054498    4438.82627453]

Func 2
======
beta [1.40128121e+00 9.80844274e+01 3.00511669e-04]
sd beta [2.73990552e-03 3.22344713e+00 3.74538794e-07]
relative [0.1955286  3.28640051 0.12463369]
```

Scipy/Numpy/Python version information:

Versions are:

Scipy - 1.4.1

Numpy - 1.18.2

Python - 3.7.2

答:
The problem is not with the degrees of freedom.

The degrees of freedom is the difference between the number of data points and the number of fitting parameters.
The problem has the same number of degrees of freedom for the two formulae, as they have the same number of parameters.
It also looks like that you do not have free degrees of freedom, which is good news, it means that it can potentially be fitted.

However, you are right that first expression has some problem: the parameters you are trying to fit are not independent.

This is probably better understood with some simpler example.

Consider the following expression:

```<code>y = x + b + c
</code>```

which you try to fit, given n data for x and y with n >> 2.

The question is: what are the optimal value for b and c? This cannot be answered. All you can say from x and y data is about the combination. Therefore, if b + c is 0, the fit cannot tell us if b = 1000, c = -1000 or b = 1, c= -1, but at least we can say that given b we can determine c.
What is the error on a given b? Potentially infinite. That is the reason for the fitting to give you that large relative error.

Body:
When running the ODR algorithm on some experiment data, I've been asked to run it with the following model:

It is clear that this fitting function is containing a redundant degree of freedom.

When I run the fitting on my experiment data I get enormous relative errors of beta, starting from 8000% relative error.

When I try to run the fitting again but with a fitting function that doesn't have a redundant degree of freedom, such as:

I don't get this kind of problem.

Why is this happening? Why the ODR algorithm is so sensitive for redundant degrees of freedom? I wasn't able to answer these questions to my supervisors. An answer will be much appreciated.

Reproducing code example:

from scipy.odr import RealData, Model, ODR

def func1(a, x):
    return a[0] * (x + a[1]) / (a[3] * (x + a[1]) + a[1] * x) + a[2]

def func2(a, x):
    return a[0] / (x + a[1]) + a[2]

# fmt: off
zx = [
    1911.125, 2216.95, 2707.71, 3010.225, 3410.612, 3906.015, 4575.105, 5517.548,
    6918.481,
]
dx = [
    0.291112577, 0.321695254, 0.370771197, 0.401026507, 0.441068641, 0.490601621,
    0.557573268, 0.651755155, 0.79184836,
]
zy = [
    0.000998056, 0.000905647, 0.000800098, 0.000751041, 0.000699982, 0.000650532,
    0.000600444, 0.000550005, 0.000500201,
]
dy = [
    5.49029e-07, 5.02824e-07, 4.5005e-07, 4.25532e-07, 3.99991e-07, 3.75266e-07,
    3.50222e-07, 3.25003e-07, 3.00101e-07,
]
# fmt: on

data = RealData(x=zx, y=zy, sx=dx, sy=dy)

print("Func 1")
print("======")
beta01 = [
    1.46,
    4775.4,
    0.01,
    1000,
]
model1 = Model(func1)
odr1 = ODR(data, model1, beta0=beta01)
result1 = odr1.run()
print("beta", result1.beta)
print("sd beta", result1.sd_beta)
print("relative", result1.sd_beta / result1.beta * 100)

print()
print()

print("Func 2")
print("======")
beta02 = [
    1,
    1,
    1,
]
model2 = Model(func2)
odr2 = ODR(data, model2, beta0=beta02)
result2 = odr2.run()
print("beta", result2.beta)
print("sd beta", result2.sd_beta)
print("relative", result2.sd_beta / result2.beta * 100)

This prints out:

Func 1
======
beta [ 1.30884537e+00 -2.82585952e+03  7.79755196e-04  9.47943376e+01]
sd beta [1.16144608e+02 3.73765816e+06 6.12613738e-01 4.20775596e+03]
relative [   8873.82193523 -132266.24068473   78564.88054498    4438.82627453]

Func 2
======
beta [1.40128121e+00 9.80844274e+01 3.00511669e-04]
sd beta [2.73990552e-03 3.22344713e+00 3.74538794e-07]
relative [0.1955286  3.28640051 0.12463369]

Scipy/Numpy/Python version information:

Versions are:

Scipy - 1.4.1

Numpy - 1.18.2

Python - 3.7.2

Body:
The problem is not with the degrees of freedom.

The degrees of freedom is the difference between the number of data points and the number of fitting parameters.
The problem has the same number of degrees of freedom for the two formulae, as they have the same number of parameters.
It also looks like that you do not have free degrees of freedom, which is good news, it means that it can potentially be fitted.

However, you are right that first expression has some problem: the parameters you are trying to fit are not independent.

This is probably better understood with some simpler example.

Consider the following expression:

y = x + b + c

which you try to fit, given n data for x and y with n >> 2.

The question is: what are the optimal value for b and c? This cannot be answered. All you can say from x and y data is about the combination. Therefore, if b + c is 0, the fit cannot tell us if b = 1000, c = -1000 or b = 1, c= -1, but at least we can say that given b we can determine c.
What is the error on a given b? Potentially infinite. That is the reason for the fitting to give you that large relative error.


问:
openpyxl IF Formula and iterating over multiple rows until you reach an empty row
This is a 3 part question:
1. When entering the following using openpyxl I get this Alert ("We found a problem with some content in 'Risks Chartio Import Py Test.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.")

```<code>sheet ['N2'] = '="IF(AND(M2>0,M2<=1),"01-VERY LOW",IF(AND(M2>1,M2<=4),"02-LOW", IF(AND(M2>4,M2<=9),"03-MEDIUM",IF(AND(M2>9,M2<=16),"04-HIGH",IF(AND(M2>16,M2<=25),"05-CRITICAL")))))"'
</code>```

How can I fix the code above so that the formula works in my xlsx file

How do I Identify the last row in the file with data and then iterate the formula above until I reach that row?

Thanks!

答:
You have a redundant set of quotation marks ("...") in your formula, just remove them:

sheet ['N2'] = '=IF(AND(M2>0,M2<=1),"01-VERY LOW",IF(AND(M2>1,M2<=4),"02-LOW", IF(AND(M2>4,M2<=9),"03-MEDIUM",IF(AND(M2>9,M2<=16),"04-HIGH",IF(AND(M2>16,M2<=25),"05-CRITICAL")))))'

to get the last row of a file with openpyxl just use worksheet.max_row which will give you the last row used in that file (note that row that had data that was deleted are not considered "empty" as they have an empty string in them.

To iterate over a worksheet columns and rows see this answer.

Body:
This is a 3 part question:
1. When entering the following using openpyxl I get this Alert ("We found a problem with some content in 'Risks Chartio Import Py Test.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.")

sheet ['N2'] = '="IF(AND(M2>0,M2<=1),"01-VERY LOW",IF(AND(M2>1,M2<=4),"02-LOW", IF(AND(M2>4,M2<=9),"03-MEDIUM",IF(AND(M2>9,M2<=16),"04-HIGH",IF(AND(M2>16,M2<=25),"05-CRITICAL")))))"'

How can I fix the code above so that the formula works in my xlsx file

How do I Identify the last row in the file with data and then iterate the formula above until I reach that row?

Thanks!


问:
How to add random op in tensorflow dataset api?
I want to generate random data in a py_func op, but when I run this code, I get different random data which is expected as the same in this code.

I think the problem come with the tf.data.Dataset.map api. When I get the values of d5, it will run random function twice which d3 and d4 will get different values in this case.

Thanks.

import tensorflow as tf
import numpy as np

def random(x):
    def random_(x):
        x = np.float32(np.random.rand())
        print("run random_")
        return x,x
    return tf.compat.v1.py_func(
        random_,
        [x],
        [tf.float32, tf.float32],
        name="generate_random")

d1 = tf.data.Dataset.from_tensor_slices(tf.zeros(10))
d2 = d1.map(random)

d3 = d2.map(lambda x1,x2: x1)
d4 = d2.map(lambda x1,x2: x2)

d5 = tf.data.Dataset.zip( (d3,d4) )

it = d5.make_one_shot_iterator()
fetch = it.get_next()
with tf.Session() as sess:
    while True:
        X = sess.run(fetch)
        print(X)
```

答:
As per the documentation -

Maps map_func across the elements of this dataset.

This transformation applies map_func to each element of this dataset,
  and returns a new dataset containing the transformed elements, in the
  same order as they appeared in the input. map_func can be used to
  change both the values and the structure of a dataset's elements. For
  example, adding 1 to each element, or projecting a subset of element
  components.

I think it’s best to see the map function as part of the pipeline. Every time you run map, nothing happens with the data yet. Instead, a chain of operations is made in the background. Note that these transformations are executed lazy. Only when you actually request data from the dataset (like with a for loop and batch), the source data from your dataset are fed through the pipeline. At that time, each map is applied on the image or on the batch.

As an alternative, you can fulfill your requirement as below -

Code -

```<code>%tensorflow_version 1.x
import tensorflow as tf
import numpy as np

def random(x):
  x = np.float32(np.random.rand())
  print("run random_")
  return x

a = []
for i in range(10):
  a.append(random(i))

d1 = tf.data.Dataset.from_tensor_slices(a)

d5 = tf.data.Dataset.zip( (d1,d1) )

it = d5.make_one_shot_iterator()
fetch = it.get_next()
with tf.Session() as sess:
    while True:
        X = sess.run(fetch)
        print(X)
</code>```

Output -

```<code>run random_
run random_
run random_
run random_
run random_
run random_
run random_
run random_
run random_
run random_
WARNING:tensorflow:From <ipython-input-2-ee4ae8ca7ce4>:18: DatasetV1.make_one_shot_iterator (from tensorflow.python.data.ops.dataset_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `for ... in dataset:` to iterate over a dataset. If using `tf.estimator`, return the `Dataset` object directly from your input function. As a last resort, you can use `tf.compat.v1.data.make_one_shot_iterator(dataset)`.
(0.6963448, 0.6963448)
(0.92889917, 0.92889917)
(0.054273304, 0.054273304)
(0.3719434, 0.3719434)
(0.33791015, 0.33791015)
(0.873847, 0.873847)
(0.66726416, 0.66726416)
(0.77356577, 0.77356577)
(0.4188753, 0.4188753)
(0.8886825, 0.8886825)
</code>```

Hope this answers your question. Happy Learning.

Body:
As per the documentation -

Maps map_func across the elements of this dataset.

This transformation applies map_func to each element of this dataset,
  and returns a new dataset containing the transformed elements, in the
  same order as they appeared in the input. map_func can be used to
  change both the values and the structure of a dataset's elements. For
  example, adding 1 to each element, or projecting a subset of element
  components.

I think it’s best to see the map function as part of the pipeline. Every time you run map, nothing happens with the data yet. Instead, a chain of operations is made in the background. Note that these transformations are executed lazy. Only when you actually request data from the dataset (like with a for loop and batch), the source data from your dataset are fed through the pipeline. At that time, each map is applied on the image or on the batch.

As an alternative, you can fulfill your requirement as below -

Code -

%tensorflow_version 1.x
import tensorflow as tf
import numpy as np

def random(x):
  x = np.float32(np.random.rand())
  print("run random_")
  return x

a = []
for i in range(10):
  a.append(random(i))

d1 = tf.data.Dataset.from_tensor_slices(a)

d5 = tf.data.Dataset.zip( (d1,d1) )

it = d5.make_one_shot_iterator()
fetch = it.get_next()
with tf.Session() as sess:
    while True:
        X = sess.run(fetch)
        print(X)

Output -

run random_
run random_
run random_
run random_
run random_
run random_
run random_
run random_
run random_
run random_
WARNING:tensorflow:From <ipython-input-2-ee4ae8ca7ce4>:18: DatasetV1.make_one_shot_iterator (from tensorflow.python.data.ops.dataset_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `for ... in dataset:` to iterate over a dataset. If using `tf.estimator`, return the `Dataset` object directly from your input function. As a last resort, you can use `tf.compat.v1.data.make_one_shot_iterator(dataset)`.
(0.6963448, 0.6963448)
(0.92889917, 0.92889917)
(0.054273304, 0.054273304)
(0.3719434, 0.3719434)
(0.33791015, 0.33791015)
(0.873847, 0.873847)
(0.66726416, 0.66726416)
(0.77356577, 0.77356577)
(0.4188753, 0.4188753)
(0.8886825, 0.8886825)

Hope this answers your question. Happy Learning.


问:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to pojo.class
Getting java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to pojo.class while serializing Generic type.Kindly assist.

This is the code written for Json fileReader class.

```<code>public class ReadJsonFile<T>  {

    private static final Object ReadJsonFile = null;
    public static void main (String[] args)
    {
        ReadJsonFile read  = new ReadJsonFile();
        read.getjsondata("src/test/resource/testdataresource/addplacerequest.json", Addbook.class);
    }
    public   List<T> getjsondata(String filepath, Class<T> typeofT)
    {

         //filepath= "src/test/resource/testdataresource/addplacerequest.json";
        Gson gson = new Gson(); ;
        BufferedReader bufferReader = null;
try {

            bufferReader = new BufferedReader(new FileReader(filepath));

         */
            Type ListType = new TypeToken<ArrayList<T>>(){}.getType();
            //gson.toJson(ReadJsonFile,ListType);
             List<T> arraylist = gson.fromJson(bufferReader, ListType);
            Iterator iter = arraylist.iterator();
              while (iter.hasNext()) {
               System.out.println(iter.next());
              }
            return(arraylist);

    }catch(FileNotFoundException e) {
    throw new RuntimeException("Json file not found at path : " + filepath);
}finally {
    try { if(bufferReader != null) bufferReader.close();}
    catch (IOException ignore) {}
}
    }

}
</code>```

POJO class that I have used is:

```<code>public class Addbook {

    public String name;
    public String isbn;
    public String aisle;
    public String author;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getIsbn() {
        return isbn;
    }
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    public String getAisle() {
        return aisle;
    }
    public void setAisle(String aisle) {
        this.aisle = aisle;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Addbook [name="+ name + ",isbn="+ isbn +",aisle="+ aisle +",authur="+ author +"]";
    }

 }
</code>```

File and Pojo reader class

```<code>public class TestDataBuild {

    private static String isbn;

    public static List<Addbook> addbook()

    {
            ReadJsonFile readJson=new ReadJsonFile();
    List<Addbook> addbook = readJson.getjsondata("src/test/resource/testdataresource/addplacerequest.json", Addbook.class);
    //System.out.println(addbook.getClass().getName()); // variable class name
    addbook.get(0).setName("name");
    addbook.get(1).setAuthor("author");//listOfClients.get(clientIndex).setFirstName(newFirstName);
    addbook.get(2).setIsbn(isbn);
    addbook.get(3).setAisle("aisle");

    return addbook;

        }

    }
</code>```

Json file used:

```<code>[
{
        "name": "The GoodDay",
        "isbn": 67086,
        "aisle": "GoodDay",
        "author": "fghwsdf"
},
{
        "name": "The BadDay",
        "isbn": 56897,
        "aisle": "BadDay",
        "author": "dhdjfjj"
}
]
</code>```

How should I resolve this error?

答:
Instead of

```<code>  Type ListType = new TypeToken<ArrayList<T>>(){}.getType();
</code>```

Use

```<code>  Type ListType =TypeToken.getParameterized(ArrayList.class, typeofT).getType();
</code>```

Support since Gson 2.8.0

This question has been asked and answered
Gson TypeToken with dynamic ArrayList item type

Body:
Getting java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to pojo.class while serializing Generic type.Kindly assist.

This is the code written for Json fileReader class.

public class ReadJsonFile<T>  {

    private static final Object ReadJsonFile = null;
    public static void main (String[] args)
    {
        ReadJsonFile read  = new ReadJsonFile();
        read.getjsondata("src/test/resource/testdataresource/addplacerequest.json", Addbook.class);
    }
    public   List<T> getjsondata(String filepath, Class<T> typeofT)
    {

         //filepath= "src/test/resource/testdataresource/addplacerequest.json";
        Gson gson = new Gson(); ;
        BufferedReader bufferReader = null;
try {

            bufferReader = new BufferedReader(new FileReader(filepath));

         */
            Type ListType = new TypeToken<ArrayList<T>>(){}.getType();
            //gson.toJson(ReadJsonFile,ListType);
             List<T> arraylist = gson.fromJson(bufferReader, ListType);
            Iterator iter = arraylist.iterator();
              while (iter.hasNext()) {
               System.out.println(iter.next());
              }
            return(arraylist);

    }catch(FileNotFoundException e) {
    throw new RuntimeException("Json file not found at path : " + filepath);
}finally {
    try { if(bufferReader != null) bufferReader.close();}
    catch (IOException ignore) {}
}
    }

}

POJO class that I have used is:

public class Addbook {

    public String name;
    public String isbn;
    public String aisle;
    public String author;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getIsbn() {
        return isbn;
    }
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    public String getAisle() {
        return aisle;
    }
    public void setAisle(String aisle) {
        this.aisle = aisle;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Addbook [name="+ name + ",isbn="+ isbn +",aisle="+ aisle +",authur="+ author +"]";
    }

 }

File and Pojo reader class

public class TestDataBuild {

    private static String isbn;

    public static List<Addbook> addbook()

    {
            ReadJsonFile readJson=new ReadJsonFile();
    List<Addbook> addbook = readJson.getjsondata("src/test/resource/testdataresource/addplacerequest.json", Addbook.class);
    //System.out.println(addbook.getClass().getName()); // variable class name
    addbook.get(0).setName("name");
    addbook.get(1).setAuthor("author");//listOfClients.get(clientIndex).setFirstName(newFirstName);
    addbook.get(2).setIsbn(isbn);
    addbook.get(3).setAisle("aisle");

    return addbook;

        }

    }

Json file used:

[
{
        "name": "The GoodDay",
        "isbn": 67086,
        "aisle": "GoodDay",
        "author": "fghwsdf"
},
{
        "name": "The BadDay",
        "isbn": 56897,
        "aisle": "BadDay",
        "author": "dhdjfjj"
}
]

How should I resolve this error?

Body:
Instead of

  Type ListType = new TypeToken<ArrayList<T>>(){}.getType();

Use

  Type ListType =TypeToken.getParameterized(ArrayList.class, typeofT).getType();

Support since Gson 2.8.0

This question has been asked and answered
Gson TypeToken with dynamic ArrayList item type


问:
How to resize an image in sharp with the option 'contain' but preserve the aspect ratio of the original dimensions?
I have a 1000px by 750px image.

I use lovell/sharp to resize it:

```<code>await sharp(image)
    .resize({
        fit: sharp.fit.contain,
        width: 800,
        height: 800
    })
    .jpeg({ quality: 80 })
    .toBuffer()
</code>```

This results in a new image that is 800px by 800px, with the original image 'contained' inside of that region.

What I would really like is to have a final image that is 800px by 600px.  IOW, to resize the image and preserve the aspect ratio.

I realize it is possible to do this by specifying only a width.  However it is useful to have a bounding box to contain the resized image in, to avoid creating images greater than a certain height.

Can I do this in sharp with different settings?

答:
Keep either width or height so that the Sharp will maintain the ratio

Below the height will maintain its ratio when resizing;

```<code>await sharp(image)
    .resize({
        fit: sharp.fit.contain,
        width: 800
    })
    .jpeg({ quality: 80 })
    .toBuffer()
</code>```

Body:
I have a 1000px by 750px image.

I use lovell/sharp to resize it:

await sharp(image)
    .resize({
        fit: sharp.fit.contain,
        width: 800,
        height: 800
    })
    .jpeg({ quality: 80 })
    .toBuffer()

This results in a new image that is 800px by 800px, with the original image 'contained' inside of that region.

What I would really like is to have a final image that is 800px by 600px.  IOW, to resize the image and preserve the aspect ratio.

I realize it is possible to do this by specifying only a width.  However it is useful to have a bounding box to contain the resized image in, to avoid creating images greater than a certain height.

Can I do this in sharp with different settings?

Body:
Keep either width or height so that the Sharp will maintain the ratio

Below the height will maintain its ratio when resizing;

await sharp(image)
    .resize({
        fit: sharp.fit.contain,
        width: 800
    })
    .jpeg({ quality: 80 })
    .toBuffer()