问:
can you capture multiple substrings in a Panda dataframe column using .str.split() in one step
I have a database with a column in a Pandas dataframe that contains a string that has two substrings (a string & a number) I extract.  I do it with str.split(), but not in a very pythonic manner because split, for me at least, returns the first item of the split to the database.  And I of course can assign the result to a separate dataframe complete the splits and bring it back.

I am sure there is a better way to do this, but as of yet I have not found it.

Here is an illustrative dataframe:

```<code>df = pd.DataFrame ({'d': {71: '2022-01-03', 72: '2022-01-04', 73: '2022-01-06', 74: '2022-01-07', 75: '2022-01-07'},
                    'e': {71: 'MDU(US5526901096) Cash Dividend USD 0.2175 per Share (Ordinary Dividend)',
                          72: 'KMB(US4943681035) Cash Dividend USD 1.14 per Share (Ordinary Dividend)',
                          73: 'IRM(US46284V1017) Cash Dividend USD 0.6185 per Share (Ordinary Dividend)',
                          74: 'MRK(US58933Y1055) Cash Dividend USD 0.69 per Share (Ordinary Dividend)',
                          75: 'PEP(US7134481081) Cash Dividend USD 1.075 per Share (Ordinary Dividend)'},
                    'f': {71: '108.75', 72: '1368', 73: '556.65', 74: '345', 75: '537.5'}})
df
</code>```

Basically from this dataframe I want to extract the stock symbol and the dividend amount without losing the other columns of 'd' and 'f'.

From the string in column 'e' I extract the symbol of the stock at the beginningof the string and then the current dividend from the middle.

df_to_process['e'] = df_to_process['e'].str.split('\(', expand=True) provides me with the stock symbol.

To get the dividend amount I copy column 'e' data in the dataframe to a column I create, for purposes here 'gg'. I then split it.  Since the dividend amount is in the middle of my split, the column I created gets the number I want.

```<code>df_to_process[['aa','gg','cc']]  = df_to_process['gg'].str.split('USD|per', expand=True)
or
y = df['gg'].str.split('USD|per', expand=True)

            0                   1                    2
71  MDU(US5526901096) Cash Dividend 0.2175  Share (Ordinary Dividend)
72  KMB(US4943681035) Cash Dividend 1.14    Share (Ordinary Dividend)
73  IRM(US46284V1017) Cash Dividend 0.6185  Share (Ordinary Dividend)
74  MRK(US58933Y1055) Cash Dividend 0.69    Share (Ordinary Dividend)
75  PEP(US7134481081) Cash Dividend 1.075   Share (Ordinary Dividend)
</code>```

I am not very familiar with Regex and am turning to that next.  But is there a way to make this work with split?

答:
This is not optimized in any way, and it makes a few assumptions, but I tried to highlight them below.

```<code>import pandas as pd
import re

def parse_row(row) :
  match = re.search('^([a-zA-Z]+).*USD (\d+\.?\d*) per', row, re.I)
  return pd.Series([match.group(1), match.group(2)])

df[['symbol', 'qrtrly_div_total']] = df['e'].apply( parse_row )

>>> df
             d                                                  e       f symbol qrtrly_div_total
71  2022-01-03  MDU(US5526901096) Cash Dividend USD 0.2175 per...  108.75    MDU           0.2175
72  2022-01-04  KMB(US4943681035) Cash Dividend USD 1.14 per S...    1368    KMB             1.14
73  2022-01-06  IRM(US46284V1017) Cash Dividend USD 0.6185 per...  556.65    IRM           0.6185
74  2022-01-07  MRK(US58933Y1055) Cash Dividend USD 0.69 per S...     345    MRK             0.69
75  2022-01-07  PEP(US7134481081) Cash Dividend USD 1.075 per ...   537.5    PEP            1.075
</code>```

As you mentioned, regex would allow you to capture both elements and assign them to new columns. python3 doc for regex

If column E is not consistent, you'll need to modify the regex, but here the elements in the one above.

'^([a-zA-Z]+).*USD (\d+\.?\d*) per'

^ indicates to start at the beginning

[a-zA-Z]+ will check for all letters at the beginning until a letter is not met (the assumption is the stock will be at least 1 letter in length, and the match will stop when meeting the (

.*USD  matches all content until we come to USD

\d+.?\d*  Should match a number, with or without the decimal, and if decimal is present, then all numbers after it

per at the end is to help isolate the number match between "USD xx.xx per"

If optimization is required, such as for large datasets, pd.apply is not the ideal function to use, and I would recommend looking into vectorization techniques.

Edit: If you wanted to name the matches, you could do this.

```<code>match = re.search('^(?P<symbol>[a-zA-Z]+).*USD (?P<value>\d+\.?\d*) per', row, re.I)
match.group('symbol')
match.group('value')
</code>```

The (?P<name>...) allows you to name the group.

Body:
I have a database with a column in a Pandas dataframe that contains a string that has two substrings (a string & a number) I extract.  I do it with str.split(), but not in a very pythonic manner because split, for me at least, returns the first item of the split to the database.  And I of course can assign the result to a separate dataframe complete the splits and bring it back.

I am sure there is a better way to do this, but as of yet I have not found it.

Here is an illustrative dataframe:

df = pd.DataFrame ({'d': {71: '2022-01-03', 72: '2022-01-04', 73: '2022-01-06', 74: '2022-01-07', 75: '2022-01-07'},
                    'e': {71: 'MDU(US5526901096) Cash Dividend USD 0.2175 per Share (Ordinary Dividend)',
                          72: 'KMB(US4943681035) Cash Dividend USD 1.14 per Share (Ordinary Dividend)',
                          73: 'IRM(US46284V1017) Cash Dividend USD 0.6185 per Share (Ordinary Dividend)',
                          74: 'MRK(US58933Y1055) Cash Dividend USD 0.69 per Share (Ordinary Dividend)',
                          75: 'PEP(US7134481081) Cash Dividend USD 1.075 per Share (Ordinary Dividend)'},
                    'f': {71: '108.75', 72: '1368', 73: '556.65', 74: '345', 75: '537.5'}})
df

Basically from this dataframe I want to extract the stock symbol and the dividend amount without losing the other columns of 'd' and 'f'.

From the string in column 'e' I extract the symbol of the stock at the beginningof the string and then the current dividend from the middle.

df_to_process['e'] = df_to_process['e'].str.split('\(', expand=True) provides me with the stock symbol.

To get the dividend amount I copy column 'e' data in the dataframe to a column I create, for purposes here 'gg'. I then split it.  Since the dividend amount is in the middle of my split, the column I created gets the number I want.

df_to_process[['aa','gg','cc']]  = df_to_process['gg'].str.split('USD|per', expand=True)
or
y = df['gg'].str.split('USD|per', expand=True)

            0                   1                    2
71  MDU(US5526901096) Cash Dividend 0.2175  Share (Ordinary Dividend)
72  KMB(US4943681035) Cash Dividend 1.14    Share (Ordinary Dividend)
73  IRM(US46284V1017) Cash Dividend 0.6185  Share (Ordinary Dividend)
74  MRK(US58933Y1055) Cash Dividend 0.69    Share (Ordinary Dividend)
75  PEP(US7134481081) Cash Dividend 1.075   Share (Ordinary Dividend)

I am not very familiar with Regex and am turning to that next.  But is there a way to make this work with split?

Body:
This is not optimized in any way, and it makes a few assumptions, but I tried to highlight them below.

import pandas as pd
import re

def parse_row(row) :
  match = re.search('^([a-zA-Z]+).*USD (\d+\.?\d*) per', row, re.I)
  return pd.Series([match.group(1), match.group(2)])

df[['symbol', 'qrtrly_div_total']] = df['e'].apply( parse_row )

>>> df
             d                                                  e       f symbol qrtrly_div_total
71  2022-01-03  MDU(US5526901096) Cash Dividend USD 0.2175 per...  108.75    MDU           0.2175
72  2022-01-04  KMB(US4943681035) Cash Dividend USD 1.14 per S...    1368    KMB             1.14
73  2022-01-06  IRM(US46284V1017) Cash Dividend USD 0.6185 per...  556.65    IRM           0.6185
74  2022-01-07  MRK(US58933Y1055) Cash Dividend USD 0.69 per S...     345    MRK             0.69
75  2022-01-07  PEP(US7134481081) Cash Dividend USD 1.075 per ...   537.5    PEP            1.075

As you mentioned, regex would allow you to capture both elements and assign them to new columns. python3 doc for regex

If column E is not consistent, you'll need to modify the regex, but here the elements in the one above.

'^([a-zA-Z]+).*USD (\d+\.?\d*) per'

^ indicates to start at the beginning

[a-zA-Z]+ will check for all letters at the beginning until a letter is not met (the assumption is the stock will be at least 1 letter in length, and the match will stop when meeting the (

.*USD  matches all content until we come to USD

\d+.?\d*  Should match a number, with or without the decimal, and if decimal is present, then all numbers after it

per at the end is to help isolate the number match between "USD xx.xx per"

If optimization is required, such as for large datasets, pd.apply is not the ideal function to use, and I would recommend looking into vectorization techniques.

Edit: If you wanted to name the matches, you could do this.

match = re.search('^(?P<symbol>[a-zA-Z]+).*USD (?P<value>\d+\.?\d*) per', row, re.I)
match.group('symbol')
match.group('value')

The (?P<name>...) allows you to name the group.


来源: stackexchange

问:
How do I find where a symbol is defined in lots of static library file on windows10?
I am trying to complie a project. The linker throw me an error that the external symbols is unsolved.

I understand that I should tell the linker where the .lib file is to deal with this problem. But how can I find what exactly the .lib file is to link with my code, from quite a lot of .lib files.

I search for solution but all assume compiling on Linux OS, though I actually compile my code on windows10 with visual studio 2019....T _ T.....

Maybe I can seaerch for the .lib file by the decorated symbol

__imp_?GetOutputPort@vtkAlgorithm@@QEAAPEAVvtkAlgorithmOutput@@XZ

but I don't know how to do....

答:
Use the dumpbin command of VS to view the dll dependencies of the target program. The usage method is as follows:

Start -> All apps -> Microsoft Visual Studio 20XX -> Developer Command Prompt for VS 20XX, where XX represents your VS version, I am using VS2022.

Enter: >dumpbin /dependents FilePath:\xxx.exe

Here is my example for your reference.(I hide my file paths and dynamic libraries.)

ContentLicense: CC BY-SA 4.0


问:
How to convert list of list to list of objects in python?
I am using python 3.7. I have an array of arrays:

```<code>[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
</code>```

How can I make it become an array of objects?

```<code>[
{
name:1,
surname:2,
price:3,
location:4
},
{
name:5,
surname:6,
price:7,
location:8
},
{
name:9,
surname:10,
price:11,
location:12
}
]
</code>```

I tried to use

```<code>array=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
json_str = json.dumps(array)
</code>```

but it does not work.

答:
input

```<code>a = ["AB", "corona"]
b = ["india",'openVINO']
c = ["korea"]
d = ["26", "10.mp3", "Nvidia.mp4"]
e = ["washington DC",6]
f = ['swiss']

import itertools

lst = [a,b,c,d,e,f]
# print(lst)
lsts = list(itertools.product(*lst))
for lst in lsts:
  print('\n')
  for con in lst:
    print(con)
</code>```

output

```<code>AB
india
korea
26
washington DC
swiss

AB
india
korea
26
6
swiss

AB
india
korea
10.mp3
washington DC
swiss

AB
india
korea
10.mp3
6
swiss

AB
india
korea
Nvidia.mp4
washington DC
swiss

AB
india
korea
Nvidia.mp4
6
swiss

AB
openVINO
korea
26
washington DC
swiss

AB
openVINO
korea
26
6
swiss

AB
openVINO
korea
10.mp3
washington DC
swiss

AB
openVINO
korea
10.mp3
6
swiss

AB
openVINO
korea
Nvidia.mp4
washington DC
swiss

AB
openVINO
korea
Nvidia.mp4
6
swiss

corona
india
korea
26
washington DC
swiss

corona
india
korea
26
6
swiss

corona
india
korea
10.mp3
washington DC
swiss

corona
india
korea
10.mp3
6
swiss

corona
india
korea
Nvidia.mp4
washington DC
swiss

corona
india
korea
Nvidia.mp4
6
swiss

corona
openVINO
korea
26
washington DC
swiss

corona
openVINO
korea
26
6
swiss

corona
openVINO
korea
10.mp3
washington DC
swiss

corona
openVINO
korea
10.mp3
6
swiss

corona
openVINO
korea
Nvidia.mp4
washington DC
swiss

corona
openVINO
korea
Nvidia.mp4
6
swiss
</code>```

Body:
I am using python 3.7. I have an array of arrays:

[[1,2,3,4],[5,6,7,8],[9,10,11,12]]

How can I make it become an array of objects?

[
{
name:1,
surname:2,
price:3,
location:4
},
{
name:5,
surname:6,
price:7,
location:8
},
{
name:9,
surname:10,
price:11,
location:12
}
]

I tried to use

array=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
json_str = json.dumps(array)

but it does not work.

Body:
input

a = ["AB", "corona"]
b = ["india",'openVINO']
c = ["korea"]
d = ["26", "10.mp3", "Nvidia.mp4"]
e = ["washington DC",6]
f = ['swiss']

import itertools

lst = [a,b,c,d,e,f]
# print(lst)
lsts = list(itertools.product(*lst))
for lst in lsts:
  print('\n')
  for con in lst:
    print(con)

output

AB
india
korea
26
washington DC
swiss

AB
india
korea
26
6
swiss

AB
india
korea
10.mp3
washington DC
swiss

AB
india
korea
10.mp3
6
swiss

AB
india
korea
Nvidia.mp4
washington DC
swiss

AB
india
korea
Nvidia.mp4
6
swiss

AB
openVINO
korea
26
washington DC
swiss

AB
openVINO
korea
26
6
swiss

AB
openVINO
korea
10.mp3
washington DC
swiss

AB
openVINO
korea
10.mp3
6
swiss

AB
openVINO
korea
Nvidia.mp4
washington DC
swiss

AB
openVINO
korea
Nvidia.mp4
6
swiss

corona
india
korea
26
washington DC
swiss

corona
india
korea
26
6
swiss

corona
india
korea
10.mp3
washington DC
swiss

corona
india
korea
10.mp3
6
swiss

corona
india
korea
Nvidia.mp4
washington DC
swiss

corona
india
korea
Nvidia.mp4
6
swiss

corona
openVINO
korea
26
washington DC
swiss

corona
openVINO
korea
26
6
swiss

corona
openVINO
korea
10.mp3
washington DC
swiss

corona
openVINO
korea
10.mp3
6
swiss

corona
openVINO
korea
Nvidia.mp4
washington DC
swiss

corona
openVINO
korea
Nvidia.mp4
6
swiss


问:
Push notifications not working after transferring data from old iPhone to new
I transferred data from iPhone 8 to iPhone 12 mini, using the iTunes Backup / Device to device migration. I wasn't getting push notifications for one app that I had already installed on my old iPhone. I checked the push notification settings for that app, and everything is enabled as before. I toggled the settings to on/off but it did not help. I tried to log out and log back in to that app, but that also did not fix the issue. Then I deleted and reinstalled the app, and then at the time of login, the app asked me whether I want to allow push notifications. I clicked Allow, and now notifications for that app have started working. Is it common behaviour? If not how to handle this?

Note: We are using Braze third party service in order to send notifications to users

答:
Here's what to do:

1). On your current iPhone, tap Settings to open it.

2). Tap your name.

3). Tap iCloud.

4). Move the Messages slider to on/green.

5). On the new phone that you want to transfer the messages to, log into the same iCloud account and follow the same steps to enable Messages in iCloud.


问:
Delete a huge number of tables in one DROP TABLE Postgres
Does Postgres have any limits for a number of tables to be deleted in one DROP TABLE command (about 10000 in my case)? Does it depend on the version? Will it be faster than executing the command 10 times & 1000 tables?

The possibilities for testing this are limited in my case, so please share if you've had a similar experience.

答:
Use This For All Table Of Database.</p>
```<code>DO $$
  DECLARE
    r RECORD;
BEGIN
  FOR r IN
    (
      SELECT table_name
      FROM information_schema.tables
      WHERE table_schema=current_schema()
    )
  LOOP
     EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.table_name) || ' CASCADE';
  END LOOP;
END $$ ;

</code>```

Body:
Use This For All Table Of Database.

DO $$
  DECLARE
    r RECORD;
BEGIN
  FOR r IN
    (
      SELECT table_name
      FROM information_schema.tables
      WHERE table_schema=current_schema()
    )
  LOOP
     EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.table_name) || ' CASCADE';
  END LOOP;
END $$ ;


问:
Access the routerlink data
I have a routerlink in an anchor tag, and I want to access the value passed. How can I do it?

As you can see in the above screenshot, "bob" is the data is being passed to the component when this anchor tag is clicked, so how can I access this value in the component when it loads? Please note that it is a child component of another component therefore route is not used.

答:
Route should work anyway like this:

constructor(private route: ActivatedRoute){}

ngOnInit() {
 const debug = this.route.snapshot.paramMap.get('debug');
}
```

Title: Access the routerlink data


问:
How do I share user controls between web applications in ASP.NET?
This question is a follow up to my question about sharing resources between web applications, because I have not yet found a good solution.

I have a web application with user controls and resources that are shared by three other web applications.

```
Solution
|
+-CommonControlsWebApp
| +- resources
| |  +- images
| |  +- scripts
| |  +- stylesheets
| +- UserControls
|
+-WebApp1
|
+-WebApp2
|
+-WebApp3
```

This is what I know this far:

I can not compile CommonControlsWebApp into a single dll since I am creating user controls. This is only possible with custom server controls, where everything is in the code-behind file. So I need a way to share the ascx files between the four projects.

Copying the files from CommonControlsWebApp into the three other projects does not update their files in the solution explorer. I would have to 'add exting items' all in all three WebApps when a file is added or renamed in CommonControls.

Changing to the Web Site model would remedy this, but I am worried about the compile time for WebApp1-3 if I do this.

'Add as link' does not work for directories.

I could use Subversion to share the files between the projects, but i believe that this would require me to check the files in and out again all the time if I am developing a user control that I have to test through one of the WebApps.

Can it really be true that ASP.NET does not have a good solution for this? How are you guys organizing large web applications?

Edit: Thanks a lot for all the answers. I am going to copy my user controls with a build event for now, and then see if we have time to refactor them into server controls.

答:
The way we do it at my present company is to make sure CommonControlsWebApp
 is a WebApplication, not a web site. Then you use names for the folders that would help identify it as the common ones that are distinct from the individual web apps. (CommonUserControls instead of just UserControls)

In your other web apps, you create a virtual directory to the CommonUserControls, etc, and add a file based reference to the CommonControlsWebApp.dll

This requires you to use IIS for development (not casini), and Visual Studio won't believe that the controls really exist, but it will work at runtime, and you can build just fine with only warnings about blahblah.ascx or blahblah.master path invalid.

If you do use common master pages and Visual Studio 2008, you will need SP1 for 2008 and use a __fallback.master in the root of the individual web projects to go in to design mode.

However, I saw this on another thread, and I am going to look into doing more like this:
http://webproject.scottgu.com/CSharp/UserControls/UserControls.aspx

OwnerDisplayName: Jan Aagaard

ContentLicense: CC BY-SA 2.5

Body:
This question is a follow up to my question about sharing resources between web applications, because I have not yet found a good solution.

I have a web application with user controls and resources that are shared by three other web applications.

Solution
|
+-CommonControlsWebApp
| +- resources
| |  +- images
| |  +- scripts
| |  +- stylesheets
| +- UserControls
|
+-WebApp1
|
+-WebApp2
|
+-WebApp3

This is what I know this far:

I can not compile CommonControlsWebApp into a single dll since I am creating user controls. This is only possible with custom server controls, where everything is in the code-behind file. So I need a way to share the ascx files between the four projects.

Copying the files from CommonControlsWebApp into the three other projects does not update their files in the solution explorer. I would have to 'add exting items' all in all three WebApps when a file is added or renamed in CommonControls.

Changing to the Web Site model would remedy this, but I am worried about the compile time for WebApp1-3 if I do this.

'Add as link' does not work for directories.

I could use Subversion to share the files between the projects, but i believe that this would require me to check the files in and out again all the time if I am developing a user control that I have to test through one of the WebApps.

Can it really be true that ASP.NET does not have a good solution for this? How are you guys organizing large web applications?

Edit: Thanks a lot for all the answers. I am going to copy my user controls with a build event for now, and then see if we have time to refactor them into server controls.

LastEditorDisplayName: Jan Aagaard

OwnerDisplayName: wulimaster


问:
Open image to full screen, if tapped - flutter_html
If I am having an image in my HTML, I am not able to open that image to full screen, if tapped.

Below is the built in function available in flutter_html if image is tapped.

```<code>onImageTap: (url, context, attributes, element) => {
// code here
}
</code>```

Is there any way we can achieve this?

I have tried below solution but it didn't worked

```<code>onImageTap: (url, context, attributes, element) => {
 Scaffold(
      body: GestureDetector(
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Hero(
            tag: 'imageHero',
            child: Image.network(image),
          ),
        ),
        onTap: () {
          Navigator.pop(context);
        },
      ),
    )
}
</code>```

答:
It seems to need Navigator.push() or showDialog.

onImageTap is not rebuild your screen.

Body:
If I am having an image in my HTML, I am not able to open that image to full screen, if tapped.

Below is the built in function available in flutter_html if image is tapped.

onImageTap: (url, context, attributes, element) => {
// code here
}

Is there any way we can achieve this?

I have tried below solution but it didn't worked

onImageTap: (url, context, attributes, element) => {
 Scaffold(
      body: GestureDetector(
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Hero(
            tag: 'imageHero',
            child: Image.network(image),
          ),
        ),
        onTap: () {
          Navigator.pop(context);
        },
      ),
    )
}


问:
Reading doc and docx files using C# without having MS Office installed on server
I'm working on a project (asp.net, c#, vb 2010, .net 4) and I need to read both DOC and DOCX files, that I've previosly uploaded (I've done uploading part). Tricky part is that I don't have MS Office installed on server and that I can't use it.

Is there any public library that I can include into my project without having to install anything?
Both docs are very simple:

```<code>NUMBER TAB STRING
NUMBER TAB STRING
NUMBER TAB STRING
...
</code>```

I need to extract number and string for each row (paragraph).

May someone help with this? I should repeat once again that I'm limited in a way that I can't install anything on a server.

答:
You can do like this:</p>
```<code>using System.IO;
using System.Text;
using Spire.Doc;

namespace ReadTextLineByLine{
    class Program {
        static void Main(string[] args) {
            //Create a Document object
            Document doc = new Document();
            //Load a Word file
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\data.docx");
            //Convert the text in Word line by line into a txt file
            doc.SaveToTxt("result.text", Encoding.UTF8);
            //Read all lines of txt file
            string[] lines = File.ReadAllLines("result.text", System.Text.Encoding.Default);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a project (asp.net, c#, vb 2010, .net 4) and I need to read both DOC and DOCX files, that I've previosly uploaded (I've done uploading part). Tricky part is that I don't have MS Office installed on server and that I can't use it.

Is there any public library that I can include into my project without having to install anything?
Both docs are very simple:

NUMBER TAB STRING
NUMBER TAB STRING
NUMBER TAB STRING
...

I need to extract number and string for each row (paragraph).

May someone help with this? I should repeat once again that I'm limited in a way that I can't install anything on a server.

Body:
You can do like this:

using System.IO;
using System.Text;
using Spire.Doc;

namespace ReadTextLineByLine{
    class Program {
        static void Main(string[] args) {
            //Create a Document object
            Document doc = new Document();
            //Load a Word file
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\data.docx");
            //Convert the text in Word line by line into a txt file
            doc.SaveToTxt("result.text", Encoding.UTF8);
            //Read all lines of txt file
            string[] lines = File.ReadAllLines("result.text", System.Text.Encoding.Default);
        }
    }
}


问:
composer git repository checkout as git-repo and not as a copy
I've a composer based TYPO3 installation, which contains a private gitlab-repository. The private git-repository should be used as dev-master (as a real repository) so that I'm able to develope inside. But composer checks out only the master repository files, but without the .git folder.

Any clue what's wrong? In some other projects this works like expected.

My composer.json:

{
    "name": "my-vendor/my-project",
    "description" : "TYPO3 CMS Website",
    "license": "GPL-2.0-or-later",
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "platform-check": false,
        "allow-plugins": {
            "typo3/class-alias-loader": true,
            "typo3/cms-composer-installers": true,
            "captainhook/plugin-composer": true
        }
    },
    "repositories": [
        { "type": "composer", "url": "https://composer.typo3.org/" },
        { "type": "path", "url": "./packages/*" },
        { "type": "vcs", "url": "git@gitlab.com:myvendor/typo3-amp.git" }
    ],
    "require": {
        "typo3/cms-about": "^11.0",
        "typo3/cms-backend": "^11.0",
        "typo3/cms-belog": "^11.0",
        "typo3/cms-beuser": "^11.0",
        "typo3/cms-core": "^11.0",
        "typo3/cms-dashboard": "^11.0",
        "typo3/cms-extbase": "^11.0",
        "typo3/cms-extensionmanager": "^11.0",
        "typo3/cms-felogin": "^11.0",
        "typo3/cms-filelist": "^11.0",
        "typo3/cms-fluid": "^11.0",
        "typo3/cms-fluid-styled-content": "^11.0",
        "typo3/cms-form": "^11.0",
        "typo3/cms-frontend": "^11.0",
        "typo3/cms-info": "^11.0",
        "typo3/cms-install": "^11.0",
        "typo3/cms-lowlevel": "^11.0",
        "typo3/cms-opendocs": "^11.0",
        "typo3/cms-recordlist": "^11.0",
        "typo3/cms-recycler": "^11.0",
        "typo3/cms-redirects": "^11.0",
        "typo3/cms-reports": "^11.0",
        "typo3/cms-rte-ckeditor": "^11.0",
        "typo3/cms-scheduler": "^11.0",
        "typo3/cms-seo": "^11.0",
        "typo3/cms-setup": "^11.0",
        "typo3/cms-sys-note": "^11.0",
        "typo3/cms-t3editor": "^11.0",
        "typo3/cms-tstemplate": "^11.0",
        "typo3/cms-viewpage": "^11.0",
        "helhum/typo3-console": "~7.0",
        "my-vendor/sitepackage": "@dev",
        "my-vendor/amp": "dev-master as 2.0.0",
        "ext-simplexml": "*",
        "ext-pdo": "*",
        "ext-zip": "*",
        "ext-libxml": "*",
        "ext-curl": "*",
        "ext-gd": "*",
        "ext-json": "*"
    },
    "require-dev": {
        "phpstan/phpstan": "^0.12.98",
        "saschaegerer/phpstan-typo3": "^0.13.3",
        "friendsofphp/php-cs-fixer": "^3.0",
        "captainhook/captainhook": "^5.10",
        "captainhook/plugin-composer": "^5.3",
        "rector/rector": "0.11.53"
    },
    "extra": {
        "captainhook": {
            "force-install": true
        }
    },
    "scripts": {
        "php-cs-fixer": "vendor/bin/php-cs-fixer fix packages",
        "phpstan": "vendor/bin/phpstan analyse",
        "rector": "vendor/bin/rector process packages",
        "ci": [
            "@php-cs-fixer",
            "@phpstan",
            "@rector"
        ]
    }
}
```

答:
Can you try the following:

Add this to your composer.json

"preferred-install": {
   "my-vendor/amp": "source"
}
```

then remove the package by using rm typo3conf/ext/amp and then do a composer install

Body:
Can you try the following:

Add this to your composer.json

"preferred-install": {
   "my-vendor/amp": "source"
}

then remove the package by using rm typo3conf/ext/amp and then do a composer install


问:
Scss classnames with special symbols like "[]"
This is a strange question. I request link type from server which might return "[TCP]" or "[UDP]". And I wanna use the string as classname directly for different background color like. What I want is :

```<code><div className={`${styles.span} ${styles["[TCP]"]}`}/>
</code>```

But the css selector ".[TCP]" is not allowed, below error given:

```<code>SassError: Invalid CSS after "&": expected selector, was ".[TCP]"
</code>```

Now I am using .replace(/\[|\]/g,"") split the string "[TCP]" --> "TCP". But I hope someone can tell me another way or it's impossible.

答:
"You can use [TCP] as classname."

As written here (demo) you can use any character for classname except NULL. All you have to do is in CSS write \ before special characters. In your case, it would look like this .\[TCP\].

But I believe it's much easier to just remove the special characters.

Body:
This is a strange question. I request link type from server which might return "[TCP]" or "[UDP]". And I wanna use the string as classname directly for different background color like. What I want is :

<div className={`${styles.span} ${styles["[TCP]"]}`}/>

But the css selector ".[TCP]" is not allowed, below error given:

SassError: Invalid CSS after "&": expected selector, was ".[TCP]"

Now I am using .replace(/\[|\]/g,"") split the string "[TCP]" --> "TCP". But I hope someone can tell me another way or it's impossible.


问:
How to check the number of points <=10 in Cypress
```<code>cy.get('div[id="base-table-\[object\ Object\]-body"] > .MuiGrid-root, .jss505').should('have.length', 10)
</code>```

How to make a check  <=10 ? Maybe to.have.length.most()
DOM

```<code><div id="base-table-[object Object]-body">
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
</div>
</code>```

答:
You can use the following callback assertion

cy.get('div[id="base-table-[object Object]-body"] > .MuiGrid-root, .jss505')
  .should($els => expect($els.length).to.be.lte(10))
```

Using .should() instead of .then() gives you command retry in async situations.

Body:
cy.get('div[id="base-table-\[object\ Object\]-body"] > .MuiGrid-root, .jss505').should('have.length', 10)

How to make a check  <=10 ? Maybe to.have.length.most()
DOM

Body:
You can use the following callback assertion

cy.get('div[id="base-table-[object Object]-body"] > .MuiGrid-root, .jss505')
  .should($els => expect($els.length).to.be.lte(10))

Using .should() instead of .then() gives you command retry in async situations.


问:
How to instruct Eclipse to record relative paths of the external jars?
Here is my .classpath file, after I have added two more external jars (org.restlet.ext.simple.jar and org.simpleframework.jar):

```<code><?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.restlet.ext.jackson.jar" sourcepath="C:/Program Files/Java/restlet-jse-2.0.10/src">
        <attributes>
            <attribute name="javadoc_location" value="file:/C:/Program Files/Java/restlet-jse-2.0.10/docs/ext/"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.restlet.ext.ssl.jar" sourcepath="C:/Program Files/Java/restlet-jse-2.0.10/src">
        <attributes>
            <attribute name="javadoc_location" value="file:/C:/Program Files/Java/restlet-jse-2.0.10/docs/ext/"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.restlet.jar" sourcepath="C:/Program Files/Java/restlet-jse-2.0.10/src">
        <attributes>
            <attribute name="javadoc_location" value="file:/C:/Program Files/Java/restlet-jse-2.0.10/docs/api"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.jsslutils_1.0/org.jsslutils.jar"/>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.codehaus.jackson_1.4/org.codehaus.jackson.core.jar"/>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.codehaus.jackson_1.4/org.codehaus.jackson.mapper.jar"/>
    <classpathentry kind="lib" path="../3rd_party/guice-3.0/aopalliance.jar"/>
    <classpathentry kind="lib" path="../3rd_party/guice-3.0/guice-3.0.jar"/>
    <classpathentry kind="lib" path="../3rd_party/guice-3.0/javax.inject.jar"/>
    <classpathentry kind="lib" path="C:/dev/poc/3rd_party/restlet-jse-2.0.10/lib/org.restlet.ext.simple.jar" sourcepath="C:/Program Files/Java/restlet-jse-2.0.10/src">
        <attributes>
            <attribute name="javadoc_location" value="file:/C:/Program Files/Java/restlet-jse-2.0.10/docs/ext/"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="lib" path="C:/dev/poc/3rd_party/restlet-jse-2.0.10/lib/org.simpleframework_4.1/org.simpleframework.jar"/>
    <classpathentry kind="output" path="bin"/>
</classpath>
</code>```

Notice that they have been added with absolute paths, unlike other entries which are with relative ones, but only because I manually edit this file each time new external jars are added.

My question is can I somehow tell Eclipse to use relative paths of newly added external jars?

Thanks.

答:
Please note that Eclipse relative paths should begin with a single dot.

Instead of

```<code><classpathentry kind="lib" path="../3rd_party/example.jar"/>
</code>```

You need to use

```<code><classpathentry kind="lib" path="./../3rd_party/example.jar"/>
</code>```

The first method might sometimes work, but the second method works always.

This is very confusing because you might have 5 entries in classpath that work with the ".." at the beginning and the others won't work with it.

Change all references to begin with the single dot first.

Body:
Here is my .classpath file, after I have added two more external jars (org.restlet.ext.simple.jar and org.simpleframework.jar):

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.restlet.ext.jackson.jar" sourcepath="C:/Program Files/Java/restlet-jse-2.0.10/src">
        <attributes>
            <attribute name="javadoc_location" value="file:/C:/Program Files/Java/restlet-jse-2.0.10/docs/ext/"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.restlet.ext.ssl.jar" sourcepath="C:/Program Files/Java/restlet-jse-2.0.10/src">
        <attributes>
            <attribute name="javadoc_location" value="file:/C:/Program Files/Java/restlet-jse-2.0.10/docs/ext/"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.restlet.jar" sourcepath="C:/Program Files/Java/restlet-jse-2.0.10/src">
        <attributes>
            <attribute name="javadoc_location" value="file:/C:/Program Files/Java/restlet-jse-2.0.10/docs/api"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.jsslutils_1.0/org.jsslutils.jar"/>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.codehaus.jackson_1.4/org.codehaus.jackson.core.jar"/>
    <classpathentry kind="lib" path="../3rd_party/restlet-jse-2.0.10/lib/org.codehaus.jackson_1.4/org.codehaus.jackson.mapper.jar"/>
    <classpathentry kind="lib" path="../3rd_party/guice-3.0/aopalliance.jar"/>
    <classpathentry kind="lib" path="../3rd_party/guice-3.0/guice-3.0.jar"/>
    <classpathentry kind="lib" path="../3rd_party/guice-3.0/javax.inject.jar"/>
    <classpathentry kind="lib" path="C:/dev/poc/3rd_party/restlet-jse-2.0.10/lib/org.restlet.ext.simple.jar" sourcepath="C:/Program Files/Java/restlet-jse-2.0.10/src">
        <attributes>
            <attribute name="javadoc_location" value="file:/C:/Program Files/Java/restlet-jse-2.0.10/docs/ext/"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="lib" path="C:/dev/poc/3rd_party/restlet-jse-2.0.10/lib/org.simpleframework_4.1/org.simpleframework.jar"/>
    <classpathentry kind="output" path="bin"/>
</classpath>

Notice that they have been added with absolute paths, unlike other entries which are with relative ones, but only because I manually edit this file each time new external jars are added.

My question is can I somehow tell Eclipse to use relative paths of newly added external jars?

Thanks.

Body:
Please note that Eclipse relative paths should begin with a single dot.

Instead of

<classpathentry kind="lib" path="../3rd_party/example.jar"/>

You need to use

<classpathentry kind="lib" path="./../3rd_party/example.jar"/>

The first method might sometimes work, but the second method works always.

This is very confusing because you might have 5 entries in classpath that work with the ".." at the beginning and the others won't work with it.

Change all references to begin with the single dot first.


问:
Permission denied when getting comments from my page via FB Graph API
Just recently, my attempts to get comments of my post via API fails with Permission denied. I'm pretty sure that it worked before (early Aug 2021).

I'm able to get posts of my page (in both API and Graph Explorer) via /ID/posts but I'm not able to get user generated content via /ID_POST/comments. I got

```<code>{
  "error": {
    "message": "(#200) Missing Permissions",
    "type": "OAuthException",
    "code": 200,
    "fbtrace_id": "AQuGaEEWWkJ_L380WhfeDPy"
  }
}
</code>```

but I have page token with pages_read_engagement, pages_show_list, pages_read_user_content (what should be enough by itself). The application is in production mode and business account is verified. So additional approval of permissions should be not be required.

What am I doing wrong?

答:
You can try these permissions that I use to get all comments on my page..

pages_read_engagement

pages_manage_metadata

pages_read_user_content

pages_manage_posts

pages_manage_engagement

public_profile

Also make sure the application type is in Business.
Trust me, you can get all comments and posts from someone on your page, except their profile name.

check this:
graph result

Body:
Just recently, my attempts to get comments of my post via API fails with Permission denied. I'm pretty sure that it worked before (early Aug 2021).

I'm able to get posts of my page (in both API and Graph Explorer) via /ID/posts but I'm not able to get user generated content via /ID_POST/comments. I got

{
  "error": {
    "message": "(#200) Missing Permissions",
    "type": "OAuthException",
    "code": 200,
    "fbtrace_id": "AQuGaEEWWkJ_L380WhfeDPy"
  }
}

but I have page token with pages_read_engagement, pages_show_list, pages_read_user_content (what should be enough by itself). The application is in production mode and business account is verified. So additional approval of permissions should be not be required.

What am I doing wrong?


问:
Why is a dash displayed as a dash on Android, but displayed as an underscore on iOS in my Flutter mobile app?
My flutter app displays a - (dash) between two times.

5:30pm - 11:00pm

On Android, this displays correctly, but on iOS the dash displays as an underscore.

5:30pm _ 11:00pm

Can anyone tell me why this is and how to correct it?

```<code>children: <Widget>[
  Row(
    children: <Widget>[
      Expanded(
        flex: 51,
        child: Text(
          data[i].jobName!,
          style: TextStyle(color: kBodyText, fontSize: 16),
        ),
      ),
      Expanded(
        flex: 23,
        child: Text(
          formatJsonTime24To12(data[i].startTime!)!
              .toLowerCase(),
          style: TextStyle(color: kBodyText, fontSize: 16),
          textAlign: TextAlign.right,
        ),
      ),
      Expanded(
        flex: 3,
        child: Text(
          ' -',
          style: TextStyle(color: kBodyText, fontSize: 16),
          textAlign: TextAlign.center,
        ),
      ),
      Expanded(
        flex: 23,
        child: Text(
          formatJsonTime24To12(data[i].finishTime!)!
              .toLowerCase(),
          style: TextStyle(color: kBodyText, fontSize: 16),
          textAlign: TextAlign.right,
        ),
      ),
    ],
  ),
</code>```

答: Thanks for the ideas. Turns out it was the flex values I was using. The flex value of 3 was enough on the android emulator I was using. But on the iOS simulator (iPhone 12 Pro Max), this wasn't enough and the text was word wrapping and creating a second line. The dash was on the second line. I increased the 3 to 5 and problem solved.</p>

Body:
My flutter app displays a - (dash) between two times.

5:30pm - 11:00pm

On Android, this displays correctly, but on iOS the dash displays as an underscore.

5:30pm _ 11:00pm

Can anyone tell me why this is and how to correct it?

children: <Widget>[
  Row(
    children: <Widget>[
      Expanded(
        flex: 51,
        child: Text(
          data[i].jobName!,
          style: TextStyle(color: kBodyText, fontSize: 16),
        ),
      ),
      Expanded(
        flex: 23,
        child: Text(
          formatJsonTime24To12(data[i].startTime!)!
              .toLowerCase(),
          style: TextStyle(color: kBodyText, fontSize: 16),
          textAlign: TextAlign.right,
        ),
      ),
      Expanded(
        flex: 3,
        child: Text(
          ' -',
          style: TextStyle(color: kBodyText, fontSize: 16),
          textAlign: TextAlign.center,
        ),
      ),
      Expanded(
        flex: 23,
        child: Text(
          formatJsonTime24To12(data[i].finishTime!)!
              .toLowerCase(),
          style: TextStyle(color: kBodyText, fontSize: 16),
          textAlign: TextAlign.right,
        ),
      ),
    ],
  ),


问:
How do I get segment style button in SwiftUI
So in SwiftUI, macOS, I want individual buttons that can be turned on and off like check boxes but look like buttons, and they are interrelates, think like bit flags, and so I want them to touch like you can with NSSegmentedControl, it would seem to me you want use Button or Toggle with some modifier to group them, but I can't find it, PickerStyle seems to be exclusively radio options, which makes sense as SwiftUI seems to be more about describing the function, and then controlling how that is presented.

Update to make it clearer

It for regular expression options, I could do it with checkbox, but it doesn't look very good, it feels like there should be a method to change how the checkboxes are displayed, in this example I have the first three buttons enabled.

答:
here is a simple custom solution:

```<code>struct Option: Hashable {
    let label: String
    var selected: Bool
}

struct ContentView: View {

    @State var options: [Option] = [
        Option(label: "Dot All", selected: false),
        Option(label: "Extended", selected: false),
        Option(label: "Ignore Case", selected: false),
        Option(label: "Multi-line", selected: false),
    ]

    var body: some View {
        OptionPicker(options: $options)
    }
}

struct OptionPicker: View {

    @Binding var options: [Option]

    var body: some View {
        HStack(spacing: 0) {
            ForEach(options.indices, id: \.self) { i in

                Text(options[i].label)
                    .padding(.horizontal, 4)
                    .padding(5)
                    .background(options[i].selected ? .blue : .gray)

                    .onTapGesture {
                        options[i].selected.toggle()
                    }

                if i < options.count-1 {
                Divider()
                }
            }
        }
        .foregroundColor(.white)
        .cornerRadius(10)
        .frame(height: 32)
    }
}
</code>```

Body:
here is a simple custom solution:

struct Option: Hashable {
    let label: String
    var selected: Bool
}

struct ContentView: View {

    @State var options: [Option] = [
        Option(label: "Dot All", selected: false),
        Option(label: "Extended", selected: false),
        Option(label: "Ignore Case", selected: false),
        Option(label: "Multi-line", selected: false),
    ]

    var body: some View {
        OptionPicker(options: $options)
    }
}

struct OptionPicker: View {

    @Binding var options: [Option]

    var body: some View {
        HStack(spacing: 0) {
            ForEach(options.indices, id: \.self) { i in

                Text(options[i].label)
                    .padding(.horizontal, 4)
                    .padding(5)
                    .background(options[i].selected ? .blue : .gray)

                    .onTapGesture {
                        options[i].selected.toggle()
                    }

                if i < options.count-1 {
                Divider()
                }
            }
        }
        .foregroundColor(.white)
        .cornerRadius(10)
        .frame(height: 32)
    }
}


问:
Plotting different columns in same R graph
I guess this question is rather simple but I have a dataframe with 3 columns (A, B and C). A is the name, B has a numeric value, and C is also has a numeric value. The values of each B and C relate to the correspondent line in A

I need to plot a bar graph that allows to observe for each A, the B bar and the C bar next to each other.

Thanks a lot!

答:
You may do this with a one-liner using low level graphics.

```<code>barplot(t(df[-1]), beside=TRUE, names.arg=df$A, col=2:3, legend.text=names(df)[-1])
</code>```

Data (borrowed from TarJae):

```<code>df <- structure(list(A = c("First", "Second", "Third", "Fourth"), B = c(44,
54, 32, 45), C = c(23, 12, 45, 34)), class = "data.frame", row.names = c(NA,
-4L))
</code>```

Body:
You may do this with a one-liner using low level graphics.

barplot(t(df[-1]), beside=TRUE, names.arg=df$A, col=2:3, legend.text=names(df)[-1])

Data (borrowed from TarJae):

df <- structure(list(A = c("First", "Second", "Third", "Fourth"), B = c(44,
54, 32, 45), C = c(23, 12, 45, 34)), class = "data.frame", row.names = c(NA,
-4L))


答:
You have to push it as a new page using Navigator.push

```<code>onImageTap: (url, context, attributes, element) => {
   Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => FullScreenImageViewer(url)),
   );
}
</code>```

Here is your stateless widget:

```<code>class FullScreenImageViewer extends StatelessWidget {
  const FullScreenImageViewer(this.url,{Key? key}) : super(key: key);
  final String url;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Hero(
            tag: 'imageHero',
            child: Image.network(url),
          ),
        ),
        onTap: () {
          Navigator.pop(context);
        },
      ),
    );
  }
}
</code>```

Title: Open image to full screen, if tapped - flutter_html

Body:
You have to push it as a new page using Navigator.push

onImageTap: (url, context, attributes, element) => {
   Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => FullScreenImageViewer(url)),
   );
}

Here is your stateless widget:

class FullScreenImageViewer extends StatelessWidget {
  const FullScreenImageViewer(this.url,{Key? key}) : super(key: key);
  final String url;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Hero(
            tag: 'imageHero',
            child: Image.network(url),
          ),
        ),
        onTap: () {
          Navigator.pop(context);
        },
      ),
    );
  }
}


问:
how to delete all lines containing Letters and characters for a textfile
I have a textfile containing words, numbers, and characters. I want to delete all lines with the characters and words, and keep the lines with numbers.
I found out that all those lines with words and characters have the letter of "r". so I wrote my code as:

The textfile contains these lines as an example:

```<code>-- for example
-- 7 Febraury 2022
5 7 1 5 3.0 2
3*2 3 5 7.0 3
</code>```

and I want to keep these 2 lines:

```<code>5 7 1 5 3.0 2
3*2 3 5 7.0 3
</code>```

This is the code written:
textfile = open('test.txt', 'r')
A = textfile.readlines()

```<code>L = []
for index,name in enumerate(A):
    if 'r' in name:
        L.append(index)

for idx in sorted(L, reverse = True):
    del A[idx]
</code>```

I know it is not a good way to do that, is there any suggestion to do that?

答:
you can find only the words using regex

```<code>import re
with open(r'text_file.txt', 'r') as f:
    data = f.readlines()

with open(r'text_file.txt', 'w') as f:
    for line in data:
        if re.findall(r"(?!^\d+$)^.+$", line):
            f.write(line)
</code>```

Body:
I have a textfile containing words, numbers, and characters. I want to delete all lines with the characters and words, and keep the lines with numbers.
I found out that all those lines with words and characters have the letter of "r". so I wrote my code as:

The textfile contains these lines as an example:

-- for example
-- 7 Febraury 2022
5 7 1 5 3.0 2
3*2 3 5 7.0 3

and I want to keep these 2 lines:

5 7 1 5 3.0 2
3*2 3 5 7.0 3

This is the code written:
textfile = open('test.txt', 'r')
A = textfile.readlines()

L = []
for index,name in enumerate(A):
    if 'r' in name:
        L.append(index)

for idx in sorted(L, reverse = True):
    del A[idx]

I know it is not a good way to do that, is there any suggestion to do that?

Body:
you can find only the words using regex

import re
with open(r'text_file.txt', 'r') as f:
    data = f.readlines()

with open(r'text_file.txt', 'w') as f:
    for line in data:
        if re.findall(r"(?!^\d+$)^.+$", line):
            f.write(line)


答: You can use the regex library re. One way to do that is to loop through the lines and then keep the line only if re.match("[^0-9 ]", line) == None.

Title: how to delete all lines containing Letters and characters for a textfile


问:
Rails 3: Drop a table using migration
I have a table that I created using the migrations, now I want to get rid of this table.  I'm pretty sure I can just back out that migration, but I can't find the syntax to do that.  I found this question from searching Rails DB Migration - How To Drop a Table?

but he basically says you can find what you need and provides a link.  I read that link and I didn't see anything that says how to do it.  I saw pieces of it, but I don't know how to put them together.

I see in the migration it has a self.down method, I really just need to know how to call that.

答:
You can rollback the last migration with:

rake db:rollback

That will run the self.down method, which should be drop_table :table_name

Title: Rails 3: Drop a table using migration


问:
How to change the background color of a button in an app created with react native on iOS?
I am learning to use react native with expo but at one point they ask me to make a button, the button they create looks good, they did it in android, but I want to do it in iOS and only the word changes color</p>

答:
Button component is more limited than the Touchables.
You can set many things on Touchables, and most useful is TouchableOpacity. Read this and see the example:
https://reactnative.dev/docs/touchableopacity</p>


问:
Why I am getting a blank page?
I started following a tutorial today and I dont know why my script is not working?

*{
    margin: 0 ;
    padding: 0;
}
.header{
    min-height: 100vh;
    width: 100%;
    background-image: linear-gradient(rgba(4,9,30,0.7),rgba(4,9,30,0.7)), url(Images/banner.png);
    background-position: center;
    background-size: cover;
    position: relative;

} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="with=device-width, initial-scale=1.0">
    <title>University Website Design - Easy Tutorials</title>
    <link rel="stylesheet" href="style.css">
 </head>
<body>
    <section class="header">

    </section>

</body>
</html></code>```

It is supposed to show a background but my website is blank.

I was following this  tutorial at 8:00 - 8:20. He is using brackets.io while I am using VSC. what am I doing wrong?

答:
This is the running example of your code:

*{
    margin: 0 ;
    padding: 0;
}
.header{
    min-height: 100vh;
    width: 100%;
    background-image: linear-gradient(rgba(4,9,30,0.7),rgba(4,9,30,0.7)), url(https://picsum.photos/seed/picsum/300/300);
    background-position: center;
    background-size: cover;
    position: relative;

} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <section class="header"></section>
</body></code>```

You need to learn, how to locate files, when you give links to images, font-files, or other files. If the image is in same location as your current file, you write url: someImage.png. If it is one folder above, you'll write url: ../someImage.png. Learn, locating files when you mention them, in your CSS.

Title: Why I am getting a blank page?

Body:
I started following a tutorial today and I dont know why my script is not working?

*{
    margin: 0 ;
    padding: 0;
}
.header{
    min-height: 100vh;
    width: 100%;
    background-image: linear-gradient(rgba(4,9,30,0.7),rgba(4,9,30,0.7)), url(Images/banner.png);
    background-position: center;
    background-size: cover;
    position: relative;

}

<!DOCTYPE html>

    <meta name="viewport" content="with=device-width, initial-scale=1.0">
    <title>University Website Design - Easy Tutorials</title>
    <link rel="stylesheet" href="style.css">

It is supposed to show a background but my website is blank.

I was following this  tutorial at 8:00 - 8:20. He is using brackets.io while I am using VSC. what am I doing wrong?

Body:
This is the running example of your code:

*{
    margin: 0 ;
    padding: 0;
}
.header{
    min-height: 100vh;
    width: 100%;
    background-image: linear-gradient(rgba(4,9,30,0.7),rgba(4,9,30,0.7)), url(https://picsum.photos/seed/picsum/300/300);
    background-position: center;
    background-size: cover;
    position: relative;

}

<body>
    <section class="header"></section>
</body>

You need to learn, how to locate files, when you give links to images, font-files, or other files. If the image is in same location as your current file, you write url: someImage.png. If it is one folder above, you'll write url: ../someImage.png. Learn, locating files when you mention them, in your CSS.


问:
iOS+How to place image on half of UINavigationbar and UITableView
I am using UITableView header to add UIImageView and other labels.
But I am unable to place UIImageView in between navigation bar and UITableViewHeader. my Image is going behind navigation bar.
Pls refer the expected design screenshot. Thanks in advance. pls guide me on this.

答: You need to use custom navigation bar to place any object on it as we cannot customize the default navigation bar in such ways.</p>


问:
CDate Function is being reformatted and creates an Error
I have a select query which has a date stored as string e.g. 20211231 (Dec 31, 2021).  I am trying to use the CDate function to convert the string. If I enter the following in the SQL view

```<code>SELECT CDate(Format([XLCustOrdDtl]![DATE_ADDED],"####/##/##")) AS DteAdded
FROM XLCustOrdDtl;
</code>```

The result are as expected, however when I go back to Design view and run the query, Access reformats the string to

```<code>SELECT CDate(Format([XLCustOrdDtl]![DATE_ADDED],"#\/#\/#")) AS DteAdded
FROM XLCustOrdDtl;
</code>```

This results in #Error

Any thoughts on why this is happening and how I might correct the issue?

答:
Apparently, lack of hyphen or slash punctuation in string means Access cannot recognize date parts and # is a date delimiter character and not valid as date format placeholder.

Assuming there are no Null fields and there are always 8 digits including placeholder zeroes, consider:

DateSerial(Left([DATE_ADDED],4), Mid([DATE_ADDED]5,2), Right([DATE_ADDED],2))

Body:
I have a select query which has a date stored as string e.g. 20211231 (Dec 31, 2021).  I am trying to use the CDate function to convert the string. If I enter the following in the SQL view

SELECT CDate(Format([XLCustOrdDtl]![DATE_ADDED],"####/##/##")) AS DteAdded
FROM XLCustOrdDtl;

The result are as expected, however when I go back to Design view and run the query, Access reformats the string to

SELECT CDate(Format([XLCustOrdDtl]![DATE_ADDED],"#\/#\/#")) AS DteAdded
FROM XLCustOrdDtl;

This results in #Error

Any thoughts on why this is happening and how I might correct the issue?


问:
How to prevent the current page from redirecting to another page when refreshing?
Every time I'll reload the Profile page, it will redirect itself to the Homepage. How can I fix this?

Once a user has successfully logged in, he or she will be directed to the Homepage. On the Homepage, there's a Profile Page. I can successfully load the Profile page, however, once I'll reload this, the user will be redirected to the homepage again.

```<code>    //custom hook
export function useAuth() {
  const [currentUser, setCurrentUser] = useState();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => setCurrentUser(user));
    return unsub;
  }, []);

  return currentUser;
}
</code>```

App.js

```<code>function App() {
  const currentUser = useAuth();
  const user = auth.currentUser;
  const navigate = useNavigate();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
      if (user) {
        // User is signed in, see docs for a list of available properties
        // https://firebase.google.com/docs/reference/js/firebase.User
        const uid = user.uid;
        console.log(uid);
        navigate("/Homepage");
        // ...
      } else {
        // User is signed out
        // ...
        navigate("/");
      }
    });

    return unsub;
  }, []);

  return (
    <div>
      <div>
        <Routes>

          {currentUser ? (
            <>
              <Route
                path="/"
                element={
                  <MainLayout>
                    <LoginPage />
                  </MainLayout>
                }
              />
              <Route path="/Homepage" element={<Home />} />
              <Route path="/Profile" element={<ProfilePage />} />
            </>
          ) : (
            <>
              <Route
                path="/"
                element={
                  <MainLayout>
                    <LoginPage />
                  </MainLayout>
                }
              />
            </>
          )}

        </Routes>
      </div>
    </div>
  );
}

export default App;
</code>```

If I'll console.log(currentUser) this is what it shows:

Also in: https://www.reddit.com/r/reactjs/comments/smfsro/how_to_prevent_the_page_from_redirecting_to/

With Protected Route:

```<code>{currentUser ? (
            <>
              <Route
                path="/"
                element={
                  <MainLayout>
                    <LoginPage />
                  </MainLayout>
                }
              />
              <Route path="/Homepage" element={<Home />} />
              <Route
                path="/Profile"
                element={
                  <PrivateRoute>
                    <ProfilePage />
                  </PrivateRoute>
                }
              />

            </>
          ) : (
            <>
              <Route
                path="/"
                element={
                  <MainLayout>
                    <LoginPage />
                  </MainLayout>
                }
              />
            </>
          )}
</code>```

PrivateRoute

```<code>import React from "react";
import { Navigate, Outlet, useLocation } from "react-router-dom";

import { useAuth } from "../../Firebase/utils";

const PrivateRoute = () => {
  const currentUser = useAuth();

  // //   const !currentUser = null; // determine if authorized, from context or however you're doing it

  // // If authorized, return an outlet that will render child elements
  // // If not, return element that will navigate to login page

  // return currentUser ? <Outlet /> : <Navigate to="/" />;

  let location = useLocation();

  if (!currentUser) {
    console.log(currentUser);
    return <Navigate to="/" state={{ from: location }} replace />;
  }
};

export default PrivateRoute;
</code>```

答:
I believe the issue is that currentUser doesn't have a default value, so it's always undefined when you first load the page. You should add a loading state to make sure the user's status is checked before using currentUser to do any logic.

Note: I haven't run any of the code below so there might be some mistakes, but it's just a general idea for reference.

export function useAuth() {
  const [isLoading, setIsLoading] = useState(true); // checking the user's status
  const [currentUser, setCurrentUser] = useState();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
        setCurrentUser(user)
        setIsLoading(false) // finished checking
    });
    return unsub;
  }, []);

  return {currentUser, isLoading};
}
```
<p>So when you're checking if the user is logged in:</p>
<pre class="lang-js prettyprint-override"><code>if(!isLoading && currentUser){
  // is finished loading and user is logged in
}
</code>```

I also recommend you store currentUser in a context instead of using a custom hook, since custom hooks won't allow you to share the state between components and it will be mounted every time you use it.

Instead your hook can be used to get the value from the context.

Something like this:

// store currentUser inside context
const AuthContext = createContext();

export const AuthProvider = ({children}) => {
  const [isLoading, setIsLoading] = useState(true);
  const [currentUser, setCurrentUser] = useState();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
        setCurrentUser(user)
        setIsLoading(false)
    });
    return unsub;
  }, []);

  return (
    <AuthContext.Provider value={{currentUser, isLoading}}>
      {children}
    </AuthContext.Provider>
  )
}

// read context value with custom hook
export useAuth = () => useContext(AuthContext)
```
<p>It'll still be the same when you're using <code>useAuth</code>, only that it's getting states from the context instead.</p>
<pre class="lang-js prettyprint-override"><code>const {currentUser, isLoading} = useAuth()
</code>```

---Edit to question---

Context is used to share data throughout the application, it's great when you need to use the same data in multiple places. You can store data and pass it down with a provider, and access it with a consumer. I won't go into the details, but you can read more about Context API here: https://reactjs.org/docs/context.html#gatsby-focus-wrapper

About how to use AuthProvider, normally you could wrap it like this in App.js

```<code>// App.js
<AuthProvider>
  <div>
    <Routes>{/* ... */}</Routes>
  </div>
</AuthProvider>
</code>```

But in this case since you're using currentUser in App.js already, you'd have to update AuthProvider to HOC, and wrap it around your component

// AuthContext
export const withAuthProvider = WrappedComponent => ({children}) => {
  // ... the rest is the same
}
```
<pre class="lang-js prettyprint-override"><code>// App.js
export default withAuthProvider(App);
</code>```

The reason for this is because context values are only accessible within the scope the provider is wrapped around. Without HOC, your provider is wrapped around your routes, which means the value is not accessible within App.js itself, but is accessible in MainLayout, LoginPage etc.. With HOC, however, since you've wrapped the entire App.js, it can access the values in AuthContext.

Body:
Every time I'll reload the Profile page, it will redirect itself to the Homepage. How can I fix this?

Once a user has successfully logged in, he or she will be directed to the Homepage. On the Homepage, there's a Profile Page. I can successfully load the Profile page, however, once I'll reload this, the user will be redirected to the homepage again.

    //custom hook
export function useAuth() {
  const [currentUser, setCurrentUser] = useState();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => setCurrentUser(user));
    return unsub;
  }, []);

  return currentUser;
}

App.js

function App() {
  const currentUser = useAuth();
  const user = auth.currentUser;
  const navigate = useNavigate();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
      if (user) {
        // User is signed in, see docs for a list of available properties
        // https://firebase.google.com/docs/reference/js/firebase.User
        const uid = user.uid;
        console.log(uid);
        navigate("/Homepage");
        // ...
      } else {
        // User is signed out
        // ...
        navigate("/");
      }
    });

    return unsub;
  }, []);

  return (

        <Routes>

          {currentUser ? (
            <>
              <Route
                path="/"
                element={
                  <MainLayout>
                    <LoginPage />
                  </MainLayout>
                }
              />
              <Route path="/Homepage" element={<Home />} />
              <Route path="/Profile" element={<ProfilePage />} />
            </>
          ) : (
            <>
              <Route
                path="/"
                element={
                  <MainLayout>
                    <LoginPage />
                  </MainLayout>
                }
              />
            </>
          )}

        </Routes>

  );
}

export default App;

If I'll console.log(currentUser) this is what it shows:

Also in: https://www.reddit.com/r/reactjs/comments/smfsro/how_to_prevent_the_page_from_redirecting_to/

With Protected Route:

{currentUser ? (
            <>
              <Route
                path="/"
                element={
                  <MainLayout>
                    <LoginPage />
                  </MainLayout>
                }
              />
              <Route path="/Homepage" element={<Home />} />
              <Route
                path="/Profile"
                element={
                  <PrivateRoute>
                    <ProfilePage />
                  </PrivateRoute>
                }
              />

            </>
          ) : (
            <>
              <Route
                path="/"
                element={
                  <MainLayout>
                    <LoginPage />
                  </MainLayout>
                }
              />
            </>
          )}

PrivateRoute

import React from "react";
import { Navigate, Outlet, useLocation } from "react-router-dom";

import { useAuth } from "../../Firebase/utils";

const PrivateRoute = () => {
  const currentUser = useAuth();

  // //   const !currentUser = null; // determine if authorized, from context or however you're doing it

  // // If authorized, return an outlet that will render child elements
  // // If not, return element that will navigate to login page

  // return currentUser ? <Outlet /> : <Navigate to="/" />;

  let location = useLocation();

  if (!currentUser) {
    console.log(currentUser);
    return <Navigate to="/" state={{ from: location }} replace />;
  }
};

export default PrivateRoute;

Body:
I believe the issue is that currentUser doesn't have a default value, so it's always undefined when you first load the page. You should add a loading state to make sure the user's status is checked before using currentUser to do any logic.

Note: I haven't run any of the code below so there might be some mistakes, but it's just a general idea for reference.

export function useAuth() {
  const [isLoading, setIsLoading] = useState(true); // checking the user's status
  const [currentUser, setCurrentUser] = useState();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
        setCurrentUser(user)
        setIsLoading(false) // finished checking
    });
    return unsub;
  }, []);

  return {currentUser, isLoading};
}

So when you're checking if the user is logged in:

if(!isLoading && currentUser){
  // is finished loading and user is logged in
}

I also recommend you store currentUser in a context instead of using a custom hook, since custom hooks won't allow you to share the state between components and it will be mounted every time you use it.

Instead your hook can be used to get the value from the context.

Something like this:

// store currentUser inside context
const AuthContext = createContext();

export const AuthProvider = ({children}) => {
  const [isLoading, setIsLoading] = useState(true);
  const [currentUser, setCurrentUser] = useState();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
        setCurrentUser(user)
        setIsLoading(false)
    });
    return unsub;
  }, []);

  return (
    <AuthContext.Provider value={{currentUser, isLoading}}>
      {children}
    </AuthContext.Provider>
  )
}

// read context value with custom hook
export useAuth = () => useContext(AuthContext)

It'll still be the same when you're using useAuth, only that it's getting states from the context instead.

const {currentUser, isLoading} = useAuth()

---Edit to question---

Context is used to share data throughout the application, it's great when you need to use the same data in multiple places. You can store data and pass it down with a provider, and access it with a consumer. I won't go into the details, but you can read more about Context API here: https://reactjs.org/docs/context.html#gatsby-focus-wrapper

About how to use AuthProvider, normally you could wrap it like this in App.js

// App.js
<AuthProvider>
  <div>
    <Routes>{/* ... */}</Routes>
  </div>
</AuthProvider>

But in this case since you're using currentUser in App.js already, you'd have to update AuthProvider to HOC, and wrap it around your component

// AuthContext
export const withAuthProvider = WrappedComponent => ({children}) => {
  // ... the rest is the same
}

// App.js
export default withAuthProvider(App);

The reason for this is because context values are only accessible within the scope the provider is wrapped around. Without HOC, your provider is wrapped around your routes, which means the value is not accessible within App.js itself, but is accessible in MainLayout, LoginPage etc.. With HOC, however, since you've wrapped the entire App.js, it can access the values in AuthContext.


问:
Why in the fragment inside the bottomNavigation, the request is not sent to the server from the second time onwards
I have a bottom navigation and when switch between its items In two cases, two different things happen :
First : When the program is first run -> Everything works fine  . that's mean:
enter image description here

Exactly when I debug:
First we enter onSuccess and  livedata valued and finally we listen to it in the fragment And finally we see the list of products in the shopping cart.

enter image description here

So far, so good  But :
Second: When the program is run and After adding other products to the cart and refer to the shopping cart item for the second time  : We do not see any new products added.

After debugging, I realized that when the program is run for the first time, the code snippet inside the init{} block is executed, and as a result, we receive the products of the shopping cart on the server side.
But for the second time after, when we click on the shopping cart item, we only listen to the live data, and in fact, the code snippet inside Init is not executed so that we can receive the server-side products.
Now my question is:
My main problem is with the shopping cart item.
What can I do to change items and return to the cart to receive recently added products?
In fact, when I come to the shopping cart item for the second time, what should I do to execute the code snippet inside Init{} AND To be able to see the new products stored in the database?

答: This is because when the onCreateView method is executed, it causes the init block to be executed only once. The solution is to destroy the piece</p>


问:
How to stop a scheduled task that was started using @Scheduled annotation?
I have created a simple scheduled task using Spring Framework's @Scheduled annotation.

```<code> @Scheduled(fixedRate = 2000)
 public void doSomething() {}
</code>```

Now I want to stop this task, when no longer needed.

I know there could be one alternative to check one conditional flag at the start of this method, but this will not stop execution of this method.

Is there anything Spring provides to stop @Scheduled task ?

答:
Using @conditional will help you check a value from condition method, if it's true? run the scheduler. else don't run.

First: create your condition class that implements the Condition interface and its matches method

```<code>public class MyCondition implements Condition{

public boolean matches(ConditionContext context, AnnotatedTypeMetaData metadata) {

// here implement your condition using if-else or checking another object
// or call another method that can return boolean value
//return boolean value : true or false

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

Then, back to your configuration or service class where you have the @Scheduled

```<code>@Service
@Conditional(value = MyCondition.class)
// this Service will only run if the condition is true
public class scheduledTask {

// the @Scheduled method should be void
@Scheduled(fixedRate= 5000)
public void task(){
System.out.println(" This is scheduled task started....");
}

}
</code>```

This definitely worked for me.

Body:
I have created a simple scheduled task using Spring Framework's @Scheduled annotation.

 @Scheduled(fixedRate = 2000)
 public void doSomething() {}

Now I want to stop this task, when no longer needed.

I know there could be one alternative to check one conditional flag at the start of this method, but this will not stop execution of this method.

Is there anything Spring provides to stop @Scheduled task ?

Body:
Using @conditional will help you check a value from condition method, if it's true? run the scheduler. else don't run.

First: create your condition class that implements the Condition interface and its matches method

public class MyCondition implements Condition{

public boolean matches(ConditionContext context, AnnotatedTypeMetaData metadata) {

// here implement your condition using if-else or checking another object
// or call another method that can return boolean value
//return boolean value : true or false

return true;
}
}

Then, back to your configuration or service class where you have the @Scheduled

@Service
@Conditional(value = MyCondition.class)
// this Service will only run if the condition is true
public class scheduledTask {

// the @Scheduled method should be void
@Scheduled(fixedRate= 5000)
public void task(){
System.out.println(" This is scheduled task started....");
}

}

This definitely worked for me.


问:
onmousemove Event is not able to pass event-data in JavaScript Example
In this example, when I move mouse inside a div, I want to show the (x and y co-ordinates) of mouse current position, but it is showing error. Why?

function fifa(ev){
  document.getElementById('div1').style.background = "cornsilk";
  document.getElementById('div1').innerHTML = (ev.clientX + " "  + ev.clientY);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  height:200px;
  width:200px;
  border:2px solid #000;
  background:green;
  display:inline-block;
  margin:20px;
}</code>```

onmousemove
```

答:
Your error is you are trying to pass the unknown variable ev - it does not exist. You can pass (event) as they do at the site you used:  myFunction(event)

I strongly recommend to change to eventListener and also to use MDN over w3schools

const div1 = document.getElementById('div1'); // cache the element
// only change colour once, using class
div1.addEventListener("mouseenter", function(e) {
  this.classList.add("silk")
})
div1.addEventListener("mouseleave", function(e) {
  this.classList.remove("silk")
})

div1.addEventListener("mousemove", function(e) {
  this.innerHTML = (e.clientX + " "  + e.clientY);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  height:200px;
  width:200px;
  border:2px solid #000;
  background:green;
  display:inline-block;
  margin:20px;
}
div.silk {background:cornsilk; }</code>```

onmousemove
```
</div>
</div>
</p>
<p>For your information but please use my version, here is a fixed version of your code.</p>
<p>Note I pass the event to the function and it is picked up as ev - not recommended since it is already available IN the function</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>function fifa(ev){ // event passed as ev
  ev.target.style.background = "cornsilk"; // the div is the event target
  ev.target.innerHTML = (ev.clientX + " "  + ev.clientY);
}</code>```

div {
  height:200px;
  width:200px;
  border:2px solid #000;
  background:green;
  display:inline-block;
  margin:20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div1" onmousemove="fifa(event)">onmousemove</div></code>```

Body:
In this example, when I move mouse inside a div, I want to show the (x and y co-ordinates) of mouse current position, but it is showing error. Why?

function fifa(ev){
  document.getElementById('div1').style.background = "cornsilk";
  document.getElementById('div1').innerHTML = (ev.clientX + " "  + ev.clientY);
}

div {
  height:200px;
  width:200px;
  border:2px solid #000;
  background:green;
  display:inline-block;
  margin:20px;
}

onmousemove

Body:
Your error is you are trying to pass the unknown variable ev - it does not exist. You can pass (event) as they do at the site you used:  myFunction(event)

I strongly recommend to change to eventListener and also to use MDN over w3schools

const div1 = document.getElementById('div1'); // cache the element
// only change colour once, using class
div1.addEventListener("mouseenter", function(e) {
  this.classList.add("silk")
})
div1.addEventListener("mouseleave", function(e) {
  this.classList.remove("silk")
})

div1.addEventListener("mousemove", function(e) {
  this.innerHTML = (e.clientX + " "  + e.clientY);
})

div {
  height:200px;
  width:200px;
  border:2px solid #000;
  background:green;
  display:inline-block;
  margin:20px;
}
div.silk {background:cornsilk; }

<div id="div1">onmousemove</div>

For your information but please use my version, here is a fixed version of your code.

Note I pass the event to the function and it is picked up as ev - not recommended since it is already available IN the function

function fifa(ev){ // event passed as ev
  ev.target.style.background = "cornsilk"; // the div is the event target
  ev.target.innerHTML = (ev.clientX + " "  + ev.clientY);
}

div {
  height:200px;
  width:200px;
  border:2px solid #000;
  background:green;
  display:inline-block;
  margin:20px;
}

<div id="div1" onmousemove="fifa(event)">onmousemove</div>


问:
What are the different ways to convert a generator expression to a list?
```<code>mylist = [1, 2, 3, 4, 5]
my_gen = (item for item in mylist if item > 3)
new_list = list(my_gen)
</code>```

passing the generator expression to the list function is one way I learned to convert the generator expression into a list. Just curious to know if this can be in  any other different way?

答:
Unclear if you're looking for alternatives or just shorter.

For shorter, you don't need an intermediate variable.

list(item for item in mylist if item > 3)

Which has the same effect as

[item for item in mylist if item > 3]

For alternatives of the generator, you could use filter function on mylist, but you'd still need list() function, or list-compression, or a while loop calling next() until the generator is exhausted for alternatives of making a list

Body:
mylist = [1, 2, 3, 4, 5]
my_gen = (item for item in mylist if item > 3)
new_list = list(my_gen)

passing the generator expression to the list function is one way I learned to convert the generator expression into a list. Just curious to know if this can be in  any other different way?


问:
Disable certain dates from html5 datepicker
Is it possible to disable dates when I use

I want to disable current date for one scenario and future dates for other scenario.
How should I disable the dates?</p>

答:
For react and similar libraries, you may use this to disable all dates before today.

 <input  type='date' min={new Date().toISOString().split('T')[0]} >


问:
The API request failed with the following error: 200 - OK
I administer my shared hosting through cPanel.

It is showing "The API request failed with the following error: 200 - OK." in red popup.

Everything is working fine. I can work on everything as usual, but still this pop?

When i login from another browser, the error is not shown.

How to get rid of it and why is this being shown?

答:
How to get rid of this message was my question.

I had installed a chrom plugin that allowed me to use CORS.

After uninstalling this plugin, the error was gone.


问:
Is this code vulnerable to SQL injection attacks?
Is this code vulnerable to SQL injection attacks?</p>

```<code>$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_author_email, comment_date_gmt, comment_approved, comment_type, comment_author_url, SUBSTRING(comment_content,1,70) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 5";
</code>```

答:
Assuming the $wpdb object is untouchable from the outside (which is generally true in Wordpress), I'd say you're safe with this particular query.

You really only need to worry about passing in any parameter received from an external source.

Wordpress offers several methods for handling user input in queries. See http://codex.wordpress.org/Data_Validation#Database

Body:
Is this code vulnerable to SQL injection attacks?

$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_author_email, comment_date_gmt, comment_approved, comment_type, comment_author_url, SUBSTRING(comment_content,1,70) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 5";


问:
How to prevent jwt token from getting stolen from the mobile phone and misused?
I have a web api and mobile app.

I'm using Oauth (openidconnect). When user invokes the login endpoint, the Oauth flow is triggered which eventually results in the jwt id token being received by the api server (from the auth server).

Assume that the jwt id token is sent to the mobile app by the app server (in the api response), so that the api remains stateless, and subsequent api requests can pass the jwt id token into the endpoint so that the api knows who the caller is.

How to prevent this jwt from being stolen from the mobile phone and misused?

答:
You can get more details on the security-related queries on this page from react-native Documentation on security

For your query on storage of the JWT,
Keychain Services on iOS & Keystore on android are the prebuild solutions on the respective OS, for storing sensitive data. we can write your own API bridging these services or you can use existing packages like react-native-keychain for this purpose.


问:
Can Firestore for the web integrate with service worker for background synchronization?
Can Firestore for the web integrate with a service worker for background synchronization? For example, it seems a user must open the app for the synchronization to happen. It would be nice if background sync could happen through service worker so when user opens app everything is already synced.</p>

答:
It might not have been possible at the time the question was asked but meanwhile with a chrome extension it is possible.

Since version 9 the Firebase Web SDK uses fetch instead of XMLHttpRequest. So it works inside a service worker.

Here is my working example for monitoring the Firestore database and updating the badge of a chrome extension in the background:

background.js:

var unsubscribe;

auth.onAuthStateChanged(function(user) {
    if (user) {
        const db = getFirestore(app);

        let colReference = collection(db, "User", user.uid, "Reference");

        unsubscribe = onSnapshot(colReference, function(querySnapshot) {
            chrome.action.setBadgeText({text: querySnapshot.size.toString()});
        });
    } else {
        unsubscribe();
    }
});

```

See this answer on how to setup Firebase for a Chrome (Manifest v3) extension: https://stackoverflow.com/a/70815962/3243751

And this answer one how to use Firebase Auth for authenticating with the Firestore database: https://stackoverflow.com/a/70987391/3243751

Body:
It might not have been possible at the time the question was asked but meanwhile with a chrome extension it is possible.

Since version 9 the Firebase Web SDK uses fetch instead of XMLHttpRequest. So it works inside a service worker.

Here is my working example for monitoring the Firestore database and updating the badge of a chrome extension in the background:

background.js:

var unsubscribe;

auth.onAuthStateChanged(function(user) {
    if (user) {
        const db = getFirestore(app);

        let colReference = collection(db, "User", user.uid, "Reference");

        unsubscribe = onSnapshot(colReference, function(querySnapshot) {
            chrome.action.setBadgeText({text: querySnapshot.size.toString()});
        });
    } else {
        unsubscribe();
    }
});

See this answer on how to setup Firebase for a Chrome (Manifest v3) extension: https://stackoverflow.com/a/70815962/3243751

And this answer one how to use Firebase Auth for authenticating with the Firestore database: https://stackoverflow.com/a/70987391/3243751


问:
Try to scrape withdrawal fee using Selenium. But doesn't work. (newbie)
I try to scrape this website https://www.bitkub.com/fee/cryptocurrency using Selenium.
I followed the tutorial from Youtube but It doesn't work. It can't find the element I wanted to use (coin_name, chain and withdrawal fees).
I'm newbie to coding by the way. thank you in advance.

Here my code

```<code>from selenium import webdriver
website = 'https://www.bitkub.com/fee/cryptocurrency'
path = r"C:\\Users\\USER\\Downloads\\chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get(website)

#pull_data

coins = driver.find_elements_by_tag_name('tr')

#variable
coin_name = []
chain = []
fee = []
for coin in coins:
    coin_name.append(coin.find_element_by_xpath('./td[2]').text)
    chain.append(coin.find_element_by_xpath('./td[3]').text)
    fee.append(coin.find_element_by_xpath('./td[4]').text)
#driver.quit()
</code>```

答:
```<code>
#pull_data

coins = driver.find_elements_by_tag_name('tr')

#variable
data = []
for coin in coins:
    coin = {
    "coin_name":coin.find_element_by_xpath('./td[2]').text,
    "chain":coin.find_element_by_xpath('./td[3]').text,
    "fee" : coin.find_element_by_xpath('./td[4]').text
    }
    data.append(coin)

</code>```

Try this this will create list of dictionaries and the convert this list to csv file

Body:
I try to scrape this website https://www.bitkub.com/fee/cryptocurrency using Selenium.
I followed the tutorial from Youtube but It doesn't work. It can't find the element I wanted to use (coin_name, chain and withdrawal fees).
I'm newbie to coding by the way. thank you in advance.

Here my code

from selenium import webdriver
website = 'https://www.bitkub.com/fee/cryptocurrency'
path = r"C:\\Users\\USER\\Downloads\\chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get(website)

#pull_data

coins = driver.find_elements_by_tag_name('tr')

#variable
coin_name = []
chain = []
fee = []
for coin in coins:
    coin_name.append(coin.find_element_by_xpath('./td[2]').text)
    chain.append(coin.find_element_by_xpath('./td[3]').text)
    fee.append(coin.find_element_by_xpath('./td[4]').text)
#driver.quit()

Body:
#pull_data

coins = driver.find_elements_by_tag_name('tr')

#variable
data = []
for coin in coins:
    coin = {
    "coin_name":coin.find_element_by_xpath('./td[2]').text,
    "chain":coin.find_element_by_xpath('./td[3]').text,
    "fee" : coin.find_element_by_xpath('./td[4]').text
    }
    data.append(coin)

Try this this will create list of dictionaries and the convert this list to csv file


问:
to_date fails to parse date in Spark 3.0
I am trying to parse date using to_date() but I get the following exception.

SparkUpgradeException: You may get a different result due to the upgrading of Spark 3.0: Fail to parse '12/1/2010 8:26' in the new parser. You can set spark.sql.legacy.timeParserPolicy to LEGACY to restore the behavior before Spark 3.0, or set to CORRECTED and treat it as an invalid datetime string.

The exception suggests I should use a legacy Time Parser, for starter I don't know how to set it to Legacy.

Here is my implementation

```<code>dfWithDate = df.withColumn("date", to_date(col("InvoiceDate"), "MM/dd/yyyy"))
</code>```

my date is in following format

```<code>+--------------+
|   InvoiceDate|
+--------------+
|12/1/2010 8:26|
|12/1/2010 8:26|
|12/1/2010 8:26|
|12/1/2010 8:26|
|12/1/2010 8:26|
</code>```

答:
One can use:

```<code>data = data.withColumn("Date", to_date(unix_timestamp("InvoiceDate", "MM/dd/yyyy").cast("timestamp")))

#result
    +--------------+----------+
    |   InvoiceDate|      Date|
    +--------------+----------+
    |12/1/2010 8:26|2010-12-01|
</code>```

This works for me.

Body:
I am trying to parse date using to_date() but I get the following exception.

SparkUpgradeException: You may get a different result due to the upgrading of Spark 3.0: Fail to parse '12/1/2010 8:26' in the new parser. You can set spark.sql.legacy.timeParserPolicy to LEGACY to restore the behavior before Spark 3.0, or set to CORRECTED and treat it as an invalid datetime string.

The exception suggests I should use a legacy Time Parser, for starter I don't know how to set it to Legacy.

Here is my implementation

dfWithDate = df.withColumn("date", to_date(col("InvoiceDate"), "MM/dd/yyyy"))

my date is in following format

+--------------+
|   InvoiceDate|
+--------------+
|12/1/2010 8:26|
|12/1/2010 8:26|
|12/1/2010 8:26|
|12/1/2010 8:26|
|12/1/2010 8:26|

Body:
One can use:

data = data.withColumn("Date", to_date(unix_timestamp("InvoiceDate", "MM/dd/yyyy").cast("timestamp")))

#result
    +--------------+----------+
    |   InvoiceDate|      Date|
    +--------------+----------+
    |12/1/2010 8:26|2010-12-01|

This works for me.


问:
How do I make a continuously updated picker in swift ui?
i am currently working on a app in swift ui. In the App is the function to add groups, and on the Mainscreen you can pick one of these groups. My problem is, that the one option of a picker I made worked, but it won't update, when I add a new group in the groups menu:

```<code>                        Picker("Please choose a color", selection: $selectedGroup) {
                            ForEach(0 ..< groups.count) {
                                Text(groups[$0].name).tag($0)
                                        }
                                    }
</code>```

and the next thing I tried because of another post don´t works at all:

```<code>                        Picker("select a group", selection: $selectedGroup) {
                                        ForEach(groups, id: \.self) {
                                            Text(groups[$0].name).tag($0)
                                        }
                                    }
</code>```

Here is the Array and struct I used for "groups":

```<code>struct Group: Identifiable{
    let id =  UUID()
    var name: String
    var members: Array<Member>

}

// AND:

var groups : [Group] = [Group = Group(name: "sample", members: [Member(name: "sample guy", sex: "m")])]
</code>```

答:
try something like this:

```<code>struct Group: Identifiable, Hashable {
    let id = UUID()
    var name: String
    var members: [Member]
}

struct ContentView: View {
    @State var selectedGroup: Group?
    @State var groups: [Group] = [Group(name: "sample", members: [Member(name: "sample guy", sex: "m")])]

    var body: some View {
        Button(action: {
            // add a new group with a random name to `groups`
            groups.append(Group(name: UUID().uuidString, members: []))
        }) {
            Text("Add new group")
        }
        Picker("select a group", selection: $selectedGroup) {
            ForEach(groups) { group in
                Text(group.name).tag(group)
            }
        }
    }
}
</code>```

I suggest you
read again Apple's SwiftUI Tutorials https://developer.apple.com/tutorials/swiftui

Body:
i am currently working on a app in swift ui. In the App is the function to add groups, and on the Mainscreen you can pick one of these groups. My problem is, that the one option of a picker I made worked, but it won't update, when I add a new group in the groups menu:

                        Picker("Please choose a color", selection: $selectedGroup) {
                            ForEach(0 ..< groups.count) {
                                Text(groups[$0].name).tag($0)
                                        }
                                    }

and the next thing I tried because of another post don´t works at all:

                        Picker("select a group", selection: $selectedGroup) {
                                        ForEach(groups, id: \.self) {
                                            Text(groups[$0].name).tag($0)
                                        }
                                    }

Here is the Array and struct I used for "groups":

struct Group: Identifiable{
    let id =  UUID()
    var name: String
    var members: Array<Member>

}

// AND:

var groups : [Group] = [Group = Group(name: "sample", members: [Member(name: "sample guy", sex: "m")])]

Body:
try something like this:

struct Group: Identifiable, Hashable {
    let id = UUID()
    var name: String
    var members: [Member]
}

struct ContentView: View {
    @State var selectedGroup: Group?
    @State var groups: [Group] = [Group(name: "sample", members: [Member(name: "sample guy", sex: "m")])]

    var body: some View {
        Button(action: {
            // add a new group with a random name to `groups`
            groups.append(Group(name: UUID().uuidString, members: []))
        }) {
            Text("Add new group")
        }
        Picker("select a group", selection: $selectedGroup) {
            ForEach(groups) { group in
                Text(group.name).tag(group)
            }
        }
    }
}

I suggest you
read again Apple's SwiftUI Tutorials https://developer.apple.com/tutorials/swiftui