问:
playwright 'no tests found.' on simple copy of example.spec.ts
I have just installed playwright (v1.18.1) to try it out (Windows 11) and I feel like something is wrong. I can run the example.spec.ts script fine, but if I copy that file and then try to run the copy then I get a no tests found. error.

The steps seem very basic...

First test run the C:\playwright\test\tests\example.spec.ts script....

```<code>C:\playwright\test\tests>npx playwright test example.spec.ts

Running 25 tests using 1 worker

  -  example.spec.ts:14:3 › New Todo › should allow me to add todo items
Terminate batch job (Y/N)?

  25 skipped
</code>```

[that worked so] then create a copy to start playing...

```<code>C:\playwright\test\tests>copy example.spec.ts test4.ts
        1 file(s) copied.
</code>```

but before editing test4.ts I check it will run...

```<code>C:\playwright\test\tests>npx playwright test test4.ts

=================
 no tests found.
=================
npm ERR! code 1
npm ERR! path C:\playwright\test\tests
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c playwright test test4.ts

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\xxxxx\AppData\Local\npm-cache\_logs\2022-02-09T16_29_19_723Z-debug.log
</code>```

If it helps the log reads:

```<code>C:\playwright\test\tests>type C:\Users\xxxxx\AppData\Local\npm-cache\_logs\2022-02-09T16_37_46_149Z-debug.log
0 verbose cli [
0 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
0 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
0 verbose cli   'exec',
0 verbose cli   '--',
0 verbose cli   'playwright',
0 verbose cli   '-version'
0 verbose cli ]
1 info using npm@7.0.15
2 info using node@v15.4.0
3 timing config:load:defaults Completed in 1ms
4 timing config:load:file:C:\Program Files\nodejs\node_modules\npm\npmrc Completed in 1ms
5 timing config:load:builtin Completed in 2ms
6 timing config:load:cli Completed in 1ms
7 timing config:load:env Completed in 0ms
8 timing config:load:file:C:\playwright\test\.npmrc Completed in 0ms
9 timing config:load:project Completed in 1ms
10 timing config:load:file:C:\Users\xxxxx\.npmrc Completed in 0ms
11 timing config:load:user Completed in 0ms
12 timing config:load:file:C:\Users\xxxxx\AppData\Roaming\npm\etc\npmrc Completed in 0ms
13 timing config:load:global Completed in 0ms
14 timing config:load:cafile Completed in 0ms
15 timing config:load:validate Completed in 1ms
16 timing config:load:setUserAgent Completed in 0ms
17 timing config:load:setEnvs Completed in 1ms
18 timing config:load Completed in 7ms
19 verbose npm-session c0bee43e8701d230
20 timing npm:load Completed in 16ms
21 timing command:exec Completed in 633ms
22 verbose stack Error: command failed
22 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\promise-spawn\index.js:64:27)
22 verbose stack     at ChildProcess.emit (node:events:376:20)
22 verbose stack     at maybeClose (node:internal/child_process:1063:16)
22 verbose stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:295:5)
23 verbose pkgid test@1.0.0
24 verbose cwd C:\playwright\test\tests
25 verbose Windows_NT 10.0.22000
26 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "exec" "--" "playwright" "-version"
27 verbose node v15.4.0
28 verbose npm  v7.0.15
29 error code 1
30 error path C:\playwright\test\tests
31 error command failed
32 error command C:\WINDOWS\system32\cmd.exe /d /s /c playwright -version
33 verbose exit 1
</code>```

Why is it giving me an error when it is just a copy of an original that does work?

答:
You can set up your own test match regex in the playwright test config.

By default, Playwright Test looks for files matching .*(test|spec)\.(js|ts|mjs), but you can run any js file by doing this:

```<code>import { PlaywrightTestConfig, devices } from '@playwright/test';

const config: PlaywrightTestConfig = {
  testMatch: /.*.js/,
};
export default config;
</code>```

Keep in mind that it would try to load tests from any helper file you have in your folder. I think that following the test or spec convention is a good thing.

Body:
I have just installed playwright (v1.18.1) to try it out (Windows 11) and I feel like something is wrong. I can run the example.spec.ts script fine, but if I copy that file and then try to run the copy then I get a no tests found. error.

The steps seem very basic...

First test run the C:\playwright\test\tests\example.spec.ts script....

C:\playwright\test\tests>npx playwright test example.spec.ts

Running 25 tests using 1 worker

  -  example.spec.ts:14:3 › New Todo › should allow me to add todo items
Terminate batch job (Y/N)?

  25 skipped

[that worked so] then create a copy to start playing...

C:\playwright\test\tests>copy example.spec.ts test4.ts
        1 file(s) copied.

but before editing test4.ts I check it will run...

C:\playwright\test\tests>npx playwright test test4.ts

=================
 no tests found.
=================
npm ERR! code 1
npm ERR! path C:\playwright\test\tests
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c playwright test test4.ts

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\xxxxx\AppData\Local\npm-cache\_logs\2022-02-09T16_29_19_723Z-debug.log

If it helps the log reads:

C:\playwright\test\tests>type C:\Users\xxxxx\AppData\Local\npm-cache\_logs\2022-02-09T16_37_46_149Z-debug.log
0 verbose cli [
0 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
0 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
0 verbose cli   'exec',
0 verbose cli   '--',
0 verbose cli   'playwright',
0 verbose cli   '-version'
0 verbose cli ]
1 info using npm@7.0.15
2 info using node@v15.4.0
3 timing config:load:defaults Completed in 1ms
4 timing config:load:file:C:\Program Files\nodejs\node_modules\npm\npmrc Completed in 1ms
5 timing config:load:builtin Completed in 2ms
6 timing config:load:cli Completed in 1ms
7 timing config:load:env Completed in 0ms
8 timing config:load:file:C:\playwright\test\.npmrc Completed in 0ms
9 timing config:load:project Completed in 1ms
10 timing config:load:file:C:\Users\xxxxx\.npmrc Completed in 0ms
11 timing config:load:user Completed in 0ms
12 timing config:load:file:C:\Users\xxxxx\AppData\Roaming\npm\etc\npmrc Completed in 0ms
13 timing config:load:global Completed in 0ms
14 timing config:load:cafile Completed in 0ms
15 timing config:load:validate Completed in 1ms
16 timing config:load:setUserAgent Completed in 0ms
17 timing config:load:setEnvs Completed in 1ms
18 timing config:load Completed in 7ms
19 verbose npm-session c0bee43e8701d230
20 timing npm:load Completed in 16ms
21 timing command:exec Completed in 633ms
22 verbose stack Error: command failed
22 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\promise-spawn\index.js:64:27)
22 verbose stack     at ChildProcess.emit (node:events:376:20)
22 verbose stack     at maybeClose (node:internal/child_process:1063:16)
22 verbose stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:295:5)
23 verbose pkgid test@1.0.0
24 verbose cwd C:\playwright\test\tests
25 verbose Windows_NT 10.0.22000
26 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "exec" "--" "playwright" "-version"
27 verbose node v15.4.0
28 verbose npm  v7.0.15
29 error code 1
30 error path C:\playwright\test\tests
31 error command failed
32 error command C:\WINDOWS\system32\cmd.exe /d /s /c playwright -version
33 verbose exit 1

Why is it giving me an error when it is just a copy of an original that does work?

Body:
You can set up your own test match regex in the playwright test config.

By default, Playwright Test looks for files matching .*(test|spec)\.(js|ts|mjs), but you can run any js file by doing this:

import { PlaywrightTestConfig, devices } from '@playwright/test';

const config: PlaywrightTestConfig = {
  testMatch: /.*.js/,
};
export default config;

Keep in mind that it would try to load tests from any helper file you have in your folder. I think that following the test or spec convention is a good thing.


来源: stackexchange

问:
Testing state of clicked radio button in Cypress
I'm using cypress test runner and its selector playground.
When I click radio button the value changes to false. Via selector playground I can't pick the right selector. I get the error shown in the picture.

      <input _ngcontent-qla-c109="" type="radio" class="native-input visually-hidden" name="redraw" value="false">

      No

```
<p><img src="https://i.stack.imgur.com/el16v.png" alt="ErrorPic" /></p>
<p>Many thanks in advance for any hints,
Robert</p>
<p>I've also tried</p>
<pre class="lang-js prettyprint-override"><code>cy.get(':nth-child(8) > :nth-child(1) > :nth-child(1) > .col-9 > .radio-toolbar > :nth-child(2) > label > .native-input visually-hidden')
  .should('have.value','false')
</code>```

答:
You can use .contains as well with Text. Since in your screenshot I can see multiple NO, you can get the first one by using eq(0).

cy.contains('No').eq(0).should('have.value', 'false')
```

ContentLicense: CC BY-SA 4.0

Body:
I'm using cypress test runner and its selector playground.
When I click radio button the value changes to false. Via selector playground I can't pick the right selector. I get the error shown in the picture.

      <input _ngcontent-qla-c109="" type="radio" class="native-input visually-hidden" name="redraw" value="false">

      No

Many thanks in advance for any hints,
Robert

I've also tried

cy.get(':nth-child(8) > :nth-child(1) > :nth-child(1) > .col-9 > .radio-toolbar > :nth-child(2) > label > .native-input visually-hidden')
  .should('have.value','false')


问:
Example for addLiquidity method of UniswapV2 Router
I am reading through UniswapV2 docs and can't understand the inputs of addLiquidity method properly.
As listed in the docs:

amountAMin (uint):  Bounds the extent to which the B/A price can go up before the transaction reverts. Must be <= amountADesired.

amountBMin (uint):  Bounds the extent to which the A/B price can go up before the transaction reverts. Must be <= amountBDesired.

What does it mean? Can you please give an example? Let's say, I set amountADesired and amountBDesired to 4 and amountAMin and amountBMin to 1. What will happen?

答:
blockchain transactions are not immediate, but must queue before being mined on the blockchain and be effective

When you add liquidity given amountADesired you have to give it amountBDesired in proportion to the existing pair (example pair: 2:1 you have to put 2 tokens A and 1 token B)

once you send the transaction, before it is mined it may happen that others make operations on that liquidity pool, changing the proportion accordingly

by entering amountAmin and amountBmin you are practically telling him: "as long as the proportion is between amountADesired:amountBDesired and amountAMin:amountBmin accepts my liquidity addition, if instead the proportion exceeds my range, cancel my transaction"


问:
Does any monitoring metrics/events exist for ClickHouse keeper?
I am considering using ClickHouse keeper to replace zookeeper for data replication. And zookeeper has lots of useful metrics for monitoring/convenient triage. I checked ClickHouse documents and CurrentMetrics/ProfileEvents files but found no similar monitoring data to zk(https://zookeeper.apache.org/doc/r3.7.0/zookeeperMonitor.html).
Pls. direct me to the right way, thanks!</p>

答: They are not implemented yet. There are plans to expose keeper metrics through Prometheus endpoint.</p>


问:
Displaying audio and video content on android
For a project in work, we are getting a multimedia company to make 7 x 3 minutes film = around 21 minutes of video. ( with H.264/1280x720/1000kbps = about 200 Mb) which will then be stored on a MicroSD on the Samsung Galaxy S. These video files will be called by an app that I am developing.
They will also record all the text in audio (voice-over) as a separate file = about 60 minutes audio (with mp3 size about 60 Mb)
Total media around 260 Mb. They will be working on a Apple computer.

I know very little about multimedia - even though I apparantly have a masters in it - and was wondering if someone could help me answer some of these questions?

What would be the max suitable size for each of the files if stored on a 4GB Micro SD?

What is the minimum quality for display on a Samsung Galaxy S?

What is the best file format for display on the device?

Thanks

答:
There's no most suitable file size. It depends on the quality of the video and if you'll only need 21 minutes of video, you'll have plenty of storage space.

There's no point in doing 720p video on a display that doesn't show more than WVGA resolution. You could easily change the video resolution to WVGA and keep the bitrate. It should look just great.

I'd probably go with H.264 for the Galaxy S2.

Good luck!

ContentLicense: CC BY-SA 3.0


问:
Can you set public / private read access for azure blobs in the same container?
The Azure documentation says that storage blob containers can be made with public or private read access (see here). This says that public access can be set to 'Container' or 'Blob', and explains the differences in the table.

However, it isn't clear if, having set the container with Blob level public access:

```<code>container.CreateIfNotExists(Azure.Storage.Blobs.Models.PublicAccessType.Blob);
</code>```

This implies that the public read access is set on a blob by blob basis, and if so, how to set it up.

However, I am not sure this is true? I have seen various other posts about copying blobs around between different public/private containers, which somewhat backs up my thinking. The client creation doesnt appear to have a public/private setting:

```<code>BlobClient blobClient = container.GetBlobClient(filename);
</code>```

... and using the above coding, then all blobs created have public access.

My problem is that I need to allow users to change the state of uploaded images/videos to public or private. I am wondering if there is a less cludgy way than moving the blobs around between private and public containers..?

答:
Public access is a container level setting.
There are two options for public access: https://learn.microsoft.com/en-us/azure/storage/blobs/anonymous-read-access-configure?tabs=portal#set-the-public-access-level-for-a-container.

Public read access for blobs only (Blob): Anonymous requests can get blobs by their full URL (caller must know the container and blob name)

Public read access for container and its blobs (Container): Anonymous requests can get blob list for the container (caller must only know container name)

So I would say that yes, you either have to move them between containers or handle the authorization on your side.

Body:
The Azure documentation says that storage blob containers can be made with public or private read access (see here). This says that public access can be set to 'Container' or 'Blob', and explains the differences in the table.

However, it isn't clear if, having set the container with Blob level public access:

container.CreateIfNotExists(Azure.Storage.Blobs.Models.PublicAccessType.Blob);

This implies that the public read access is set on a blob by blob basis, and if so, how to set it up.

However, I am not sure this is true? I have seen various other posts about copying blobs around between different public/private containers, which somewhat backs up my thinking. The client creation doesnt appear to have a public/private setting:

BlobClient blobClient = container.GetBlobClient(filename);

... and using the above coding, then all blobs created have public access.

My problem is that I need to allow users to change the state of uploaded images/videos to public or private. I am wondering if there is a less cludgy way than moving the blobs around between private and public containers..?


问:
Move button when clicked
How do I move the button from the div with id of two to the div with id of one when I click the button?

  <button onclick="moveMe"></button>

```
<pre class="lang-js prettyprint-override"><code>function moveMe() {
 // ??
}
</code>```

答:
```<code><div id="one">

</div>

<div id="two">
  <button id="btn" onclick="moveMe">MoveMe</button>
</div>

 function moveMe() {
        var divOne = document.querySelector("#one");
        var btn = document.querySelector("#btn");
        divOne.appendChild(btn);
 }
</code>```

Title: Move button when clicked

Body:
How do I move the button from the div with id of two to the div with id of one when I click the button?

  <button onclick="moveMe"></button>

function moveMe() {
 // ??
}


问:
Rest API in Flutter Login
When I give header and body information inside my http request, it redirects automatically to next page even if i dont give any login credential in my Mobile App.

```<code>Future<Login> fetchLoginData() async {
    final http.Response response = await http.post(
      'http://lmsapi.design.net:88//api/login/login',
      headers: <String, String>{
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic XfnatLYBaDO2AKP6KfcIJg=='
      },
/*        body: {
          'companycode': 'ABC1001',
          'deploymentcode': 'ui11'
        }*/
    );
    if (response.statusCode == 200) {
      // then parse the JSON.
      return Login.fromJson(jsonDecode(response.body));
      } else {
      // then throw an exception.
      throw Exception('Failed to load Data');
    }
  }
</code>```

Can someone help me how to pass header and body inside my http request?

答:
The issue doesn't seem to be about handling the http response and leans more toward on how the navigation to the next page is handled. You'd need to check if fetchLoginData() returns the response. Future callback can be handled by using fetchLoginData().then() for example.

fetchLoginData().then((Login? loginData){
  if(loginData!=null){
    // Handle Navigation
  }
});
```

Then you may consider implementing the navigation once you got a successful response from fetchLoginData()

Title: Rest API in Flutter Login

Body:
When I give header and body information inside my http request, it redirects automatically to next page even if i dont give any login credential in my Mobile App.

Future<Login> fetchLoginData() async {
    final http.Response response = await http.post(
      'http://lmsapi.design.net:88//api/login/login',
      headers: <String, String>{
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic XfnatLYBaDO2AKP6KfcIJg=='
      },
/*        body: {
          'companycode': 'ABC1001',
          'deploymentcode': 'ui11'
        }*/
    );
    if (response.statusCode == 200) {
      // then parse the JSON.
      return Login.fromJson(jsonDecode(response.body));
      } else {
      // then throw an exception.
      throw Exception('Failed to load Data');
    }
  }

Can someone help me how to pass header and body inside my http request?

Body:
The issue doesn't seem to be about handling the http response and leans more toward on how the navigation to the next page is handled. You'd need to check if fetchLoginData() returns the response. Future callback can be handled by using fetchLoginData().then() for example.

fetchLoginData().then((Login? loginData){
  if(loginData!=null){
    // Handle Navigation
  }
});

Then you may consider implementing the navigation once you got a successful response from fetchLoginData()


问:
Calculating mean grades for deciles within a dataset with Python, grouped by another field
```<code>import pandas as pd
import csv

df_orig = pd.read_csv('test_sample.csv')
df_orig = df_orig[(df_orig['number']>0)]
decile_stats = df_orig.groupby(pd.qcut(df_orig.number, 5))['number'].mean()

print(decile_stats)
</code>```

I'm trying to use python to calculate statistics for deciles of my dataset. I can calculate the mean of each decile using qcut, but I want to group my numbers by the values in a second column. This way the deciles are calculated and reported on values according to their value in the family column.

family  number

0    1000    0.04

1    1000    0.20

2    1000    0.04

3    1000    0.16

4    1000    0.08

5    1000    0.02

6    1000    0.02

7    1000    0.02

8    1000    0.64

9    1000    0.04

My desired output would be:

Q1 1000  0.028617

Q2 1000  0.105060

Q3 1000  0.452467

Q4 1000  2.644886

Q5 1000  141.749797...

etc. with each 'family' shown, 1000, 2000, 3000 in this case.

答:
IIUC, you can use:

```<code>N = 3
labels = [f'Q{i}' for i in range(1, N+1)]
decile = lambda x: x.groupby(pd.qcut(x['number'], N, labels=labels)).mean()

out = df.groupby('family').apply(decile)['number'].rename('mean').reset_index()
</code>```

Output:

```<code>>>> out
   family number      mean
0    1000     Q1  0.030000
1    1000     Q2  0.080000
2    1000     Q3  0.333333
</code>```

Body:
import pandas as pd
import csv

df_orig = pd.read_csv('test_sample.csv')
df_orig = df_orig[(df_orig['number']>0)]
decile_stats = df_orig.groupby(pd.qcut(df_orig.number, 5))['number'].mean()

print(decile_stats)

I'm trying to use python to calculate statistics for deciles of my dataset. I can calculate the mean of each decile using qcut, but I want to group my numbers by the values in a second column. This way the deciles are calculated and reported on values according to their value in the family column.

family  number

0    1000    0.04

1    1000    0.20

2    1000    0.04

3    1000    0.16

4    1000    0.08

5    1000    0.02

6    1000    0.02

7    1000    0.02

8    1000    0.64

9    1000    0.04

My desired output would be:

Q1 1000  0.028617

Q2 1000  0.105060

Q3 1000  0.452467

Q4 1000  2.644886

Q5 1000  141.749797...

etc. with each 'family' shown, 1000, 2000, 3000 in this case.

Body:
IIUC, you can use:

N = 3
labels = [f'Q{i}' for i in range(1, N+1)]
decile = lambda x: x.groupby(pd.qcut(x['number'], N, labels=labels)).mean()

out = df.groupby('family').apply(decile)['number'].rename('mean').reset_index()

Output:

>>> out
   family number      mean
0    1000     Q1  0.030000
1    1000     Q2  0.080000
2    1000     Q3  0.333333


问:
SSO Okta is sitting at the okta developer page after login . NOT returning to the ACS URL of the service provider
Two scenarios

scenario #1. Logged in to Okta developer portal independently + Logged out from Service provider(SP)

scenario #2. Logged out from Okta + Logged out from Service Provider

In scenario #1, I tried to login into the SP, It get logged in via Okta(already logged in) and redirected back to the SP page with the logged-in state. Working as expected.

In scenario #2, I tried to login into the SP => it get redirected to Okta developer login page => logged in through GitHub => Redirected to the Okta developer portal dashboard page with logged-in state and sitting on the same okta developer page.NOT redirecting back to the SP page.

Scenario #1

Scenario #2

答:
Something is dodgy with your configuration. What is SSO URL configured for your SP to redirect users to for login? It should be taken from Okta app SAML metadata.

It would be helpful if you attach rather HAR file(s) demonstrating the full flow.


问:
How to launch Flutter App from MainActivity.java
I have created app. I want to run app when device is restart\turned on. So I implemented the functionality in native code. Now the native code is calling the MainActivity class when device is restarted. Now I want to make a function in MainActivity which will launch my app. Something Like I call main() method of main.dart file from MainActivity.java.

If anybody know then kindly answer this question.

答: Could you just create a Flutter project and add your native part in MainActivity.java?</p>


问:
MySQL/MariaDB GET_LOCK lifecyle with Events
I am attempting to use the GET_LOCK() functionality of MariaDB 10.0.19 to implement a system that limits events run by the event scheduler to only run one at a time.  Essentially each event tries to acquire a 'run_lock' and if successful it runs, otherwise it waits till the lock is available or times out.  The issue is, in testing, I can find many cases where my stored procedure does not release its lock even if it completes successfully.  Now I know when testing at the command line the lock is associated with my session - so if I exit the lock is released.  What I cannot seem to test/figure out is if an event terminates (normally or abnormally) will all of it's locks be released?

答:
You should proceed only if the lock is obtained successfully</p>
```<code>DELIMITER //

CREATE EVENT test_lock_1 ON SCHEDULE EVERY 1 MINUTE DO
BEGIN

  IF GET_LOCK('test', 30) IS TRUE THEN
    SELECT SLEEP(65);
  END IF;

END //

DELIMITER ;
</code>```

Body:
You should proceed only if the lock is obtained successfully

DELIMITER //

CREATE EVENT test_lock_1 ON SCHEDULE EVERY 1 MINUTE DO
BEGIN

  IF GET_LOCK('test', 30) IS TRUE THEN
    SELECT SLEEP(65);
  END IF;

END //

DELIMITER ;


问:
How do I make a locator based on custom attribute based on webpage of a hybrid app
I tried to use xpath for custom attribute provided by developers but getting no element found exception.

```<code>[HTTP] --> POST /wd/session/5fcb27d1-ab07-4d9b-b06f-cb4d006391e3/element
[HTTP] {"using":"xpath","value":"//input[@data-autoid='AC_NAME_ctrl']"}
[debug] [W3C (5fcb27d1)] Calling AppiumDriver.findElement() with args: ["xpath","//input[@data-autoid='AC_NAME_ctrl']","5fcb27d1-ab07-4d9b-b06f-cb4d006391e3"]
[debug] [BaseDriver] Valid locator strategies for this request: xpath, id, class name, accessibility id, css selector, -android uiautomator
[debug] [BaseDriver] Waiting up to 10000 ms for condition
[debug] [WD Proxy] Matched '/element' to command name 'findElement'
[debug] [WD Proxy] Proxying [POST /element] to [POST http://127.0.0.1:8201/wd/hub/session/bb01926e-16fe-426e-881c-d1b4c689bc8e/element] with body: {"strategy":"xpath","selector":"//input[@data-autoid='AC_NAME_ctrl']","context":"","multiple":false}
[WD Proxy] Got response with status 404: {"sessionId":"bb01926e-16fe-426e-881c-d1b4c689bc8e","value":{"error":"no such element","message":"An element could not be located on the page using the given search parameters","stacktrace":"io.appium.uiautomator2.common.exceptions.ElementNotFoundException: An element could not be located on the page using the given search parameters\n\tat io.appium.uiautomator2.handler.FindElement.findElement(FindElement.java:90)\n\tat io.appium.uiautomator2.handler.FindElement.safeHandle(FindElement.java:67)\n\tat io.appium.uiautomator2.handler.request.SafeRequestHandler.handle(SafeRequestHandler.java:59)\n\tat io.appium.uiautomator2.server.AppiumServlet.handleRequest(AppiumServlet.java:266)\n\tat io.appium.uiautomator2.server.AppiumServlet.handleHttpRequest(AppiumServlet.java:260)\n\tat io.appium.uiautomator2.http.ServerHandler.channelRead(ServerHandler.java:68)\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:366)\n\tat io.netty.channel.AbstractChannelHandlerCont...
</code>```

Code used:

```<code>WebElement f1 = driver.findElement(By.xpath("//input[@data-autoid='AC_NAME_ctrl']"));
f1.sendKeys("Rahul");
</code>```

data-autoid is custom attribute with value 'AC_NAME_ctrl'
Any help in this direction will be helpful.

答:
For hybrid apps, Appium has to know whether you want to automate the native aspects of the app or the web views.

Switch to web-context before interaction with web views elements.

NOTE: Starting from appium java client version is 8.0.0 for work with contexts, casting to SupportsContextSwitching might be required.

```<code>import io.appium.java_client.remote.SupportsContextSwitching;

contexts and find your one
((SupportsContextSwitching) driver).context("WEBVIEW_1");
// the name could be WEBVIEW_... you have to print all the available
// To avoid `ClassCastException`, the driver initially should be created as `AndroidDriver` or `IOSDriver`,
// e.g. AppiumDriver driver = new AndroidDriver(...);
</code>```

and then

```<code>WebElement f1 = driver.findElement(By.xpath("//input[@data-autoid='AC_NAME_ctrl']"));
f1.sendKeys("Rahul");
</code>```

do not forget to switch back to native.

```<code>((SupportsContextSwitching) driver).context("NATIVE_APP");
</code>```

This will print all the available contexts:

Set<String> contextNames = ((SupportsContextSwitching) driver).getContextHandles();
for (String contextName : contextNames) {
    System.out.println(contextName);
}
```

Reference

https://appium.io/docs/en/writing-running-appium/web/hybrid/

Body:
I tried to use xpath for custom attribute provided by developers but getting no element found exception.

[HTTP] --> POST /wd/session/5fcb27d1-ab07-4d9b-b06f-cb4d006391e3/element
[HTTP] {"using":"xpath","value":"//input[@data-autoid='AC_NAME_ctrl']"}
[debug] [W3C (5fcb27d1)] Calling AppiumDriver.findElement() with args: ["xpath","//input[@data-autoid='AC_NAME_ctrl']","5fcb27d1-ab07-4d9b-b06f-cb4d006391e3"]
[debug] [BaseDriver] Valid locator strategies for this request: xpath, id, class name, accessibility id, css selector, -android uiautomator
[debug] [BaseDriver] Waiting up to 10000 ms for condition
[debug] [WD Proxy] Matched '/element' to command name 'findElement'
[debug] [WD Proxy] Proxying [POST /element] to [POST http://127.0.0.1:8201/wd/hub/session/bb01926e-16fe-426e-881c-d1b4c689bc8e/element] with body: {"strategy":"xpath","selector":"//input[@data-autoid='AC_NAME_ctrl']","context":"","multiple":false}
[WD Proxy] Got response with status 404: {"sessionId":"bb01926e-16fe-426e-881c-d1b4c689bc8e","value":{"error":"no such element","message":"An element could not be located on the page using the given search parameters","stacktrace":"io.appium.uiautomator2.common.exceptions.ElementNotFoundException: An element could not be located on the page using the given search parameters\n\tat io.appium.uiautomator2.handler.FindElement.findElement(FindElement.java:90)\n\tat io.appium.uiautomator2.handler.FindElement.safeHandle(FindElement.java:67)\n\tat io.appium.uiautomator2.handler.request.SafeRequestHandler.handle(SafeRequestHandler.java:59)\n\tat io.appium.uiautomator2.server.AppiumServlet.handleRequest(AppiumServlet.java:266)\n\tat io.appium.uiautomator2.server.AppiumServlet.handleHttpRequest(AppiumServlet.java:260)\n\tat io.appium.uiautomator2.http.ServerHandler.channelRead(ServerHandler.java:68)\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:366)\n\tat io.netty.channel.AbstractChannelHandlerCont...

Code used:

WebElement f1 = driver.findElement(By.xpath("//input[@data-autoid='AC_NAME_ctrl']"));
f1.sendKeys("Rahul");

data-autoid is custom attribute with value 'AC_NAME_ctrl'
Any help in this direction will be helpful.

Body:
For hybrid apps, Appium has to know whether you want to automate the native aspects of the app or the web views.

Switch to web-context before interaction with web views elements.

NOTE: Starting from appium java client version is 8.0.0 for work with contexts, casting to SupportsContextSwitching might be required.

import io.appium.java_client.remote.SupportsContextSwitching;

contexts and find your one
((SupportsContextSwitching) driver).context("WEBVIEW_1");
// the name could be WEBVIEW_... you have to print all the available
// To avoid `ClassCastException`, the driver initially should be created as `AndroidDriver` or `IOSDriver`,
// e.g. AppiumDriver driver = new AndroidDriver(...);

and then

WebElement f1 = driver.findElement(By.xpath("//input[@data-autoid='AC_NAME_ctrl']"));
f1.sendKeys("Rahul");

do not forget to switch back to native.

((SupportsContextSwitching) driver).context("NATIVE_APP");

This will print all the available contexts:

Set<String> contextNames = ((SupportsContextSwitching) driver).getContextHandles();
for (String contextName : contextNames) {
    System.out.println(contextName);
}

Reference

https://appium.io/docs/en/writing-running-appium/web/hybrid/


问:
Something from string in list python
I have a list with keywords id = ['pop','ppp','cre'] and now I am going through a bunch of files/large strings and if any of these keywords are in these files than I have to be able to do something...

like:

```<code>id = ['pop','ppp','cre']
if id in dataset:
         print id
</code>```

But i think now all of these 3 or later maybe more have to be in the dataset and not just only one.

答:
You can use all to make sure all the values in your id list are in the dataset:

```<code>id = ['pop', 'ppp', 'cre']
if all(i in dataset for i in id):
    print id
</code>```

Title: Something from string in list python

Body:
I have a list with keywords id = ['pop','ppp','cre'] and now I am going through a bunch of files/large strings and if any of these keywords are in these files than I have to be able to do something...

like:

id = ['pop','ppp','cre']
if id in dataset:
         print id

But i think now all of these 3 or later maybe more have to be in the dataset and not just only one.

Body:
You can use all to make sure all the values in your id list are in the dataset:

id = ['pop', 'ppp', 'cre']
if all(i in dataset for i in id):
    print id


问:
Angular InjectionToken throws 'No provider for InjectionToken'
I'm currently learning the new Angular framework, and I'm trying to make a dynamic search bar which accepts a service name as an argument in order for it to dynamically resolve a service to query the backend service with.

For this I'm using an Injector, and loading the the service during ngOnInit. This works fine when using a string based provider, however my IDE notes that it's deprecated and I should use an InjectionToken which I can't seem to wrap my head around.

I expected the following code to work, as removing all instances of InjectionToken and replacing them with the direct string literal works:

I tried looking at the following documentation, but I didn't quite understand it as I feel like I did exactly what it says, yet it keeps telling me it doesn't work: https://angular.io/guide/dependency-injection-providers

Could someone tell me what I'm doing wrong?

Thanks

Module declaration

```<code>// app.module.ts
@NgModule({
  declarations: [
    AppComponent,
    SearchBarComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule
  ],
  providers: [
    {
      provide: new InjectionToken<ISearchable>('CustomerService'), // <-- doesn't work;  'CustomerService' <-- works
      useValue: CustomerService
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Search bar component:

```<code>// search-bar.component.ts
@Component({
  selector: 'search-bar',
  templateUrl: './search-bar.component.html',
  styleUrls: ['./search-bar.component.sass']
})
export class SearchBarComponent implements OnInit {

  @Input()
  source: string;

  private searcher: ISearchable;

  constructor(private injector: Injector) {}

  ngOnInit() {
    // error: Error: No provider for InjectionToken CustomerService!
    let token = new InjectionToken<ISearchable>(this.source);
    this.searcher = this.injector.get<ISearchable>(token);

    // this works, but it's deprecated and will probably break in the future
    // this.searcher = this.injector.get(this.source);
    console.log(this.searcher);
  }
}
</code>```

Using the search bar:

```<code><!-- app.component.html -->
<div class="row justify-content-center mb-2">
  <div class="col-8">
    <search-bar title="Customers" source="CustomerService"></search-bar>
  </div>
</div>
</code>```

Edit: Here's an example with the error:

https://stackblitz.com/edit/angular-3admbe

答: For anyone still struggling with this, it may be as simple as restarting VS Code, as was the case for me.  I'm not sure why, but that fixed it for me.  Of course, I tried this first, because I was quite certain the error was wrong to begin with.</p>

Body:
I'm currently learning the new Angular framework, and I'm trying to make a dynamic search bar which accepts a service name as an argument in order for it to dynamically resolve a service to query the backend service with.

For this I'm using an Injector, and loading the the service during ngOnInit. This works fine when using a string based provider, however my IDE notes that it's deprecated and I should use an InjectionToken which I can't seem to wrap my head around.

I expected the following code to work, as removing all instances of InjectionToken and replacing them with the direct string literal works:

I tried looking at the following documentation, but I didn't quite understand it as I feel like I did exactly what it says, yet it keeps telling me it doesn't work: https://angular.io/guide/dependency-injection-providers

Could someone tell me what I'm doing wrong?

Thanks

Module declaration

// app.module.ts
@NgModule({
  declarations: [
    AppComponent,
    SearchBarComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule
  ],
  providers: [
    {
      provide: new InjectionToken<ISearchable>('CustomerService'), // <-- doesn't work;  'CustomerService' <-- works
      useValue: CustomerService
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Search bar component:

// search-bar.component.ts
@Component({
  selector: 'search-bar',
  templateUrl: './search-bar.component.html',
  styleUrls: ['./search-bar.component.sass']
})
export class SearchBarComponent implements OnInit {

  @Input()
  source: string;

  private searcher: ISearchable;

  constructor(private injector: Injector) {}

  ngOnInit() {
    // error: Error: No provider for InjectionToken CustomerService!
    let token = new InjectionToken<ISearchable>(this.source);
    this.searcher = this.injector.get<ISearchable>(token);

    // this works, but it's deprecated and will probably break in the future
    // this.searcher = this.injector.get(this.source);
    console.log(this.searcher);
  }
}

Using the search bar:

    <search-bar title="Customers" source="CustomerService"></search-bar>

Edit: Here's an example with the error:

https://stackblitz.com/edit/angular-3admbe


问:
Wordpress ACF oEmbed field - Embedding Bandcamp content
I've set up with Advanced Custom Field a custom oEmbed field, called embed.

And it's displayed in the front end in the simplest way :

```<code>the_field('embed');
</code>```

Pasting the media url from Youtube, Vimeo or Souncloud works fine and the field displays  the player and it's content correctly.

However embedding Bandcamp content doesn't work.
If i paste the url directly, it just displays the url and doesn't grab the player from Bandcamp.
If i paste the iframe html provided by Bandcamp, it shows the html.

So i'm wondering if there is a workaround.

答:
ACF oEmbed field refers to Wordpress Embeds feature.

You can see the list of supported websites:
https://wordpress.org/support/article/embeds/

It's seems that Bandcamp isn't supported yet.

Body:
I've set up with Advanced Custom Field a custom oEmbed field, called embed.

And it's displayed in the front end in the simplest way :

the_field('embed');

Pasting the media url from Youtube, Vimeo or Souncloud works fine and the field displays  the player and it's content correctly.

However embedding Bandcamp content doesn't work.
If i paste the url directly, it just displays the url and doesn't grab the player from Bandcamp.
If i paste the iframe html provided by Bandcamp, it shows the html.

So i'm wondering if there is a workaround.


问:
Could not find the correct Provider<List<CurrentUser>> above this HomeBuilder Widget
I am trying to make chatting appp with fire base but stuck at getting list of recent chat  the error says =>  This happens because you used a BuildContext that does not include the provider
of your choice

```<code>class ProviderInit extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return StreamProvider<User?>.value(
    value: FirebaseAuth.instance.authStateChanges(),
    initialData: null,
    child: const MaterialApp(
    title: 'Chat Application',
    debugShowCheckedModeBanner: false,
      home:   Recent(),
  ));
  }
}
class Recent extends StatefulWidget {
const Recent({Key? key}) : super(key: key);

@override
RecentState createState() => RecentState();
}

class RecentState extends State<Recent> {
@override
Widget build(BuildContext context) {
final User?  firebaseUser = Provider.of<User?>(context);
if ((firebaseUser != null)) {
        return ConversationProvider(user: firebaseUser);

  } else {
  return const LoginScreen();

   }
 }
 }

class ConversationProvider extends StatelessWidget {
 const ConversationProvider({

required this.user,
}) ;

final User user;

@override
Widget build(BuildContext context) {
 return StreamProvider<List<Convo>>.value(
    value: FireStoreMethods().streamConversations(user.uid),
   catchError: (_, __) => [],
    initialData: [],
    child:Builder(
      builder: (context) {
        return ConversationDetailsProvider(user: user);
       }
     )

  );
}
}

class ConversationDetailsProvider extends StatelessWidget {
 const ConversationDetailsProvider({

required this.user,
 });

 final User user;

 @override
 Widget build(BuildContext context) {
 final List<Convo?> _convos = Provider.of<List<Convo>>(context);
     return StreamProvider<List<CurrentUser?>>.value(
           catchError: (_,err) => [],
            value: FireStoreMethods().getUsersByList(
                getUserIds(_convos)),
        initialData: [],
            child: Builder(
              builder: (context) {
                return  HomeBuilder();
              }
            ));

    }

 List<String> getUserIds(List<Convo?> _convos) {
  final List<String> users = <String>[];
 for (int i = 0; i < _convos.length; i++) {
  Convo c = _convos[i]!;
  c.userIds[0] != user.uid
      ? users.add(c.userIds[0])
      : users.add(c.userIds[1]);
   }
   return users;
 }
}

class HomeBuilder extends StatefulWidget {

@override
State<HomeBuilder> createState() => _HomeBuilderState();
 }

class _HomeBuilderState extends State<HomeBuilder> {

 @override
 Widget build(BuildContext context) {
 final User? firebaseUser = Provider.of<User>(context);
 final List<Convo?> _convos = Provider.of<List<Convo>>(context);
 final List<CurrentUser?> _users = Provider.of<List<CurrentUser>>(context);
  return Scaffold(
     appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            // IconButton(
            //     onPressed: Authentication.handleLogout,
            //     icon: Icon(Icons.first_page, size: 30)),
            Text(firebaseUser!.displayName!, style: TextStyle(fontSize: 18)),

          ],
        )),
    body: ListView(
        scrollDirection: Axis.vertical,
        shrinkWrap: true,
        children: getWidgets(context, firebaseUser, _convos, _users))
    );
     }

   // void createNewConvo(BuildContext context) {
     Map<String, CurrentUser> getUserMap(List<CurrentUser?> users) {
    final Map<String, CurrentUser> userMap = {};
    for (int i = 0; i < users.length; i++) {
    CurrentUser u = users[i]!;
    userMap[u.uid] = u;
    }
    return userMap;
    }

 List<Widget> getWidgets(
  BuildContext context, User user, List<Convo?> _convos, List<CurrentUser?> _users) {
 final List<Widget> list = <Widget>[];
 if (_convos != null && _users != null && user != null) {
  final Map<String, CurrentUser> userMap = getUserMap(_users);
  for (int i = 0; i < _convos.length; i++) {
    Convo c = _convos[i]!;
    if (c.userIds[0] == user.uid) {
      list.add(ConvoListItem(
          user: user,
          peer: userMap[c.userIds[1]]!,
          lastMessage: c.lastMessage));
    } else {
      list.add(ConvoListItem(
          user: user,
          peer: userMap[c.userIds[0]]!,
          lastMessage: c.lastMessage));
    }
  }
}

return list;
</code>```

}
}

some one please help thanks in advance

答:
That is quite a long code but I get the gist of it since I encountered one like this earlier today.

It is quite simple to be honest, one of the most optimal and easiest solution is to always use the all of your providers as the parent of your MaterialApp widget (you can use MultiProvider class along with Consumer3(3 or whatever is the number of your providers you want to use, max upto 6).

To debug this yourself or how to find what was the problem, I highly recommend opening Dart dev tool on browser and checking out the widget hierarchy, and observe whether the place where you were trying to access the provider actually falls under the hierarchy or not? If it doesn't you need to figure out what you can do to make it happen which will eventually solve your problem.

But it is also recommended to use providers at the root of your application.

Body:
I am trying to make chatting appp with fire base but stuck at getting list of recent chat  the error says =>  This happens because you used a BuildContext that does not include the provider
of your choice

class ProviderInit extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return StreamProvider<User?>.value(
    value: FirebaseAuth.instance.authStateChanges(),
    initialData: null,
    child: const MaterialApp(
    title: 'Chat Application',
    debugShowCheckedModeBanner: false,
      home:   Recent(),
  ));
  }
}
class Recent extends StatefulWidget {
const Recent({Key? key}) : super(key: key);

@override
RecentState createState() => RecentState();
}

class RecentState extends State<Recent> {
@override
Widget build(BuildContext context) {
final User?  firebaseUser = Provider.of<User?>(context);
if ((firebaseUser != null)) {
        return ConversationProvider(user: firebaseUser);

  } else {
  return const LoginScreen();

   }
 }
 }

class ConversationProvider extends StatelessWidget {
 const ConversationProvider({

required this.user,
}) ;

final User user;

@override
Widget build(BuildContext context) {
 return StreamProvider<List<Convo>>.value(
    value: FireStoreMethods().streamConversations(user.uid),
   catchError: (_, __) => [],
    initialData: [],
    child:Builder(
      builder: (context) {
        return ConversationDetailsProvider(user: user);
       }
     )

  );
}
}

class ConversationDetailsProvider extends StatelessWidget {
 const ConversationDetailsProvider({

required this.user,
 });

 final User user;

 @override
 Widget build(BuildContext context) {
 final List<Convo?> _convos = Provider.of<List<Convo>>(context);
     return StreamProvider<List<CurrentUser?>>.value(
           catchError: (_,err) => [],
            value: FireStoreMethods().getUsersByList(
                getUserIds(_convos)),
        initialData: [],
            child: Builder(
              builder: (context) {
                return  HomeBuilder();
              }
            ));

    }

 List<String> getUserIds(List<Convo?> _convos) {
  final List<String> users = <String>[];
 for (int i = 0; i < _convos.length; i++) {
  Convo c = _convos[i]!;
  c.userIds[0] != user.uid
      ? users.add(c.userIds[0])
      : users.add(c.userIds[1]);
   }
   return users;
 }
}

class HomeBuilder extends StatefulWidget {

@override
State<HomeBuilder> createState() => _HomeBuilderState();
 }

class _HomeBuilderState extends State<HomeBuilder> {

 @override
 Widget build(BuildContext context) {
 final User? firebaseUser = Provider.of<User>(context);
 final List<Convo?> _convos = Provider.of<List<Convo>>(context);
 final List<CurrentUser?> _users = Provider.of<List<CurrentUser>>(context);
  return Scaffold(
     appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            // IconButton(
            //     onPressed: Authentication.handleLogout,
            //     icon: Icon(Icons.first_page, size: 30)),
            Text(firebaseUser!.displayName!, style: TextStyle(fontSize: 18)),

          ],
        )),
    body: ListView(
        scrollDirection: Axis.vertical,
        shrinkWrap: true,
        children: getWidgets(context, firebaseUser, _convos, _users))
    );
     }

   // void createNewConvo(BuildContext context) {
     Map<String, CurrentUser> getUserMap(List<CurrentUser?> users) {
    final Map<String, CurrentUser> userMap = {};
    for (int i = 0; i < users.length; i++) {
    CurrentUser u = users[i]!;
    userMap[u.uid] = u;
    }
    return userMap;
    }

 List<Widget> getWidgets(
  BuildContext context, User user, List<Convo?> _convos, List<CurrentUser?> _users) {
 final List<Widget> list = <Widget>[];
 if (_convos != null && _users != null && user != null) {
  final Map<String, CurrentUser> userMap = getUserMap(_users);
  for (int i = 0; i < _convos.length; i++) {
    Convo c = _convos[i]!;
    if (c.userIds[0] == user.uid) {
      list.add(ConvoListItem(
          user: user,
          peer: userMap[c.userIds[1]]!,
          lastMessage: c.lastMessage));
    } else {
      list.add(ConvoListItem(
          user: user,
          peer: userMap[c.userIds[0]]!,
          lastMessage: c.lastMessage));
    }
  }
}

return list;

}
}

some one please help thanks in advance


问:
How to preview a Composable with non-null type parameters?
```<code>@Composable
fun VerifyScreen(
    email: String,
    navigator: DestinationsNavigator
) {
// ..

}

@Composable
@Preview
fun VerifyScreenPreview() {
    VerifyScreen("you@re.awesome", null)
}
</code>```

Null can not be a value of a non-null type DestinationsNavigator

Of course you can change the type by adding a question mark, but what if that is not an option?

```<code>navigator: DestinationsNavigator?
</code>```

答:
It's discouraged to pass NavController or anything like that to your Composables, see the decumentation.
If you follow the recommendation, you will simply pass empty lambda (or more of them) from your Preview

Pass lambdas that should be triggered by the composable to navigate, rather than the NavController itself.

The problem with that is when you need a lot of lambdas in your Composable, it doesn't look very nice. One option then is not to preview such a big Composable as a whole but rather preview some smaller pieces of the ui. The other option would be to create some interface for the DestinationsNavigator that you can mock from your previews.

Body:
@Composable
fun VerifyScreen(
    email: String,
    navigator: DestinationsNavigator
) {
// ..

}

@Composable
@Preview
fun VerifyScreenPreview() {
    VerifyScreen("you@re.awesome", null)
}

Null can not be a value of a non-null type DestinationsNavigator

Of course you can change the type by adding a question mark, but what if that is not an option?

navigator: DestinationsNavigator?


问:
You may have encountered a bug in the Ruby interpreter or extension libraries
I have got a new MacBook, and are trying to install some pods.
I first did sudo gem install cocoapods on root, then did pod install in the directory I need the pods.
Got this error, and have no clue what went wrong.

From Crash Report:

Process:               ruby [5444]
Path:                  /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/bin/ruby
Identifier:            ruby
Version:               145.100.1
Code Type:             ARM-64 (Native)
Parent Process:        zsh [5282]
Responsible:           Terminal [5005]
User ID:               501

Date/Time:             2021-09-27 21:24:20.779 +0200
OS Version:            macOS 11.6 (20G165)
Report Version:        12
Anonymous UUID:       --D950-78ED-2DF378C6BA5B

Sleep/Wake UUID:      -FE18-47F9-9A4EF2935C96

Time Awake Since Boot: 29000 seconds
Time Since Wake:       1900 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_INSTRUCTION (SIGABRT)
Exception Codes:       0x0000000000000001, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
dyld3 mode
abort() called.

x

x

x

x

External Modification Summary:
Calls made by other processes targeting this process:
task_for_pid: 0
thread_create: 0
thread_set_state: 0
Calls made by this process:
task_for_pid: 0
thread_create: 0
thread_set_state: 0
Calls made by all processes on this machine:
task_for_pid: 0
thread_create: 0
thread_set_state: 0

VM Region Summary:
ReadOnly portion of Libraries: Total=574.8M resident=0K(0%) swapped_out_or_unallocated=574.8M(100%)
Writable regions: Total=356.4M written=0K(0%) resident=0K(0%) swapped_out=0K(0%) unallocated=356.4M(100%)

```<code>                            VIRTUAL   REGION
</code>```

REGION TYPE                        SIZE    COUNT (non-coalesced)
===========                     =======  =======
Activity Tracing                   256K        1
Kernel Alloc Once                   32K        1
MALLOC                           105.2M       32
MALLOC guard page                   96K        5
MALLOC_MEDIUM (reserved)         240.0M        2         reserved VM address space (unallocated)
STACK GUARD                       56.1M        4
Stack                             10.6M        4
VM_ALLOCATE                        1.0G        4
VM_ALLOCATE (reserved)              12K        1         reserved VM address space (unallocated)
__AUTH                             273K       64
__AUTH_CONST                      3528K      153
__DATA                            1616K      162
__DATA_CONST                      4536K      173
__DATA_DIRTY                       313K       63
__LINKEDIT                       490.7M       27
__OBJC_CONST                       437K       41
__OBJC_RO                         75.1M        1
__OBJC_RW                         2576K        1
__TEXT                            84.2M      185
__UNICODE                          588K        1
shared memory                       32K        2
===========                     =======  =======
TOTAL                              2.1G      927
TOTAL, minus reserved VM space     1.8G      927

答: Closing all instances of Terminal, then re-opening terminal and running pod install in the relevant directory did the job for me :)</p>

Body:
I have got a new MacBook, and are trying to install some pods.
I first did sudo gem install cocoapods on root, then did pod install in the directory I need the pods.
Got this error, and have no clue what went wrong.

From Crash Report:

Process:               ruby [5444]
Path:                  /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/bin/ruby
Identifier:            ruby
Version:               145.100.1
Code Type:             ARM-64 (Native)
Parent Process:        zsh [5282]
Responsible:           Terminal [5005]
User ID:               501

Date/Time:             2021-09-27 21:24:20.779 +0200
OS Version:            macOS 11.6 (20G165)
Report Version:        12
Anonymous UUID:       --D950-78ED-2DF378C6BA5B

Sleep/Wake UUID:      -FE18-47F9-9A4EF2935C96

Time Awake Since Boot: 29000 seconds
Time Since Wake:       1900 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_INSTRUCTION (SIGABRT)
Exception Codes:       0x0000000000000001, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
dyld3 mode
abort() called.

x

x

x

x

External Modification Summary:
Calls made by other processes targeting this process:
task_for_pid: 0
thread_create: 0
thread_set_state: 0
Calls made by this process:
task_for_pid: 0
thread_create: 0
thread_set_state: 0
Calls made by all processes on this machine:
task_for_pid: 0
thread_create: 0
thread_set_state: 0

VM Region Summary:
ReadOnly portion of Libraries: Total=574.8M resident=0K(0%) swapped_out_or_unallocated=574.8M(100%)
Writable regions: Total=356.4M written=0K(0%) resident=0K(0%) swapped_out=0K(0%) unallocated=356.4M(100%)

                            VIRTUAL   REGION

REGION TYPE                        SIZE    COUNT (non-coalesced)
===========                     =======  =======
Activity Tracing                   256K        1
Kernel Alloc Once                   32K        1
MALLOC                           105.2M       32
MALLOC guard page                   96K        5
MALLOC_MEDIUM (reserved)         240.0M        2         reserved VM address space (unallocated)
STACK GUARD                       56.1M        4
Stack                             10.6M        4
VM_ALLOCATE                        1.0G        4
VM_ALLOCATE (reserved)              12K        1         reserved VM address space (unallocated)
__AUTH                             273K       64
__AUTH_CONST                      3528K      153
__DATA                            1616K      162
__DATA_CONST                      4536K      173
__DATA_DIRTY                       313K       63
__LINKEDIT                       490.7M       27
__OBJC_CONST                       437K       41
__OBJC_RO                         75.1M        1
__OBJC_RW                         2576K        1
__TEXT                            84.2M      185
__UNICODE                          588K        1
shared memory                       32K        2
===========                     =======  =======
TOTAL                              2.1G      927
TOTAL, minus reserved VM space     1.8G      927


问:
PHP and Objects - Extending a common object, which other objects inherit from
I have a base object (form_field_base) that is extended/inherited by other objects in the form of:

```<code>class form_field_base {
    // Lots of code
}
class form_field_text extends form_field_base {
    // Lots of code
}
class form_field_email extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_file extends form_field_base {
    // Lots of code, for example uploading files
}
</code>```

The "form_field_base" provides helper methods that all of the form field types use, for example a html() function calls the specific object (form_field_email::html_input) to get the  field, then put that in a string with the standard  tag, etc.

All of these objects are used by many projects.

However, this latest project I'm working on requires the "form_field_base" object to be customised to allow the setting of some help text, a feature that no other project requires, and if future projects do, it will probably be done differently.

So how should this have be organised?

Ideally I won't have a complete copy of "form_field_base", as that would cause code duplication.

And it does seem like quite a bit of overhead to have dummy intermediate objects:

```<code>class form_field_base_common {
    // Lots of code
}
class form_field_base extends form_field_base_common {
    // By default is empty
}

class form_field_text_common extends form_field_base {
    // Lots of code
}
class form_field_text extends form_field_text_common {
    // ...
}

class form_field_email_common extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_email extends form_field_email_common {
    // ...
}

class form_field_file_common extends form_field_base {
    // Lots of code, for example uploading files
}
class form_field_file extends form_field_file_common {
    // ...
}
</code>```

Taking that each one has it's own file, which is auto-loaded (either a from a project specific location, if it exists, or from a common folder that all projects can access)... that is already 8 files that need to be found, opened, parsed, etc, just for supporting a form.

Surly there has to be a better way?

答:
You have your inheritance chain and you want to modify the base implementation on a per project base while still keeping the common code and types (and not being forced to severely modify the existing projects).

The way to go is to decouple the common functionality from project specific customizations. Use the decorator pattern which even enables you to share customizations between projects.

You situation is for all existing projects:

```<code>A <- B <- C

A->a()
B->a(), B->b()
C->a(), C->b(), C->c()
</code>```

Your new project (lets say project 1) shall have:

```<code>A1 <- B <- C

A1->a(), A1->a1(),
B->a(), B->a1(), B->b()
C->a(), C->a1(), C->b(), C->c()
</code>```

The decorator pattern requires you to create a decorator for each object you want to extend (A1, B1, C1). You want the custom methods of A1 also available in your decorating B1 and C1, so you need to chain them the same way as the original classes.

```<code>A1 decorates A
B1 decorates B
C1 decorates C

A1 <- B1 <- C1

A1->a1()
B1->a1()
C1->a1()
</code>```

You still want the functionality of A, B, C also in your decorating classes, so you need to create a link between each decorator and its decorating source class and delegate the appropriate methods:

```<code>A1 hosts a reference of A
B1 hosts a reference of B
C1 hosts a reference of C

A1->a() ----> $this->myA->a();
B1->a() ----> $this->myB->a();
B1->b() ----> $this->myB->b();
</code>```

All custom project 1 methods are executed directly:

```<code>A1->a1() ----> $this->a1();
</code>```

In your new project 1 you use then:

```<code>A1 instead of A
B1 instead of B
C1 instead of C
</code>```

Your A1, B1 and C1 may be allowed to create their instances of A, B, C right in their constructor although you could pass the instances to enable multiple decorations. In that case you will need proper interfaces, lets say IA, IB, IC. Then your A1 could have the method setA(IA theA) where theA might be an exact A or even an A1 or A2 or A3 ... But this is more advanced and you will find more information by googling the decorator pattern and you perhaps need a little bit of experience with interfaces and polymorphy.

Altogether:

Leave your inheritance chain as it is

Create a decorator chain for each custom project

Link the decorators to their original class and delegate the common functionality.

Use the decorators instead of the original classes in your custom project. They are now identical to their originals plus have the additional methods you want to add.

Body:
I have a base object (form_field_base) that is extended/inherited by other objects in the form of:

class form_field_base {
    // Lots of code
}
class form_field_text extends form_field_base {
    // Lots of code
}
class form_field_email extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_file extends form_field_base {
    // Lots of code, for example uploading files
}

The "form_field_base" provides helper methods that all of the form field types use, for example a html() function calls the specific object (form_field_email::html_input) to get the  field, then put that in a string with the standard  tag, etc.

All of these objects are used by many projects.

However, this latest project I'm working on requires the "form_field_base" object to be customised to allow the setting of some help text, a feature that no other project requires, and if future projects do, it will probably be done differently.

So how should this have be organised?

Ideally I won't have a complete copy of "form_field_base", as that would cause code duplication.

And it does seem like quite a bit of overhead to have dummy intermediate objects:

class form_field_base_common {
    // Lots of code
}
class form_field_base extends form_field_base_common {
    // By default is empty
}

class form_field_text_common extends form_field_base {
    // Lots of code
}
class form_field_text extends form_field_text_common {
    // ...
}

class form_field_email_common extends form_field_text {
    // Extending the text object to update validation, and set input type="email"
}
class form_field_email extends form_field_email_common {
    // ...
}

class form_field_file_common extends form_field_base {
    // Lots of code, for example uploading files
}
class form_field_file extends form_field_file_common {
    // ...
}

Taking that each one has it's own file, which is auto-loaded (either a from a project specific location, if it exists, or from a common folder that all projects can access)... that is already 8 files that need to be found, opened, parsed, etc, just for supporting a form.

Surly there has to be a better way?

Body:
You have your inheritance chain and you want to modify the base implementation on a per project base while still keeping the common code and types (and not being forced to severely modify the existing projects).

The way to go is to decouple the common functionality from project specific customizations. Use the decorator pattern which even enables you to share customizations between projects.

You situation is for all existing projects:

A <- B <- C

A->a()
B->a(), B->b()
C->a(), C->b(), C->c()

Your new project (lets say project 1) shall have:

A1 <- B <- C

A1->a(), A1->a1(),
B->a(), B->a1(), B->b()
C->a(), C->a1(), C->b(), C->c()

The decorator pattern requires you to create a decorator for each object you want to extend (A1, B1, C1). You want the custom methods of A1 also available in your decorating B1 and C1, so you need to chain them the same way as the original classes.

A1 decorates A
B1 decorates B
C1 decorates C

A1 <- B1 <- C1

A1->a1()
B1->a1()
C1->a1()

You still want the functionality of A, B, C also in your decorating classes, so you need to create a link between each decorator and its decorating source class and delegate the appropriate methods:

A1 hosts a reference of A
B1 hosts a reference of B
C1 hosts a reference of C

A1->a() ----> $this->myA->a();
B1->a() ----> $this->myB->a();
B1->b() ----> $this->myB->b();

All custom project 1 methods are executed directly:

A1->a1() ----> $this->a1();

In your new project 1 you use then:

A1 instead of A
B1 instead of B
C1 instead of C

Your A1, B1 and C1 may be allowed to create their instances of A, B, C right in their constructor although you could pass the instances to enable multiple decorations. In that case you will need proper interfaces, lets say IA, IB, IC. Then your A1 could have the method setA(IA theA) where theA might be an exact A or even an A1 or A2 or A3 ... But this is more advanced and you will find more information by googling the decorator pattern and you perhaps need a little bit of experience with interfaces and polymorphy.

Altogether:

Leave your inheritance chain as it is

Create a decorator chain for each custom project

Link the decorators to their original class and delegate the common functionality.

Use the decorators instead of the original classes in your custom project. They are now identical to their originals plus have the additional methods you want to add.


问:
React Native - React Navigation slow transitions when nesting navigators
I am building a cross-platform native application using react-native and using react-navigation for navigating to and from screens and managing navigation state using redux. The problem arises when I am nesting my navigators.

For example, I am using Stack Navigator as the default navigator for my app.

```<code>export const DefaultNavigate = new StackNavigator(
{
        Login: {
            screen: LoginScreen,
        },
        Home: {
            screen: AppDrawerNavigate,
        },
        AppTabNav: {
            screen: AppTabNavigator,
        },
    }
);
</code>```

where my first screen is loginscreen and home screen is a drawer navigator.

```<code>const AppDrawerNavigate = new DrawerNavigator(
{
        InProcess: {
             screen: InProcess,
        },
        Machine: {
             screen: Machine
        },
        Settings: {
             screen: Settings
        },
        Logout: {
             screen: Logout
        },
        ContactUs: {
             screen: ContactUs
        }
    }
);
</code>```

When the user clicks on the Machine in the Drawer Navigator I am navigating the screen to AppTabNav declared in DefaultNavigator.

```<code>const AppTabNavigator = new TabNavigator(
    {
        MachineList: {
            screen: MachineList,
        },
        CalendarView: {
            screen: CalendarView,
        }
    },
);
</code>```

which is a tab navigator with two screens as the name suggests one is using listview to display list and the other is using the calendarview to display calendar. There are around only 30-40 items in my dataSource of listview so rendering them is a piece of cake for listview. But when there is navigation from any screen to Machine screen from DrawerNavigator there is lag of 1-2sec and js thread drops to -2.1 which is really slowing down the transition.

and if someone need the code for Machine screen in drawer navigator here it is,

```<code>componentDidMount() {
    if(this.state.loaded)
        this.props.navigation.dispatch({ type: MACHINE});
}
render() {
    return <AppActivityIndicator />
}
</code>```

the following is my reducer code which is handling navigation of the screen,

```<code>case types.MACHINE:
  nextState = DefaultNavigate.router.getStateForAction(
    NavigationActions.reset({
      index: 1,
      actions: [
        NavigationActions.navigate({ routeName: 'Home' }),
        NavigationActions.navigate({ routeName: 'AppTabNav' })
      ]
    }),
    state
  );
</code>```

the following is the render method of MachineList screen in drawer navigator,

```<code>render() {
    return (
        <View style={styles.container}>
            <AppStatusBar />
            <ListView
                initialListSize={10}
                dataSource={this.state.dataSource}
                renderRow={this.renderRow.bind(this)}
                enableEmptySections={true}
            />
        </View>
    );
}
</code>```

Please help me out of this one. What am I doing wrong?

dependemcies

```<code>"dependencies": {
    "native-base": "^2.3.1",
    "react": "16.0.0-alpha.12",
    "react-devtools": "^2.5.0",
    "react-native": "0.47.1",
    "react-native-calendars": "^1.5.8",
    "react-native-vector-icons": "^4.3.0",
    "react-navigation": "^1.0.0-beta.11",
    "react-redux": "^5.0.6",
    "redux": "^3.7.2",
    "redux-logger": "^3.0.6",
    "redux-persist": "^4.9.1",
    "redux-thunk": "^2.2.0"
},
"devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "3.0.0",
    "jest": "20.0.4",
    "react-test-renderer": "16.0.0-alpha.12"
},
</code>```

答:
I was encountering the same issue with my application. Similar to what other people have described, I have nested Stack and Drawer navigators. The lagginess for me was with the transition between screens in a nested Stack Navigator.

I tried using InteractionManager to resolve this, but it did not seem to make much difference.  Eventually I found that building a simple timeout in to delay the rendering of large components made a huge difference.

So, I wrote this simple useIsReady hook which I now use in my screens:

import { useEffect, useState } from "react";

const useIsReady = () => {
  const [isReady, setIsReady] = useState(false);

  useEffect(() => {
    setTimeout(() => setIsReady(true), 100);
  }, []);

  return isReady;
};

export default useIsReady;```
</div>
</div>
</p>
<p>This is how I use the hook in my screens:</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-js lang-js prettyprint-override"><code>import React, { memo } from "react";
import { useTheme } from "react-native-paper";
import { View, ActivityIndicator } from "react-native";
import { useIsReady } from "hooks";

const BusyIndicator = () => {
  const theme = useTheme();
  return (
    <View style={{ flex: 1, justifyContent: "center" }}>
      <ActivityIndicator size="large" color={theme.colors.primary} />
    </View>
  );
};

const Camera = () => {
  const isReady = useIsReady();

  if (!isReady ) {
    return <BusyIndicator />;
  }

  return (
    <> ... </>
  );
};

export default memo(Camera);</code>```

I have found that this has made the world of difference, and my screen transitions are now completely smooth.

Body:
I am building a cross-platform native application using react-native and using react-navigation for navigating to and from screens and managing navigation state using redux. The problem arises when I am nesting my navigators.

For example, I am using Stack Navigator as the default navigator for my app.

export const DefaultNavigate = new StackNavigator(
{
        Login: {
            screen: LoginScreen,
        },
        Home: {
            screen: AppDrawerNavigate,
        },
        AppTabNav: {
            screen: AppTabNavigator,
        },
    }
);

where my first screen is loginscreen and home screen is a drawer navigator.

const AppDrawerNavigate = new DrawerNavigator(
{
        InProcess: {
             screen: InProcess,
        },
        Machine: {
             screen: Machine
        },
        Settings: {
             screen: Settings
        },
        Logout: {
             screen: Logout
        },
        ContactUs: {
             screen: ContactUs
        }
    }
);

When the user clicks on the Machine in the Drawer Navigator I am navigating the screen to AppTabNav declared in DefaultNavigator.

const AppTabNavigator = new TabNavigator(
    {
        MachineList: {
            screen: MachineList,
        },
        CalendarView: {
            screen: CalendarView,
        }
    },
);

which is a tab navigator with two screens as the name suggests one is using listview to display list and the other is using the calendarview to display calendar. There are around only 30-40 items in my dataSource of listview so rendering them is a piece of cake for listview. But when there is navigation from any screen to Machine screen from DrawerNavigator there is lag of 1-2sec and js thread drops to -2.1 which is really slowing down the transition.

and if someone need the code for Machine screen in drawer navigator here it is,

componentDidMount() {
    if(this.state.loaded)
        this.props.navigation.dispatch({ type: MACHINE});
}
render() {
    return <AppActivityIndicator />
}

the following is my reducer code which is handling navigation of the screen,

case types.MACHINE:
  nextState = DefaultNavigate.router.getStateForAction(
    NavigationActions.reset({
      index: 1,
      actions: [
        NavigationActions.navigate({ routeName: 'Home' }),
        NavigationActions.navigate({ routeName: 'AppTabNav' })
      ]
    }),
    state
  );

the following is the render method of MachineList screen in drawer navigator,

render() {
    return (
        <View style={styles.container}>
            <AppStatusBar />
            <ListView
                initialListSize={10}
                dataSource={this.state.dataSource}
                renderRow={this.renderRow.bind(this)}
                enableEmptySections={true}
            />
        </View>
    );
}

Please help me out of this one. What am I doing wrong?

dependemcies

"dependencies": {
    "native-base": "^2.3.1",
    "react": "16.0.0-alpha.12",
    "react-devtools": "^2.5.0",
    "react-native": "0.47.1",
    "react-native-calendars": "^1.5.8",
    "react-native-vector-icons": "^4.3.0",
    "react-navigation": "^1.0.0-beta.11",
    "react-redux": "^5.0.6",
    "redux": "^3.7.2",
    "redux-logger": "^3.0.6",
    "redux-persist": "^4.9.1",
    "redux-thunk": "^2.2.0"
},
"devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "3.0.0",
    "jest": "20.0.4",
    "react-test-renderer": "16.0.0-alpha.12"
},

Body:
I was encountering the same issue with my application. Similar to what other people have described, I have nested Stack and Drawer navigators. The lagginess for me was with the transition between screens in a nested Stack Navigator.

I tried using InteractionManager to resolve this, but it did not seem to make much difference.  Eventually I found that building a simple timeout in to delay the rendering of large components made a huge difference.

So, I wrote this simple useIsReady hook which I now use in my screens:

import { useEffect, useState } from "react";

const useIsReady = () => {
  const [isReady, setIsReady] = useState(false);

  useEffect(() => {
    setTimeout(() => setIsReady(true), 100);
  }, []);

  return isReady;
};

export default useIsReady;

This is how I use the hook in my screens:

import React, { memo } from "react";
import { useTheme } from "react-native-paper";
import { View, ActivityIndicator } from "react-native";
import { useIsReady } from "hooks";

const BusyIndicator = () => {
  const theme = useTheme();
  return (
    <View style={{ flex: 1, justifyContent: "center" }}>
      <ActivityIndicator size="large" color={theme.colors.primary} />
    </View>
  );
};

const Camera = () => {
  const isReady = useIsReady();

  if (!isReady ) {
    return <BusyIndicator />;
  }

  return (
    <> ... </>
  );
};

export default memo(Camera);

I have found that this has made the world of difference, and my screen transitions are now completely smooth.


问:
Spring - import jpa repositories from another module
I have two gradle modules: common and app

The common module contains a JpaRepository named OutboxJpaMessageRepository.

The app module contains another JpaRepository named RentRepository.

The common has the following configuration class, which is auto-imported by the other module (using a spring.factories file):

@Configuration
@EntityScan("path.to.common.module")
@EnableJpaRepositories("path.to.common.module")
@ComponentScan("path.to.common.module")
public class OutboxMessagingAutoConfig {
}
```

The problem is that @EnableJpaRepositories("path.to.common.module") overrides the default auto-configuration of the application, and the app can't find RentRepository (different package).

Can a library exports jpa repositories without override the default configuration of the client?

I don't want to re-configure all apps which use the common module

答:
I found the solution to my problem.

I solved using @AutoConfigurationPackage

@Configuration
@AutoConfigurationPackage
@ComponentScan("path.to.common.module")
public class OutboxJpaMessagingConfig {
}
```

Body:
I have two gradle modules: common and app

The common module contains a JpaRepository named OutboxJpaMessageRepository.

The app module contains another JpaRepository named RentRepository.

The common has the following configuration class, which is auto-imported by the other module (using a spring.factories file):

@Configuration
@EntityScan("path.to.common.module")
@EnableJpaRepositories("path.to.common.module")
@ComponentScan("path.to.common.module")
public class OutboxMessagingAutoConfig {
}

The problem is that @EnableJpaRepositories("path.to.common.module") overrides the default auto-configuration of the application, and the app can't find RentRepository (different package).

Can a library exports jpa repositories without override the default configuration of the client?

I don't want to re-configure all apps which use the common module


问:
How to save a large pandas dataframe with compex arrays and load it up again?
I have a large pandas DataFrame with individual elements that are complex numpy arrays. Please see below a minimal code example to reproduce the scenario:

```<code>
d = {f'x{i}': [] for i in range(4)}
df = pd.DataFrame(data=d).astype(object)

for K in range(4):
    for i in range(4):

        df.loc[f'{K}', f'x{i}'] = np.random.random(size=(2,2)) + np.random.random(size=(2,2)) * 1j

df

</code>```

What is the best way to save these and load them up again for use later?

The problem I am having is that when I increase the size of the matrices stored and the number of elements, I get an OverflowError when I try to save it as .h5 file as shown below:

```<code>import pandas as pd

size = (300,300)
xs = 1500

d = {f'x{i}': [] for i in range(xs)}
df = pd.DataFrame(data=d).astype(object)

for K in range(10):
    for i in range(xs):

        df.loc[f'{K}', f'x{i}'] = np.random.random(size=size) + np.random.random(size=size) * 1j

df.to_hdf('test.h5', key="df", mode="w")

load_test = pd.read_hdf("test.h5", "df")
</code>```
```<code>---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-124-8cb8df1a0653> in <module>
     12         df.loc[f'{K}', f'x{i}'] = np.random.random(size=size) + np.random.random(size=size) * 1j
     13
---> 14 df.to_hdf('test.h5', key="df", mode="w")
     15
     16

~/PQKs/pqks/lib/python3.6/site-packages/pandas/core/generic.py in to_hdf(self, path_or_buf, key, mode, complevel, complib, append, format, index, min_itemsize, nan_rep, dropna, data_columns, errors, encoding)
   2447             data_columns=data_columns,
   2448             errors=errors,
-> 2449             encoding=encoding,
   2450         )
   2451

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in to_hdf(path_or_buf, key, value, mode, complevel, complib, append, format, index, min_itemsize, nan_rep, dropna, data_columns, errors, encoding)
    268             path_or_buf, mode=mode, complevel=complevel, complib=complib
    269         ) as store:
--> 270             f(store)
    271     else:
    272         f(path_or_buf)

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in <lambda>(store)
    260             data_columns=data_columns,
    261             errors=errors,
--> 262             encoding=encoding,
    263         )
    264

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in put(self, key, value, format, index, append, complib, complevel, min_itemsize, nan_rep, data_columns, encoding, errors, track_times)
   1127             encoding=encoding,
   1128             errors=errors,
-> 1129             track_times=track_times,
   1130         )
   1131

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in _write_to_group(self, key, value, format, axes, index, append, complib, complevel, fletcher32, min_itemsize, chunksize, expectedrows, dropna, nan_rep, data_columns, encoding, errors, track_times)
   1799             nan_rep=nan_rep,
   1800             data_columns=data_columns,
-> 1801             track_times=track_times,
   1802         )
   1803

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in write(self, obj, **kwargs)
   3189             # I have no idea why, but writing values before items fixed #2299
   3190             blk_items = data.items.take(blk.mgr_locs)
-> 3191             self.write_array(f"block{i}_values", blk.values, items=blk_items)
   3192             self.write_index(f"block{i}_items", blk_items)
   3193

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in write_array(self, key, value, items)
   3047
   3048             vlarr = self._handle.create_vlarray(self.group, key, _tables().ObjectAtom())
-> 3049             vlarr.append(value)
   3050
   3051         elif empty_array:

~/PQKs/pqks/lib/python3.6/site-packages/tables/vlarray.py in append(self, sequence)
    526             nparr = None
    527
--> 528         self._append(nparr, nobjects)
    529         self.nrows += 1
    530

~/PQKs/pqks/lib/python3.6/site-packages/tables/hdf5extension.pyx in tables.hdf5extension.VLArray._append()

OverflowError: value too large to convert to int

</code>```

答:
As noted in the similar issue https://stackoverflow.com/a/57133759/8896855, hdf/h5 files have more overhead and are intended to optimize many dataframes saved into a single file system.  Feather and parquet objects will likely provide a better solution in terms of saving/loading a larger single dataframe as an in-memory object.  In terms of the specific overflow error, this likely is the result of having larger mixed-type (as numpy array) columns stored in the "object" type in pandas.  One (more complicated) option would be to split out the arrays in your dataframe into separate columns, but that's probably unnecessary.

A general quick fix would be to use df.to_pickle(r'path_to/filename.pkl'), but to_feather or to_parquet likely present more optimized solutions.

Body:
I have a large pandas DataFrame with individual elements that are complex numpy arrays. Please see below a minimal code example to reproduce the scenario:

d = {f'x{i}': [] for i in range(4)}
df = pd.DataFrame(data=d).astype(object)

for K in range(4):
    for i in range(4):

        df.loc[f'{K}', f'x{i}'] = np.random.random(size=(2,2)) + np.random.random(size=(2,2)) * 1j

df

What is the best way to save these and load them up again for use later?

The problem I am having is that when I increase the size of the matrices stored and the number of elements, I get an OverflowError when I try to save it as .h5 file as shown below:

import pandas as pd

size = (300,300)
xs = 1500

d = {f'x{i}': [] for i in range(xs)}
df = pd.DataFrame(data=d).astype(object)

for K in range(10):
    for i in range(xs):

        df.loc[f'{K}', f'x{i}'] = np.random.random(size=size) + np.random.random(size=size) * 1j

df.to_hdf('test.h5', key="df", mode="w")

load_test = pd.read_hdf("test.h5", "df")

---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-124-8cb8df1a0653> in <module>
     12         df.loc[f'{K}', f'x{i}'] = np.random.random(size=size) + np.random.random(size=size) * 1j
     13
---> 14 df.to_hdf('test.h5', key="df", mode="w")
     15
     16

~/PQKs/pqks/lib/python3.6/site-packages/pandas/core/generic.py in to_hdf(self, path_or_buf, key, mode, complevel, complib, append, format, index, min_itemsize, nan_rep, dropna, data_columns, errors, encoding)
   2447             data_columns=data_columns,
   2448             errors=errors,
-> 2449             encoding=encoding,
   2450         )
   2451

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in to_hdf(path_or_buf, key, value, mode, complevel, complib, append, format, index, min_itemsize, nan_rep, dropna, data_columns, errors, encoding)
    268             path_or_buf, mode=mode, complevel=complevel, complib=complib
    269         ) as store:
--> 270             f(store)
    271     else:
    272         f(path_or_buf)

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in <lambda>(store)
    260             data_columns=data_columns,
    261             errors=errors,
--> 262             encoding=encoding,
    263         )
    264

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in put(self, key, value, format, index, append, complib, complevel, min_itemsize, nan_rep, data_columns, encoding, errors, track_times)
   1127             encoding=encoding,
   1128             errors=errors,
-> 1129             track_times=track_times,
   1130         )
   1131

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in _write_to_group(self, key, value, format, axes, index, append, complib, complevel, fletcher32, min_itemsize, chunksize, expectedrows, dropna, nan_rep, data_columns, encoding, errors, track_times)
   1799             nan_rep=nan_rep,
   1800             data_columns=data_columns,
-> 1801             track_times=track_times,
   1802         )
   1803

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in write(self, obj, **kwargs)
   3189             # I have no idea why, but writing values before items fixed #2299
   3190             blk_items = data.items.take(blk.mgr_locs)
-> 3191             self.write_array(f"block{i}_values", blk.values, items=blk_items)
   3192             self.write_index(f"block{i}_items", blk_items)
   3193

~/PQKs/pqks/lib/python3.6/site-packages/pandas/io/pytables.py in write_array(self, key, value, items)
   3047
   3048             vlarr = self._handle.create_vlarray(self.group, key, _tables().ObjectAtom())
-> 3049             vlarr.append(value)
   3050
   3051         elif empty_array:

~/PQKs/pqks/lib/python3.6/site-packages/tables/vlarray.py in append(self, sequence)
    526             nparr = None
    527
--> 528         self._append(nparr, nobjects)
    529         self.nrows += 1
    530

~/PQKs/pqks/lib/python3.6/site-packages/tables/hdf5extension.pyx in tables.hdf5extension.VLArray._append()

OverflowError: value too large to convert to int


答:
Your code as it stands will actually look through dataset for the entire list "['pop', 'ppp', 'cre']". Why don't you try something like this:

```<code>for item in id:
    if item in dataset:
        print id
</code>```

Edit:

This will probably be more efficient:

```<code>for item in dataset:
    if item in id:
        print id
</code>```

Assuming |dataset| > |id| and you break out of the loop when you find a match.

Title: Something from string in list python

Body:
Your code as it stands will actually look through dataset for the entire list "['pop', 'ppp', 'cre']". Why don't you try something like this:

for item in id:
    if item in dataset:
        print id

Edit:

This will probably be more efficient:

for item in dataset:
    if item in id:
        print id

Assuming |dataset| > |id| and you break out of the loop when you find a match.


问:
Convert .tex LaTeX file to a PDF
I am using Python 3.10.1 and the VSC Editor.
My code below creates a LaTeX file then converts it to a pdf.

The users.tex file successfully creates, but the pdf does not.

How can I resolve this issue?

```<code>import pandas as pd
import os
from pdflatex import PDFLaTeX

cols = ('Name', 'Username', 'Fav Color');
df = pd.DataFrame ((('Peter',  '1998_pete2', (139, 0, 139)),
                    ('Leon',  'Gar_man',    (143, 188, 143)),
                    ('Isla',  'Isla2021',   (173, 216, 230)),
                    ('Blake', 'kirbster',   (147, 112, 219))), columns=cols)

print(df)
df.to_latex('users.tex', index=False, caption='User Details', position='center')

pdf = os.system('pdflatex users.tex')
</code>```

答:
I believe that the df.to_latex() only produces the \begin{tabular} environment. If so, your .tex file is missing the preamble needed in a LaTeX document.
Thus the build of that document would fail.

You would have to insert the output into the \begin{document} part a properly formatted latex file.

Edit: I can confirm that the output is as follows:

\begin{table}[center]
\centering
\caption{User Details}
\begin{tabular}{lll}
\toprule
 Name &   Username &       Fav Color \\
\midrule
Peter & 1998\_pete2 &   (139, 0, 139) \\
 Leon &    Gar\_man & (143, 188, 143) \\
 Isla &   Isla2021 & (173, 216, 230) \\
Blake &   kirbster & (147, 112, 219) \\
\bottomrule
\end{tabular}
\end{table}
```
<p>This means you need the LaTeX boiler plate document wrapped around it like such:</p>
<pre class="lang-tex prettyprint-override"><code>\documentclass{article}
\usepackage{booktabs}
\begin{document}

\begin{table}
\centering
\caption{User Details}
\begin{tabular}{lll}
\toprule
 Name &   Username &       Fav Color \\
\midrule
Peter & 1998\_pete2 &   (139, 0, 139) \\
 Leon &    Gar\_man & (143, 188, 143) \\
 Isla &   Isla2021 & (173, 216, 230) \\
Blake &   kirbster & (147, 112, 219) \\
\bottomrule
\end{tabular}
\end{table}

\end{document}
</code>```

Edit 2: In order for the compilation to work you will also need to get rid of the position='center' argument, as mentioned by jjramsey.

Title: Convert .tex LaTeX file to a PDF

Body:
I am using Python 3.10.1 and the VSC Editor.
My code below creates a LaTeX file then converts it to a pdf.

The users.tex file successfully creates, but the pdf does not.

How can I resolve this issue?

import pandas as pd
import os
from pdflatex import PDFLaTeX

cols = ('Name', 'Username', 'Fav Color');
df = pd.DataFrame ((('Peter',  '1998_pete2', (139, 0, 139)),
                    ('Leon',  'Gar_man',    (143, 188, 143)),
                    ('Isla',  'Isla2021',   (173, 216, 230)),
                    ('Blake', 'kirbster',   (147, 112, 219))), columns=cols)

print(df)
df.to_latex('users.tex', index=False, caption='User Details', position='center')

pdf = os.system('pdflatex users.tex')

Body:
I believe that the df.to_latex() only produces the \begin{tabular} environment. If so, your .tex file is missing the preamble needed in a LaTeX document.
Thus the build of that document would fail.

You would have to insert the output into the \begin{document} part a properly formatted latex file.

Edit: I can confirm that the output is as follows:

\begin{table}[center]
\centering
\caption{User Details}
\begin{tabular}{lll}
\toprule
 Name &   Username &       Fav Color \\
\midrule
Peter & 1998\_pete2 &   (139, 0, 139) \\
 Leon &    Gar\_man & (143, 188, 143) \\
 Isla &   Isla2021 & (173, 216, 230) \\
Blake &   kirbster & (147, 112, 219) \\
\bottomrule
\end{tabular}
\end{table}

This means you need the LaTeX boiler plate document wrapped around it like such:

\documentclass{article}
\usepackage{booktabs}
\begin{document}

\begin{table}
\centering
\caption{User Details}
\begin{tabular}{lll}
\toprule
 Name &   Username &       Fav Color \\
\midrule
Peter & 1998\_pete2 &   (139, 0, 139) \\
 Leon &    Gar\_man & (143, 188, 143) \\
 Isla &   Isla2021 & (173, 216, 230) \\
Blake &   kirbster & (147, 112, 219) \\
\bottomrule
\end{tabular}
\end{table}

\end{document}

Edit 2: In order for the compilation to work you will also need to get rid of the position='center' argument, as mentioned by jjramsey.


问:
How can I remove this icon from text field? (Vuetifyjs, CSS)
I have this vuetifyjs text field and I want to remove the clock icon.

<v-text-field

 v-model="model.end_time"

 type="time">

</v-text-field>

I have already tried this code but it is not working

```<code>input[type="time"]::-webkit-calendar-picker-indicator {
  background: none;
  display:none;
}
</code>```

Can someone help me with this

答:
You need append css code globally. If you add css in

   <v-text-field
        value="12:30:00"
        type="time"
      ></v-text-field>

<script>
new Vue({
  el: "#app",
  data: {
   count: 1
  }
});

</script>```

Body:
I have this vuetifyjs text field and I want to remove the clock icon.

<v-text-field

 v-model="model.end_time"

 type="time">

</v-text-field>

I have already tried this code but it is not working

input[type="time"]::-webkit-calendar-picker-indicator {
  background: none;
  display:none;
}

Can someone help me with this

Body:
You need append css code globally. If you add css in <style scoped> it will be not working.

import { createApp } from 'vue'

Vue.use(Vuetify);

new Vue({
  el: "#app",
  components: { App },
  template: "<App/>"
});

createApp({
  data() {
    return {
      count: 0
    }
  }
}).mount('#app')

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
<style>
  input[type="time"]::-webkit-calendar-picker-indicator {
  background: none;
  display: none;
}
</style>
<div id="app">
<br>
<br>
   <v-text-field
        value="12:30:00"
        type="time"
      ></v-text-field>
</div>

<script>
new Vue({
  el: "#app",
  data: {
   count: 1
  }
});

</script>


问:
How to get the week start in this format '07-Feb-22' in SQL server
Hi there please help me .
I'm using this code

```<code>Weekstart = DATEDD(Wk, DATEDIFF(d,0,CONVERT(DATE, GETDATE(),103)) / 7,0)
</code>```

This above query is given me the output in this format '2022-02-07 00:00:00.000' however I want the date in this format '07-Feb-22'

答:
Some things to avoid:

Shorthand like Wk and d - this isn't code golf

Magic dates like 0 - again, not code golf

Style 103 doesn't belong here at all, that is when you are taking a string in a regional format (which you also should avoid), not when converting a datetime to a date

Lots more things to avoid here: Dating Responsibly

I would do it this way. Use a base date that you know falls on the same weekday that you consider the start of the week:

```<code>DECLARE @base date = '20180101';

SELECT Weekstart = REPLACE(CONVERT(char(9),
    DATEADD(WEEK, DATEDIFF(DAY, @base, GETDATE())/7, @base), 6),' ','-');
</code>```

The only magic / shorthand in here is the style number, 6, which is a very specific way to coerce a date/time into a specific format (discover them all here). Some will suggest the built-in FORMAT() function, which matches capability in other languages like C#, but I suggest avoiding it. Not only is it not available in flavors of SQL Server that don't support CLR or x64 (like Azure SQL Edge), the overhead is substantial.

Body:
Hi there please help me .
I'm using this code

Weekstart = DATEDD(Wk, DATEDIFF(d,0,CONVERT(DATE, GETDATE(),103)) / 7,0)

This above query is given me the output in this format '2022-02-07 00:00:00.000' however I want the date in this format '07-Feb-22'

Body:
Some things to avoid:

Shorthand like Wk and d - this isn't code golf

Magic dates like 0 - again, not code golf

Style 103 doesn't belong here at all, that is when you are taking a string in a regional format (which you also should avoid), not when converting a datetime to a date

Lots more things to avoid here: Dating Responsibly

I would do it this way. Use a base date that you know falls on the same weekday that you consider the start of the week:

DECLARE @base date = '20180101';

SELECT Weekstart = REPLACE(CONVERT(char(9),
    DATEADD(WEEK, DATEDIFF(DAY, @base, GETDATE())/7, @base), 6),' ','-');

The only magic / shorthand in here is the style number, 6, which is a very specific way to coerce a date/time into a specific format (discover them all here). Some will suggest the built-in FORMAT() function, which matches capability in other languages like C#, but I suggest avoiding it. Not only is it not available in flavors of SQL Server that don't support CLR or x64 (like Azure SQL Edge), the overhead is substantial.


问:
How can I change the hash sign in the url of a page to some other value?
WIth this code </p>

```<code>     <script type="text/javascript">
               window.location.hash="Aboutus";
  </script>
</code>```

<p>,I get url#Aboutus..
I want to change this sign to some other value ..How can I procees?</p>

答: You can't, the hash has special meaning in a url, it has to be a hash, not any other symbol.</p>

Body:
WIth this code

,I get url#Aboutus..
I want to change this sign to some other value ..How can I procees?