问:
Text doesn't appear over CameraPreview layout
I'm trying to create a camera screen in my app that resembles a scanner apps screen. The final design should look something like this:

I was able to create the camera+layout screen by using CameraPreview widget and providing a layout child:

```<code>@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.black,
    body: GestureDetector(
        onLongPress: () async {
          // some logic
        },
        child: Column(children: [
          Stack(children: [
            Text("Center your camera over the indicator ", style: TextStyle(color: Colors.white)),
            Padding(
              padding: EdgeInsets.only(top: 70.0),
              child: FutureBuilder<void>(
                future: _initializeControllerFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    // If the Future is complete, display the preview.
                    return CameraPreview(_controller,
                        child: MaterialPreviewOverlay(
                          overlayColor: overlayColor,
                        ));
                  } else {
                    // Otherwise, display a loading indicator.
                    return const Center(child: CircularProgressIndicator());
                  }
                },
              ),
            )
          ])
        ])),
  );
}
</code>```

The MaterialPreviewOverlay doesn't have too much logic, mainly it calls the painter that looks like this:

```<code>@override
void paint(Canvas canvas, Size size) {
  final screenRect = Rect.fromLTWH(0, 0, size.width, size.height);
  final cutOutWidth = screenRect.width - 80;
  final cutOutHeight = cutOutWidth * 1.7;
  final cutOut = RRect.fromRectAndCorners(
      Rect.fromCenter(
          center: screenRect.center,
          width: cutOutWidth,
          height: cutOutHeight),
      bottomLeft: const Radius.circular(40),
      topRight: const Radius.circular(40),
      topLeft: const Radius.circular(40)
  );
  final cutOutPath = Path.combine(PathOperation.difference,
      Path()..addRect(screenRect), Path()..addRRect(cutOut));
  final borderPaint = Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = 5 // strokeWidth is painted 50/50 outwards and inwards.
    ..color = overlayColor;//.withAlpha(160);
  canvas
    ..drawPath(cutOutPath, backgroundPaint)
    ..drawRRect(cutOut.deflate(borderPaint.strokeWidth / 2), borderPaint);
}
</code>```

For some reason the Text widget isn't shown at all. I tried with Stack (like in the provided code example) and without. If I put the text below the FutureBuilder widget the text is shown (both with and without using Stack) and if I add an appBar to the Scaffold the text is also shown beneath the app bar. But I do not need the app bar, why wouldn't the text appear in my example?

答:
Your Text widget doesn't show up since your Stack order is Text and then the CameraPreview. This means that your Text widget will be drawn and on top of it your CameraPreview will be drawn, which means that your Text widget isn't visible anymore. To fix your issue you have to reorder your Stack so that CameraPreview is before Text.

```<code>Stack(
  children: [
    CameraPreview(),
    Text('My Text'),
  ],
),
</code>```

Body:
I'm trying to create a camera screen in my app that resembles a scanner apps screen. The final design should look something like this:

I was able to create the camera+layout screen by using CameraPreview widget and providing a layout child:

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.black,
    body: GestureDetector(
        onLongPress: () async {
          // some logic
        },
        child: Column(children: [
          Stack(children: [
            Text("Center your camera over the indicator ", style: TextStyle(color: Colors.white)),
            Padding(
              padding: EdgeInsets.only(top: 70.0),
              child: FutureBuilder<void>(
                future: _initializeControllerFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    // If the Future is complete, display the preview.
                    return CameraPreview(_controller,
                        child: MaterialPreviewOverlay(
                          overlayColor: overlayColor,
                        ));
                  } else {
                    // Otherwise, display a loading indicator.
                    return const Center(child: CircularProgressIndicator());
                  }
                },
              ),
            )
          ])
        ])),
  );
}

The MaterialPreviewOverlay doesn't have too much logic, mainly it calls the painter that looks like this:

@override
void paint(Canvas canvas, Size size) {
  final screenRect = Rect.fromLTWH(0, 0, size.width, size.height);
  final cutOutWidth = screenRect.width - 80;
  final cutOutHeight = cutOutWidth * 1.7;
  final cutOut = RRect.fromRectAndCorners(
      Rect.fromCenter(
          center: screenRect.center,
          width: cutOutWidth,
          height: cutOutHeight),
      bottomLeft: const Radius.circular(40),
      topRight: const Radius.circular(40),
      topLeft: const Radius.circular(40)
  );
  final cutOutPath = Path.combine(PathOperation.difference,
      Path()..addRect(screenRect), Path()..addRRect(cutOut));
  final borderPaint = Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = 5 // strokeWidth is painted 50/50 outwards and inwards.
    ..color = overlayColor;//.withAlpha(160);
  canvas
    ..drawPath(cutOutPath, backgroundPaint)
    ..drawRRect(cutOut.deflate(borderPaint.strokeWidth / 2), borderPaint);
}

For some reason the Text widget isn't shown at all. I tried with Stack (like in the provided code example) and without. If I put the text below the FutureBuilder widget the text is shown (both with and without using Stack) and if I add an appBar to the Scaffold the text is also shown beneath the app bar. But I do not need the app bar, why wouldn't the text appear in my example?

Body:
Your Text widget doesn't show up since your Stack order is Text and then the CameraPreview. This means that your Text widget will be drawn and on top of it your CameraPreview will be drawn, which means that your Text widget isn't visible anymore. To fix your issue you have to reorder your Stack so that CameraPreview is before Text.

Stack(
  children: [
    CameraPreview(),
    Text('My Text'),
  ],
),


来源: stackexchange

问:
Most efficient way to handle large multi-dimensional time series data in python
I am providing a statistics service for a video game in which I mine the leaderboard of that game once per hour and create graphs etc. to track the progress of the players.
Initially, I used a MultiIndex DataFrame, which looks similar to this:

```<code>import pandas as pd
import numpy as np
index_arrays = [np.array(["01.01.22"]*4+["02.01.22"]*4),
                np.array(["Name","Level","Money","Guild"]*2)]

df = pd.DataFrame([["a","b","c"],[4,5,6],[7,8,9],
                   [10,11,12],["a","b","d"],[16,1,17],
                   [18,19,20],[21,22,23]], index=index_arrays, columns=["1","2","3"])
</code>```

Output:

```<code>                 1   2   3
01.01.22 Name    a   b   c
         Level   4   5   6
         Money   7   8   9
         Guild  10  11  12
02.01.22 Name    a   b   d
         Level  16   1  17
         Money  18  19  20
         Guild  21  22  23
</code>```

The structure is based on how the leaderboard is mined (Columns represent the rank). After updating this DataFrame, it has always been saved as a .csv file.

However, after a year or so, iterating through this DataFrame and collecting data for a specific player (which was neither easily filterable by column nor index) became really slow.
This was fixed by re-organizing the data in a more player oriented way. Each player got his own .csv file (=> hundreds of those files), which made accessing this data more easy, but at the same time increased the needed disk space significantly.
An example for player "a" looks like this:

```<code>          Level  Money  Guild
01.01.22      4      7     10
02.01.22     16     18     21
</code>```

This works for now, but I am thinking about what would be the most efficient way to continue this, both in the sense of speed of accessing the data and storage space.
I am thinking about switching from a .csv storage to a SQL solution. Would that be faster or require less disk space? Instead of having numerous .csv files, I could use numerous tables in a single database file. Another option I saw in the context of stock data was one big database in which each row would present the entry of one player at a certain time. It would look something like this and adds up to millions of rows.

```<code>  Name  Rank  Level  Money  Guild      Date
0    a     1      4      7     10  01.01.22
1    b     2      5      8     11  01.01.22
2    c     3      6      9     12  01.01.22
3    a     1     16     18     21  02.01.22
4    b     2      1     19     22  02.01.22
5    d     3     17     20     23  02.01.22
</code>```

I realized that this problem may be similar to collecting historical stock market data in which one has time series data of several properties (price, volume, ...) for hundreds of stocks. So I am sure that some people have found the most elegant and fast solution to this kind of problem. Does anyone of you have experience with this and maybe even measured some benchmarks?

答:
You might consider polars. It is orders of magnitudes faster than pandas. And I recommend storing your data in a binary format such as parquet or arrow ipc format (feather).

If you write to parquet, we can even use the statistics in your queries, which might improve your query performance.

ContentLicense: CC BY-SA 4.0

Body:
I am providing a statistics service for a video game in which I mine the leaderboard of that game once per hour and create graphs etc. to track the progress of the players.
Initially, I used a MultiIndex DataFrame, which looks similar to this:

import pandas as pd
import numpy as np
index_arrays = [np.array(["01.01.22"]*4+["02.01.22"]*4),
                np.array(["Name","Level","Money","Guild"]*2)]

df = pd.DataFrame([["a","b","c"],[4,5,6],[7,8,9],
                   [10,11,12],["a","b","d"],[16,1,17],
                   [18,19,20],[21,22,23]], index=index_arrays, columns=["1","2","3"])

Output:

                 1   2   3
01.01.22 Name    a   b   c
         Level   4   5   6
         Money   7   8   9
         Guild  10  11  12
02.01.22 Name    a   b   d
         Level  16   1  17
         Money  18  19  20
         Guild  21  22  23

The structure is based on how the leaderboard is mined (Columns represent the rank). After updating this DataFrame, it has always been saved as a .csv file.

However, after a year or so, iterating through this DataFrame and collecting data for a specific player (which was neither easily filterable by column nor index) became really slow.
This was fixed by re-organizing the data in a more player oriented way. Each player got his own .csv file (=> hundreds of those files), which made accessing this data more easy, but at the same time increased the needed disk space significantly.
An example for player "a" looks like this:

          Level  Money  Guild
01.01.22      4      7     10
02.01.22     16     18     21

This works for now, but I am thinking about what would be the most efficient way to continue this, both in the sense of speed of accessing the data and storage space.
I am thinking about switching from a .csv storage to a SQL solution. Would that be faster or require less disk space? Instead of having numerous .csv files, I could use numerous tables in a single database file. Another option I saw in the context of stock data was one big database in which each row would present the entry of one player at a certain time. It would look something like this and adds up to millions of rows.

  Name  Rank  Level  Money  Guild      Date
0    a     1      4      7     10  01.01.22
1    b     2      5      8     11  01.01.22
2    c     3      6      9     12  01.01.22
3    a     1     16     18     21  02.01.22
4    b     2      1     19     22  02.01.22
5    d     3     17     20     23  02.01.22

I realized that this problem may be similar to collecting historical stock market data in which one has time series data of several properties (price, volume, ...) for hundreds of stocks. So I am sure that some people have found the most elegant and fast solution to this kind of problem. Does anyone of you have experience with this and maybe even measured some benchmarks?


问:
Python Regex re.compile query
I'm trying to find get a list of required names from list of names using a regex query.

csv file:  FYI, I converted Countries from Capital to small letters

searchList:

```<code>['AU.LS1_james.aus',
'AU.LS1_scott.aus',
'AP.LS1_amanda.usa',
'AP.LS1_john.usa',
'LA.LS1_harsha.ind',
'LA.LS1_vardhan.ind',
'IECAU13_peter-tu.can',
'LONSA13_smith.gbp']
</code>```

Format of the searchList: [(region)(Category)]_[EmployeeName].[country]

(region)(Category) is concatenated.

I'm trying to get a list of each group like this,

```<code>[
['AU.LS1_james.aus', 'AU.LS1_scott.aus'],
['AP.LS1_amanda.usa', 'AP.LS1_john.usa'],
['LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']
]
</code>```

Using the following regex query: \<({region}).*\{country}\>

```<code>for region, country in regionCountry:
    query = f"\<({region}).*\{country}\>"
    r = re.compile(query)
    group = list(filter(r.match, searchList))
</code>```

I tried  re.search  as well, but the  group is always  None

FYI: I also tried this query in notepad++ find using regex functionality.
<img src="https://i.stack.imgur.com/r9xeT.png" alt="NOTEPAD++ query: <(AU.LS1).*.aus> " />

Can Anyone Tell where it's going wrong in my script.? Thank you

答:
Without regex:

split

And a dictionary to group the entries:

Data

```<code>entries = ['AU.LS1_james.aus', 'AU.LS1_scott.aus', 'AP.LS1_amanda.usa', 'AP.LS1_john.usa', 'LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']
</code>```

Solution 1: simple dict and setdefault

```<code>d = {}
for entry in entries:
    d.setdefault(entry.split('.',1)[0], []).append(entry)
</code>```

Solution 2: defaultdict

```<code>from collections import defaultdict
d = defaultdict(list)
for entry in entries:
    d[entry.split('.',1)[0]].append(entry)
</code>```

Result is in d.values()

```<code>>>> list(d.values())

[['AU.LS1_james.aus', 'AU.LS1_scott.aus'],
 ['AP.LS1_amanda.usa', 'AP.LS1_john.usa'],
 ['LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']]
</code>```

Title: Python Regex re.compile query

Body:
I'm trying to find get a list of required names from list of names using a regex query.

csv file:  FYI, I converted Countries from Capital to small letters

searchList:

['AU.LS1_james.aus',
'AU.LS1_scott.aus',
'AP.LS1_amanda.usa',
'AP.LS1_john.usa',
'LA.LS1_harsha.ind',
'LA.LS1_vardhan.ind',
'IECAU13_peter-tu.can',
'LONSA13_smith.gbp']

Format of the searchList: [(region)(Category)]_[EmployeeName].[country]

(region)(Category) is concatenated.

I'm trying to get a list of each group like this,

[
['AU.LS1_james.aus', 'AU.LS1_scott.aus'],
['AP.LS1_amanda.usa', 'AP.LS1_john.usa'],
['LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']
]

Using the following regex query: \<({region}).*\{country}\>

for region, country in regionCountry:
    query = f"\<({region}).*\{country}\>"
    r = re.compile(query)
    group = list(filter(r.match, searchList))

I tried  re.search  as well, but the  group is always  None

FYI: I also tried this query in notepad++ find using regex functionality.
<img src="https://i.stack.imgur.com/r9xeT.png" alt="NOTEPAD++ query: <(AU.LS1).*.aus> " />

Can Anyone Tell where it's going wrong in my script.? Thank you

Body:
Without regex:

split

And a dictionary to group the entries:

Data

entries = ['AU.LS1_james.aus', 'AU.LS1_scott.aus', 'AP.LS1_amanda.usa', 'AP.LS1_john.usa', 'LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']

Solution 1: simple dict and setdefault

d = {}
for entry in entries:
    d.setdefault(entry.split('.',1)[0], []).append(entry)

Solution 2: defaultdict

from collections import defaultdict
d = defaultdict(list)
for entry in entries:
    d[entry.split('.',1)[0]].append(entry)

Result is in d.values()

>>> list(d.values())

[['AU.LS1_james.aus', 'AU.LS1_scott.aus'],
 ['AP.LS1_amanda.usa', 'AP.LS1_john.usa'],
 ['LA.LS1_harsha.ind', 'LA.LS1_vardhan.ind']]


问:
R: how to loop through multiple columns and store value in a vector for each category
I am new to R.

I have a time series data set (60k rows) which also has a category built in. Take the example below: the table records each bus journey from 2001 to 2009. [enter image description here][1]

If a bus has multiple journeys, it then has multiple rows with the same bus number. The number of journeys per bus is random. The minimum number of journey is one.

I would like to reshape the data frame below into a table with n rows, where n is equal to the number of unique buses, and the columns shows the sequence of the stops each bus travels through time.

Therefore row one of the new table is
bus1 stop 1 stop20 stop 2 stop 21.

The second row of the table is
bus 2 stop 4 stop 23 stop 5 stop 25 stop 6 stop 25 stop 7 stop 26 stop 8 stop 27.

Since these buses do not have the same number of journeys, the converted table/list do not have the same number of columns.

I don't know what is the best way to reshape the dataset. Should I use loop?

Many thanks

Take the example below:

```<code>df <- data.frame(
  transport = c("bus1", "bus1", "bus2", "bus2", "bus2",
            "bus2", "bus2", "bus2", "bus3", "bus4", "bus4", "bus4",
            "bus4", "bus4", "bus4", "bus4", "bus4", "bus4"),
  travel_time = c(2001, 2002, 2001, 2002, 2003,
                  2004, 2005, 2006, 2001, 2001,2002,2003,
                 2004,2005,2006,2007,2008,2009),
  from = paste("stop",seq(1,18)),
  to = paste("stop",seq(20,37))
)
</code>```

答:
There might be better approaches, as I am an R beginner myself, but I would do it as follows:

```<code>df <- data.frame(
        transport = c("bus1", "bus1", "bus2", "bus2", "bus2",
                "bus2", "bus2", "bus2", "bus3", "bus4", "bus4", "bus4",
                "bus4", "bus4", "bus4", "bus4", "bus4", "bus4"),
        travel_time = c(2001, 2002, 2001, 2002, 2003,
                2004, 2005, 2006, 2001, 2001,2002,2003,
                2004,2005,2006,2007,2008,2009),
        from = paste("stop",seq(1,18)),
        to = paste("stop",seq(20,37))
)

library(tidyr)
df_bus <- df %>%
        #unpivot from/to columns into variable and value columns
        pivot_longer(cols = c(from, to)) %>%
        #combine year information with from/to, so this information is not lost
        transform(year_fromto=paste0(travel_time, "_", name)) %>%
        #pivot the from/to columns per bus id
        pivot_wider(id_cols= transport, names_from = year_fromto, values_from = value)

print(df_bus)
</code>```

Sample output:

```<code># A tibble: 4 × 19
  transport `2001_from` `2001_to` `2002_from` `2002_to` `2003_from` `2003_to`
  <chr>     <chr>       <chr>     <chr>       <chr>     <chr>       <chr>
1 bus1      stop 1      stop 20   stop 2      stop 21   <NA>        <NA>
2 bus2      stop 3      stop 22   stop 4      stop 23   stop 5      stop 24
3 bus3      stop 9      stop 28   <NA>        <NA>      <NA>        <NA>
4 bus4      stop 10     stop 29   stop 11     stop 30   stop 12     stop 31
# … with 12 more variables: `2004_from` <chr>, `2004_to` <chr>,
#   `2005_from` <chr>, `2005_to` <chr>, `2006_from` <chr>, `2006_to` <chr>,
#   `2007_from` <chr>, `2007_to` <chr>, `2008_from` <chr>, `2008_to` <chr>,
#   `2009_from` <chr>, `2009_to` <chr>
</code>```

Body:
I am new to R.

I have a time series data set (60k rows) which also has a category built in. Take the example below: the table records each bus journey from 2001 to 2009. [enter image description here][1]

If a bus has multiple journeys, it then has multiple rows with the same bus number. The number of journeys per bus is random. The minimum number of journey is one.

I would like to reshape the data frame below into a table with n rows, where n is equal to the number of unique buses, and the columns shows the sequence of the stops each bus travels through time.

Therefore row one of the new table is
bus1 stop 1 stop20 stop 2 stop 21.

The second row of the table is
bus 2 stop 4 stop 23 stop 5 stop 25 stop 6 stop 25 stop 7 stop 26 stop 8 stop 27.

Since these buses do not have the same number of journeys, the converted table/list do not have the same number of columns.

I don't know what is the best way to reshape the dataset. Should I use loop?

Many thanks

Take the example below:

df <- data.frame(
  transport = c("bus1", "bus1", "bus2", "bus2", "bus2",
            "bus2", "bus2", "bus2", "bus3", "bus4", "bus4", "bus4",
            "bus4", "bus4", "bus4", "bus4", "bus4", "bus4"),
  travel_time = c(2001, 2002, 2001, 2002, 2003,
                  2004, 2005, 2006, 2001, 2001,2002,2003,
                 2004,2005,2006,2007,2008,2009),
  from = paste("stop",seq(1,18)),
  to = paste("stop",seq(20,37))
)

Body:
There might be better approaches, as I am an R beginner myself, but I would do it as follows:

df <- data.frame(
        transport = c("bus1", "bus1", "bus2", "bus2", "bus2",
                "bus2", "bus2", "bus2", "bus3", "bus4", "bus4", "bus4",
                "bus4", "bus4", "bus4", "bus4", "bus4", "bus4"),
        travel_time = c(2001, 2002, 2001, 2002, 2003,
                2004, 2005, 2006, 2001, 2001,2002,2003,
                2004,2005,2006,2007,2008,2009),
        from = paste("stop",seq(1,18)),
        to = paste("stop",seq(20,37))
)

library(tidyr)
df_bus <- df %>%
        #unpivot from/to columns into variable and value columns
        pivot_longer(cols = c(from, to)) %>%
        #combine year information with from/to, so this information is not lost
        transform(year_fromto=paste0(travel_time, "_", name)) %>%
        #pivot the from/to columns per bus id
        pivot_wider(id_cols= transport, names_from = year_fromto, values_from = value)

print(df_bus)

Sample output:

# A tibble: 4 × 19
  transport `2001_from` `2001_to` `2002_from` `2002_to` `2003_from` `2003_to`
  <chr>     <chr>       <chr>     <chr>       <chr>     <chr>       <chr>
1 bus1      stop 1      stop 20   stop 2      stop 21   <NA>        <NA>
2 bus2      stop 3      stop 22   stop 4      stop 23   stop 5      stop 24
3 bus3      stop 9      stop 28   <NA>        <NA>      <NA>        <NA>
4 bus4      stop 10     stop 29   stop 11     stop 30   stop 12     stop 31
# … with 12 more variables: `2004_from` <chr>, `2004_to` <chr>,
#   `2005_from` <chr>, `2005_to` <chr>, `2006_from` <chr>, `2006_to` <chr>,
#   `2007_from` <chr>, `2007_to` <chr>, `2008_from` <chr>, `2008_to` <chr>,
#   `2009_from` <chr>, `2009_to` <chr>


问:
Find a directory containing desired text and stored all that files into another folder
How can we identify files of desired text in a file of the same directory and then separate all those files into another directory?</p>
```<code>import os
user_input = input('What is the name of your directory')
directory = os.listdir(user_input)
searching = input('What word are you trying to find?')
for fname in directory:
    if os.path.isfile(user_input + os.sep + fname):
        # Full path
        f = open(user_input + os.sep + fname, 'r')

        if searching in f.read():
            print('found string in file %s' % fname)
        else:
            print('string not found')
        f.close()
</code>```

答:
shutil has many methods you can use. One of which is:

```<code>import shutil

shutil.copyfile(src, dst)

# 2nd option
shutil.copy(src, dst)
</code>```

You can copy those file into another location.

by adding

```<code>if searching in f.read():
            print('found string in file %s' % fname)
            shutil.copy(user_input + os.sep + fname,destination)
</code>```

Body:
How can we identify files of desired text in a file of the same directory and then separate all those files into another directory?

import os
user_input = input('What is the name of your directory')
directory = os.listdir(user_input)
searching = input('What word are you trying to find?')
for fname in directory:
    if os.path.isfile(user_input + os.sep + fname):
        # Full path
        f = open(user_input + os.sep + fname, 'r')

        if searching in f.read():
            print('found string in file %s' % fname)
        else:
            print('string not found')
        f.close()

Body:
shutil has many methods you can use. One of which is:

import shutil

shutil.copyfile(src, dst)

# 2nd option
shutil.copy(src, dst)

You can copy those file into another location.

by adding

if searching in f.read():
            print('found string in file %s' % fname)
            shutil.copy(user_input + os.sep + fname,destination)


问:
Replace with HTML ascii codes
I ran into a problem. Wrote the following code snippet:

```<code>teksti = teksti.Trim()
teksti = Replace(teksti, "<", "& lt;")
teksti = Replace(teksti, ">", "& gt;")
teksti = Replace(teksti, """", "& quot;")
teksti = Replace(teksti, "'", "& #8217;")
teksti = Replace(teksti, "%", "& #37;")
teksti = Replace(teksti, "&", "& amp;")
teksti = Replace(teksti, "#", "& #35;")
teksti = Replace(teksti, "@", "& #64;")
</code>```

After writing this I realized it becomes its own problem. The function is supposed to make information safe for HTML and SQL injection (there are other methods too, parameterized queries, etc but that's beside the point). However what happens, is that it first replaces < with & lt;  and then proceeds to replace the newly written string again as every replace string has &, # and ; signs in it.

Any hints? I thought about using a regex for this, but I couldn't find any decent Visual Basic examples that were simple enough.

Edit: Thanks for the tips. I was sure there would be a "smart" easy way to do this, but I guess there are no common methods available after all. The re-arranging the problem cases first is the obvious solution here, thanks for that. I guess the work day was too long for me to notice. :D

As for parametirized queries, checking back I see my English doesn't come out as intended. I meant to say that I'm already using them, that this problem here is specific to prevent all manner of html-injection and possible sql-injection using the same strings elsewhere later. Thanks again for the help.

答:
Like mentioned in previous posts, reordering your "replaces" should provide a quick fix to your specific issue and it is highly advisable for you to look into parametrized queries as well.

Another suggestion is for you to look into the built-in .net libraries for encoding, specifically the Microsoft.Security.Application.AntiXss library which I find it to be better than System.Web.HttpUtility.HtmlEncode because it uses a "whitelist" approach rather than a "blacklist" approach.

You can find more info about it here:

Hope this helps.

OwnerDisplayName: Zan

ContentLicense: CC BY-SA 3.0

Title: Replace with HTML ascii codes

Body:
I ran into a problem. Wrote the following code snippet:

teksti = teksti.Trim()
teksti = Replace(teksti, "<", "& lt;")
teksti = Replace(teksti, ">", "& gt;")
teksti = Replace(teksti, """", "& quot;")
teksti = Replace(teksti, "'", "& #8217;")
teksti = Replace(teksti, "%", "& #37;")
teksti = Replace(teksti, "&", "& amp;")
teksti = Replace(teksti, "#", "& #35;")
teksti = Replace(teksti, "@", "& #64;")

After writing this I realized it becomes its own problem. The function is supposed to make information safe for HTML and SQL injection (there are other methods too, parameterized queries, etc but that's beside the point). However what happens, is that it first replaces < with & lt;  and then proceeds to replace the newly written string again as every replace string has &, # and ; signs in it.

Any hints? I thought about using a regex for this, but I couldn't find any decent Visual Basic examples that were simple enough.

Edit: Thanks for the tips. I was sure there would be a "smart" easy way to do this, but I guess there are no common methods available after all. The re-arranging the problem cases first is the obvious solution here, thanks for that. I guess the work day was too long for me to notice. :D

As for parametirized queries, checking back I see my English doesn't come out as intended. I meant to say that I'm already using them, that this problem here is specific to prevent all manner of html-injection and possible sql-injection using the same strings elsewhere later. Thanks again for the help.

LastEditorDisplayName: Zan

OwnerDisplayName: dcadenas


问:
End To End Encrypted Chat Application using Windows Forms and . Net C#. Where do I start with encryption?
I have an assignment at school to create a chat application. I have created this using SignalR to ensure real time communication. However, our teacher wanted also end to end encryption.

I have 2 projects: 1 server (which contains the hub) and the Client, which communicates directly with the database to load the messages on log-in. When a user is online, the user communicates directly through SignalR connections.

I need to find a way to make this communication secure (teacher suggested Diffie Hellman to exchange keys). It would really be appreciated if any of you guys could put me on the right road where to start or if you could suggest me some articles which could help.

Note: I am a Java Developer and am new to .Net Framework and C#.

If any of you is interested here is the github link to my project: https://github.com/joanjanku2000/chat-app/tree/jjanku/feature/chat-app

答:
You need to read documentation first in order to choose the right encoding/decoding technique.

Read these :

https://learn.microsoft.com/en-us/dotnet/standard/security/cryptography-model

https://learn.microsoft.com/en-us/dotnet/standard/security/generating-keys-for-encryption-and-decryption

https://www.c-sharpcorner.com/article/encryption-and-decryption-using-a-symmetric-key-in-c-sharp/


问:
What are the best practice to handle errors on NodeJS, and to work on validation within the model props using mongoose?
BEST PRACTICE NODEJS :
As I am working on a back-end nodeJS application,
what are the best practice especially when it comes to validate your props,

like email, names ...etc

or this could be handled in the front-end part, it really confuses me.

答:
You can validate your props/inputs either on the backend or frontend but it's important to do so on the backend and it's a good practice to do so on both ends.

Following are the ways of validating your props/input:

Validation on the frontend (ReactJS code):

```<code>const regex =
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    if (!regex.test(email)) {
      return alert('Enter email in correct format!');
    }

    if (!firstName || !lastName || !email || !password || !passwordCheck) {
      return alert('Enter all fields!');
    }
</code>```

Validation on the backend (ExpressJS code):

```<code>const { password, passwordCheck, firstName, email, lastName, employId } =
      req.body;

if (!password || !passwordCheck || !firstName || !email || !lastName)
      return res.json({
        success: false,
        message: "Enter all fields' values!",
      });

    if (password.length < 6) {
      return res.json({
        success: false,
        message: 'Password is too short!',
      });
    }
</code>```

Hope the confusion goes away now.

Body:
You can validate your props/inputs either on the backend or frontend but it's important to do so on the backend and it's a good practice to do so on both ends.

Following are the ways of validating your props/input:

Validation on the frontend (ReactJS code):

const regex =
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    if (!regex.test(email)) {
      return alert('Enter email in correct format!');
    }

    if (!firstName || !lastName || !email || !password || !passwordCheck) {
      return alert('Enter all fields!');
    }

Validation on the backend (ExpressJS code):

const { password, passwordCheck, firstName, email, lastName, employId } =
      req.body;

if (!password || !passwordCheck || !firstName || !email || !lastName)
      return res.json({
        success: false,
        message: "Enter all fields' values!",
      });

    if (password.length < 6) {
      return res.json({
        success: false,
        message: 'Password is too short!',
      });
    }

Hope the confusion goes away now.


问:
Angular pipe with reactive formControlName of angular form array

Here i am using custom pipe to format the rate field.
Which is read only field.
Issue is value attribute not formating the rate field on page load.
Which is working for another fields

```<code><div formArrayName="rateList" *ngFor="let product of formData.controls; let i=index;">
                    <div [formGroupName]="i">
                      <input formControlName="rate" readonly="readonly"
                        [value]="formData.controls[i].get('rate').value  | udpCurrency : false : this.translate.currentLang" />
                    </div>
                  </div>
</code>```

答:
I don't know the exact answer for this, but as a workaround you can use setTimeout at the time you are setting the value to the form array.</p>
```<code>setTimeout(()=> {
  this.rateList.setValue(someRateArray)
} ,0)
</code>```

Body:
Here i am using custom pipe to format the rate field.
Which is read only field.
Issue is value attribute not formating the rate field on page load.
Which is working for another fields

                      <input formControlName="rate" readonly="readonly"
                        [value]="formData.controls[i].get('rate').value  | udpCurrency : false : this.translate.currentLang" />

Body:
I don't know the exact answer for this, but as a workaround you can use setTimeout at the time you are setting the value to the form array.

setTimeout(()=> {
  this.rateList.setValue(someRateArray)
} ,0)


问:
VS Code Logpoint suspends/breaks the execution unexpectedly
I am quite new to JavaScript/TypeScript development in VS Code. I wanted to start experimenting with Eclipse Theia, and so I have implemented a backend service. I wanted to put a logpoint in my backend service to see on the console when it is called.

But sadly, when the execution reaches the respective line, execution is suspended. Only after resuming execution, the expected log message is printed.

This is my setup:

I have created https://github.com/xpomul/theia-boilerplate and there, a branch named hello-world.

I use VS Code 1.63.2 and the Remote Containers Extension.

Here’s what I do:

Start VS Code

Use "Remote-Containers: Clone Repository in Container Volume...“ and clone the https://github.com/xpomul/theia-boilerplate repository branch hello-world

After some waiting to get everything installed, open hello-world-impl.ts and add a logpoint with the expression test in line 7 (so it has a diamond symbol)

Do to the Run/Debug view and select the Launch Backend launch configuration and start it

Open a browser at http://127.0.0.1:3000 and run Edit > Say Hello

I’d expect that the backend continues running and just prints test to the log.

Instead, it breaks/suspends execution at the line of the logpoint and I need to explicitly resume.

What am I doing wrong? Is it some configuration issue? Or is the logpoint functionality dependent on the node version (Theia uses Node 12...) and is just not yet supported? Or is it because of TypeScript or the usage of inversify?

EDIT: I have also captured and attached a debug trace file, if that helps: https://dav.winklerweb.net/s/y5snhRgfiyaEF2B

答:
Turns out it was a bug in vscode-js-debug:

https://github.com/microsoft/vscode-js-debug/issues/1191

It’s fixed in the latest nightly build and should be available in the next official VS Code release.


问:
Change div content on mouse hover with default content fallback
I've implemented the accepted answer to Change div content based on mouse hover on different divs across a lot of links, so I don't really want to go with another solution if it can be avoided. I'm trying to figure out one more piece of the puzzle though...

I can't seem to get it to where it defaults back to the original text of the content div when not hovering over an item.

```<code><div id="content">
    Stuff should be placed here.
</div>

<br/>
<br/>
<br/>
<ul>
    <li onmouseover="hover('Apples are delicious')">Apple</li>
    <li onmouseover="hover('oranges are healthy')">Orange</li>
    <li onmouseover="hover('Candy is the best')">Candy</li>
</ul>

<script>
    function hover(description) {
        console.log(description);
        document.getElementById('content').innerHTML = description;
    }
</script>
</code>```

答:
i dont think in your code there was anything to make the content to go back to the default but i have made the least changes in your code to make the content to go back to default and i have used onmouseout event for that.

```<code><div id="content">
    Stuff should be placed here.
</div>

<br/>
<br/>
<br/>
<ul>
    <li onmouseover="hover('Apples are delicious')" onmouseout="hover('Stuff should be placed here.')">Apple</li>
    <li onmouseover="hover('oranges are healthy')" onmouseout="hover('Stuff should be placed here.')">Orange</li>
    <li onmouseover="hover('Candy is the best')" onmouseout="hover('Stuff should be placed here.')">Candy</li>
</ul>

<script>
    function hover(description) {
        console.log(description);
        document.getElementById('content').innerHTML = description;
    }
</script>
</code>```

Body:
I've implemented the accepted answer to Change div content based on mouse hover on different divs across a lot of links, so I don't really want to go with another solution if it can be avoided. I'm trying to figure out one more piece of the puzzle though...

I can't seem to get it to where it defaults back to the original text of the content div when not hovering over an item.

    Stuff should be placed here.

Apple

Orange

Candy

Body:
i dont think in your code there was anything to make the content to go back to the default but i have made the least changes in your code to make the content to go back to default and i have used onmouseout event for that.

<div id="content">
    Stuff should be placed here.
</div>

<br/>
<br/>
<br/>
<ul>
    <li onmouseover="hover('Apples are delicious')" onmouseout="hover('Stuff should be placed here.')">Apple</li>
    <li onmouseover="hover('oranges are healthy')" onmouseout="hover('Stuff should be placed here.')">Orange</li>
    <li onmouseover="hover('Candy is the best')" onmouseout="hover('Stuff should be placed here.')">Candy</li>
</ul>

<script>
    function hover(description) {
        console.log(description);
        document.getElementById('content').innerHTML = description;
    }
</script>


问:
Issues with list index after swapping first and last number in the list
I am new to Python and with the swapping exercise, I cannot swap the first and last element of the list using the following code (the line with issue noted below).

def swapList(list):

    first = list.pop(0)
    last = list.pop(-1)

    list.insert(0, last)
    list.insert(-1, first)  # this line is the issue.
    # It does not swap first to the last position in the list,
    # but instead place it just before the last number. If I change
    # it to list.append(first) then the issue is solved.
    # I cannot understand why.

    return list
```

Can you please help?

答:
The insert method will insert the element to the left of the index you provide - my_list.insert(0, 1) would insert the value 1 to left of index 0 in my_list.

To add an item to the end of your list, use the append method instead: my_list.append(1).

Also, don't call your list list - list is a reserved keyword in Python and should not be used to name a variable. You could instead use my_list, or , preferably, a name that describes what the list is for/the data it contains.

Body:
I am new to Python and with the swapping exercise, I cannot swap the first and last element of the list using the following code (the line with issue noted below).

def swapList(list):

    first = list.pop(0)
    last = list.pop(-1)

    list.insert(0, last)
    list.insert(-1, first)  # this line is the issue.
    # It does not swap first to the last position in the list,
    # but instead place it just before the last number. If I change
    # it to list.append(first) then the issue is solved.
    # I cannot understand why.

    return list

Can you please help?


问:
Can you stretch the CSS grid to fill the width of the screen?
I'm wanting to stretch out the grid to look like the second image attached in the imgur below (sorry I can't post directly on I don't have enough points to post the image directly)

My code:

.container {
    display: grid;
    grid-template-columns: 0.5fr 2.4fr 1.3fr 1fr;
    grid-template-rows: 1fr 1fr 1fr [F] 1fr;
    /* gap: 1px 0px; */
    grid-auto-flow: row;
    grid-template-areas:
      "One oneTitle oneDescrip Picture"
      "Two twoTitle twoDescrip Picture"
      "Three threeTitle threeDescrip Picture"
      "Four fourTitle fourDescrip Picture";
  }

  .One { grid-area: One; }

  .Two { grid-area: Two;  }

  .Three { grid-area: Three; }

  .Four { grid-area: Four; }

  .oneTitle { grid-area: oneTitle;  }

  .twoTitle { grid-area: twoTitle; }

  .threeTitle { grid-area: threeTitle; }

  .fourTitle { grid-area: fourTitle; }

  .oneDescrip { grid-area: oneDescrip; }

  .twoDescrip { grid-area: twoDescrip; }

  .threeDescrip { grid-area: threeDescrip; }

  .fourDescrip { grid-area: fourDescrip; }

  .Picture { grid-area: Picture; }

  .One,.Two,.Three,.Four {
      font-size: 60px;
      color: lightgray;

  }

  .oneTitle, .twoTitle, .threeTitle, .fourTitle, .oneDescrip, .twoDescrip, .threeDescrip, .fourDescrip {
    /* padding-top: 35px; */
    color: black;
    padding-right: 30px;
    padding-left: 20px;
  }

  .oneTitle, .twoTitle, .threeTitle, .fourTitle {
    font-weight: bold;
    padding-top: 17px;
    font-size: 25px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
      <div class="One">1</div>
      <hr>
      <div class="Two">2</div>
      <div class="Three">3</div>
      <div class="Four">4</div>
      <div class="oneTitle">Connect your Crowds</div>
      <div class="twoTitle">Gamify the Experience</div>
      <div class="threeTitle">Engage with Business Growth</div>
      <div class="fourTitle">Continuous Interaction</div>
      <div class="oneDescrip">Descript</div>
      <div class="twoDescrip">Descript</div>
      <div class="threeDescrip">whehwehahha</div>
      <div class="fourDescrip">Descriptjwsenwejwje</div>
      <div class="Picture"><img id="block3img" src="https://i.imgur.com/PEbCBjt.png")></div>
      </div></code>```

What it looks like:

What I want it to look like:

答: In the .container rule set make this declaration. width: 100%;

Body:
I'm wanting to stretch out the grid to look like the second image attached in the imgur below (sorry I can't post directly on I don't have enough points to post the image directly)

My code:

.container {
    display: grid;
    grid-template-columns: 0.5fr 2.4fr 1.3fr 1fr;
    grid-template-rows: 1fr 1fr 1fr [F] 1fr;
    /* gap: 1px 0px; */
    grid-auto-flow: row;
    grid-template-areas:
      "One oneTitle oneDescrip Picture"
      "Two twoTitle twoDescrip Picture"
      "Three threeTitle threeDescrip Picture"
      "Four fourTitle fourDescrip Picture";
  }

  .One { grid-area: One; }

  .Two { grid-area: Two;  }

  .Three { grid-area: Three; }

  .Four { grid-area: Four; }

  .oneTitle { grid-area: oneTitle;  }

  .twoTitle { grid-area: twoTitle; }

  .threeTitle { grid-area: threeTitle; }

  .fourTitle { grid-area: fourTitle; }

  .oneDescrip { grid-area: oneDescrip; }

  .twoDescrip { grid-area: twoDescrip; }

  .threeDescrip { grid-area: threeDescrip; }

  .fourDescrip { grid-area: fourDescrip; }

  .Picture { grid-area: Picture; }

  .One,.Two,.Three,.Four {
      font-size: 60px;
      color: lightgray;

  }

  .oneTitle, .twoTitle, .threeTitle, .fourTitle, .oneDescrip, .twoDescrip, .threeDescrip, .fourDescrip {
    /* padding-top: 35px; */
    color: black;
    padding-right: 30px;
    padding-left: 20px;
  }

  .oneTitle, .twoTitle, .threeTitle, .fourTitle {
    font-weight: bold;
    padding-top: 17px;
    font-size: 25px;
  }

1

2

3

4

Connect your Crowds

Gamify the Experience

Engage with Business Growth

Continuous Interaction

Descript

Descript

whehwehahha

Descriptjwsenwejwje

What it looks like:

What I want it to look like:


问:
.Net compact framework: inherit from DataGridTextBoxColumn, GetColumnValueAtRow is missing
The DataGrid in the .net compact framework (I'm using v3.5) is a bit limited. I try to display a bool-value with app-defined texts like "on/off" or translations of "true/false". I've created a class DataGridBoolColumn which inherits from DataGridTextBoxColumn and there I override the Paint-method. But I've problems with retrieving the current value of the cell, since there's no GetColumnValueAtRow-method in the comapct framework.

In my small app I know, that the grid is bound to a DataView and I can pass the relevant objects to my constructor so I can look up the value. But this is not a real generic way so I can't use this class in other apps with other bound data sources. Is there a "righter" way to get the current value in the Paint method?

答:
I hope this answer helps someone</p>

```<code>DirectCast(DirectCast(source.List(rowNum), System.Object), System.Data.DataRowView).Row(Me.MappingName, Data.DataRowVersion.Current)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I hope this answer helps someone

DirectCast(DirectCast(source.List(rowNum), System.Object), System.Data.DataRowView).Row(Me.MappingName, Data.DataRowVersion.Current)


问:
.apk Built from GitHub Workflow not Compatible with Local Build
When I try to install an .apk built from a GitHub workflow over one that I built locally, I get the following error:

```<code>$ adb install -r /path/to/package-debug.apk
Performing Push Install
/path/to/package-debug.apk: 1 file pushed, 0 skipped. 14.1 MB/s (4047241 bytes in 0.275s)
        pkg: /data/local/tmp/package-debug.apk
Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]
</code>```

I can install the GitHub built version if I uninstall the locally built package first.

I have run aapk on both packages to make sure they were built with the same min & target values. My guess is that the key signatures are different, but I'm not sure. The build is configured to use the default signing config (signingConfig signingConfigs.debug) in build.gradle. Do different versions of the Android development tools provide different versions of the debug signing keystore? Or does each installation generate a unique keystore file? Is there a way I can get more information on why the installation fails?

I also noticed that the file sizes are different:

```<code>$ wc -c local-debug.apk
4085058 local-debug.apk

$ wc -c remote-debug.apk
4047241 remote-debug.apk
</code>```

I have looked at this question, but the answers are about uninstalling first. I need to figure out how to make the remote build compatible with the local one.

答:
I found a solution before posting this question. And as I haven't seen the answer on StackOverflow, I will post it in case it might help someone else.

It appears that the Android development tools generate unique debug keystores on systems that don't already have one. I was assuming that the keystore file was a universal one. So to solve the problem, I simply included the keystore file with the source code (I'm assuming is safe as it is meant for debugging only) & set its location in the gradle.build file.

In this particular case, I put the keystore file in the same directory as the gradlew script & added the following line to app/build.gradle:

```<code>signingConfigs.debug.storeFile file("../debug.keystore")
</code>```

Edit: Though now I have deleted it as the head developer felt it was unsecure. So, use this solution at your own risk & don't use debug keys for signing official releases of your software.

Body:
When I try to install an .apk built from a GitHub workflow over one that I built locally, I get the following error:

$ adb install -r /path/to/package-debug.apk
Performing Push Install
/path/to/package-debug.apk: 1 file pushed, 0 skipped. 14.1 MB/s (4047241 bytes in 0.275s)
        pkg: /data/local/tmp/package-debug.apk
Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]

I can install the GitHub built version if I uninstall the locally built package first.

I have run aapk on both packages to make sure they were built with the same min & target values. My guess is that the key signatures are different, but I'm not sure. The build is configured to use the default signing config (signingConfig signingConfigs.debug) in build.gradle. Do different versions of the Android development tools provide different versions of the debug signing keystore? Or does each installation generate a unique keystore file? Is there a way I can get more information on why the installation fails?

I also noticed that the file sizes are different:

$ wc -c local-debug.apk
4085058 local-debug.apk

$ wc -c remote-debug.apk
4047241 remote-debug.apk

I have looked at this question, but the answers are about uninstalling first. I need to figure out how to make the remote build compatible with the local one.

Body:
I found a solution before posting this question. And as I haven't seen the answer on StackOverflow, I will post it in case it might help someone else.

It appears that the Android development tools generate unique debug keystores on systems that don't already have one. I was assuming that the keystore file was a universal one. So to solve the problem, I simply included the keystore file with the source code (I'm assuming is safe as it is meant for debugging only) & set its location in the gradle.build file.

In this particular case, I put the keystore file in the same directory as the gradlew script & added the following line to app/build.gradle:

signingConfigs.debug.storeFile file("../debug.keystore")

Edit: Though now I have deleted it as the head developer felt it was unsecure. So, use this solution at your own risk & don't use debug keys for signing official releases of your software.


问:
Check list element parts for mandatory array
I have a string list of files with the same names but different extensions and an array of extensions.
Every file name must have every extension and I want to output all missing pairs.
Is there good LINQ for it?

var files = new List<string>() { "file2.jpg", "file1.jpg", "file1.png", "file2.bmp", "file3.png", "file1.bmp" };
var exts = new[] { ".png", ".bmp", ".jpg" };
```
<p>The result must be like this</p>
```file2 missing .png
file3 missing .bmp, .jpg
```

答:
Serhii answer is efficient enough.
Anyway, I would advise to check for double extension if these files are not used internally only. There are couple of plug-and-play solutions for this one.</p>

Body:
I have a string list of files with the same names but different extensions and an array of extensions.
Every file name must have every extension and I want to output all missing pairs.
Is there good LINQ for it?

var files = new List<string>() { "file2.jpg", "file1.jpg", "file1.png", "file2.bmp", "file3.png", "file1.bmp" };
var exts = new[] { ".png", ".bmp", ".jpg" };

The result must be like this

file2 missing .png
file3 missing .bmp, .jpg


答:
You need to store the original text and bring it back when the mouse leaves.

var element = getElementById('content'),
  storedText;

function hover(description) {
    console.log(description);
  storedText = element.innerHTML;
  element.innerHTML = description;
}

function leave() {
    element.innerHTML = storedText;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content">
    Stuff should be placed here.
</div>

<br/>
<br/>
<br/>
<ul>
    <li onmouseover="hover('Apples are delicious')" onmouseleave="leave()">Apple</li>
    <li onmouseover="hover('oranges are healthy')" onmouseleave="leave()">Orange</li>
    <li onmouseover="hover('Candy is the best')" onmouseleave="leave()">Candy</li>
</ul></code>```

It is generally recommended to add event listeners in the JS code and not in the HTML, but put that aside for now.

Title: Change div content on mouse hover with default content fallback

Body:
You need to store the original text and bring it back when the mouse leaves.

var element = getElementById('content'),
  storedText;

function hover(description) {
    console.log(description);
  storedText = element.innerHTML;
  element.innerHTML = description;
}

function leave() {
    element.innerHTML = storedText;
}

<div id="content">
    Stuff should be placed here.
</div>

<br/>
<br/>
<br/>
<ul>
    <li onmouseover="hover('Apples are delicious')" onmouseleave="leave()">Apple</li>
    <li onmouseover="hover('oranges are healthy')" onmouseleave="leave()">Orange</li>
    <li onmouseover="hover('Candy is the best')" onmouseleave="leave()">Candy</li>
</ul>

It is generally recommended to add event listeners in the JS code and not in the HTML, but put that aside for now.


问:
Prevent file name changes in chooser of Intent.ACTION_CREATE_DOCUMENT
I am using the following code to have a user select where to export a file:

```<code>private void onChooseFile() {
  SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
  Intent intent = new Intent()
    .setType("*/*")
    .setAction(Intent.ACTION_CREATE_DOCUMENT)
    .putExtra(Intent.EXTRA_TITLE, dateFormatter.format(new Date()) + "-Whatever.mydb");

  Intent chooser = Intent.createChooser(intent, "Select a file");

  startActivityForResult(chooser, FILE_SELECT_CODE);
}
</code>```

This works unless a user decides to delete my default provided file name... then it creates a file called literally "(invalid)" at the selected location... how do I prevent users changing my default provided name... my real intent is to make sure that the file that I export is never called "(invalid)" and always ends with the "mydb" extension.

答:
I am using the following code to have a user select where to export a file:

Not only that but you give them also the power to determine the file name.

Instead you should use ACTION_OPEN_DOCUMENT_TREE to .. to have a user select where to export a file.

The user then selects the directory upon which you can write a file in it with a suitable name.

Body:
I am using the following code to have a user select where to export a file:

private void onChooseFile() {
  SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
  Intent intent = new Intent()
    .setType("*/*")
    .setAction(Intent.ACTION_CREATE_DOCUMENT)
    .putExtra(Intent.EXTRA_TITLE, dateFormatter.format(new Date()) + "-Whatever.mydb");

  Intent chooser = Intent.createChooser(intent, "Select a file");

  startActivityForResult(chooser, FILE_SELECT_CODE);
}

This works unless a user decides to delete my default provided file name... then it creates a file called literally "(invalid)" at the selected location... how do I prevent users changing my default provided name... my real intent is to make sure that the file that I export is never called "(invalid)" and always ends with the "mydb" extension.


问:
Use Async/Await in event handler in react
I have a function with two arrows, which sends some form data to my api via a POST request with fetch, once the form gets submitted. I want to make fetch asynchronous, but I really have no clue where the async keyword goes in this case.

```<code> //handles the submitting process
const handleSubmit = async (form_username, form_email, form_password) => (event) => {
  event.preventDefault();

    let data = {
      username: form_username,
      email: form_email,
      password: form_password,
    };

    const response = await fetch(API + "/register", {
      method: "POST",
      mode: "cors",
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
      body: JSON.stringify(data),
    });
};
</code>```

The function would then be called via handleSubmit(param1, param2,...);

However, having the async keyword infront of the first params list returns the error unexpected reserved word 'await'

Any ideas where I should place the async keyword in order to actually make it async?
Thanks in advance!

答:
Your async is declared on the wrong function: it should be the inner function that is being returned, since it is the one that contains the await keyword:

```<code>const handleSubmit = (form_username, form_email, form_password) => async (event) => {
  // Rest of the logic here
}
</code>```

Body:
I have a function with two arrows, which sends some form data to my api via a POST request with fetch, once the form gets submitted. I want to make fetch asynchronous, but I really have no clue where the async keyword goes in this case.

 //handles the submitting process
const handleSubmit = async (form_username, form_email, form_password) => (event) => {
  event.preventDefault();

    let data = {
      username: form_username,
      email: form_email,
      password: form_password,
    };

    const response = await fetch(API + "/register", {
      method: "POST",
      mode: "cors",
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
      body: JSON.stringify(data),
    });
};

The function would then be called via handleSubmit(param1, param2,...);

However, having the async keyword infront of the first params list returns the error unexpected reserved word 'await'

Any ideas where I should place the async keyword in order to actually make it async?
Thanks in advance!

Body:
Your async is declared on the wrong function: it should be the inner function that is being returned, since it is the one that contains the await keyword:

const handleSubmit = (form_username, form_email, form_password) => async (event) => {
  // Rest of the logic here
}


问:
Spring Controller GET/POST/PUT to another interface
I am using React as frontend and Java Spring Boot as backend.
React sends JSON form data as GET/PUT/POST requests to my backend url (http://localhost:8080/test). Now, I wan't to send this JSON forward to another interfaces GET endpoint (https://another/interface/add?id={id}). This interface then queries database based on the id and answers 200 OK message with a JSON reply which I need to display (send back to frontend).

1. What is the correct way of sending a request to another interface from Spring Boot backend? In the same method I catched the frontends data?

2. I also have to set HTTP headers to the GET request, how would I go on about this?

Example of how Frontend is sending an id field as a JSON to backend:

React POST

```<code>    addId = async (data) => {
        return this.post(/localhost:8080/test/id, data)
    }
</code>```

Example of how Backend is receiving the id field:

Spring Boot POST

```<code>    @PostMapping("test/id")
    public String test(@RequestBody String id) {
        return id;
    }
</code>```

答:
As I understand you want to get data from backend with json body and httpstatuscode 200 . Am i right?

May be you can try this

```<code>@GetMapping(/interface/add)
public ResponseEntity<?> test(@RequestParam("id") String id){
  //write code you want
return ResponseEntity.status(HttpStatus.OK).body("string" or dto possible);
}
</code>```

ResponseEntity send body with httpstatus code and if you want to send requestparam you set @RequestParam annotation to set .

When I do project with springboot and react. I use json type to exchange data. And Most Services usually exchange data with json data type.

2.I confused about this Question if you send data React to springboot your code is right
Axios.get("localhost....", data) you can change http type with
Axios.(get, post, delete)

Body:
I am using React as frontend and Java Spring Boot as backend.
React sends JSON form data as GET/PUT/POST requests to my backend url (http://localhost:8080/test). Now, I wan't to send this JSON forward to another interfaces GET endpoint (https://another/interface/add?id={id}). This interface then queries database based on the id and answers 200 OK message with a JSON reply which I need to display (send back to frontend).

1. What is the correct way of sending a request to another interface from Spring Boot backend? In the same method I catched the frontends data?

2. I also have to set HTTP headers to the GET request, how would I go on about this?

Example of how Frontend is sending an id field as a JSON to backend:

React POST

    addId = async (data) => {
        return this.post(/localhost:8080/test/id, data)
    }

Example of how Backend is receiving the id field:

Spring Boot POST

    @PostMapping("test/id")
    public String test(@RequestBody String id) {
        return id;
    }

Body:
As I understand you want to get data from backend with json body and httpstatuscode 200 . Am i right?

May be you can try this

@GetMapping(/interface/add)
public ResponseEntity<?> test(@RequestParam("id") String id){
  //write code you want
return ResponseEntity.status(HttpStatus.OK).body("string" or dto possible);
}

ResponseEntity send body with httpstatus code and if you want to send requestparam you set @RequestParam annotation to set .

When I do project with springboot and react. I use json type to exchange data. And Most Services usually exchange data with json data type.

2.I confused about this Question if you send data React to springboot your code is right
Axios.get("localhost....", data) you can change http type with
Axios.(get, post, delete)


问:
Is there a RegEx to extract semicolon separated values from a string... possibly containing string with semicolon
I would like to extract values from a string semicolon separated values that could also contains semicolon but not as separator. The RegEx I found on this website (I lost the post) is almost complete because it separates the key and it's value.

Example:
my.parameter 10; the.foo "Procedural Map"; pve; server.description "This; is \"my\", my description,.\n"

Current result with [^; "]+|"(?:\\"|[^"])*"/g

```<code>[
  'server.seed',
  '10',
  'pve',
  'server.level',
  '"Procedural Map"',
  'server.description',
  '"This; is \\"my\\", server; description,."'
]
</code>```

Desired result

```<code>[
  'my.parameter 10',
  'the.foo "Procedural Map"',
  'pve',
  'server.description "This; is \"my\", server; description,.\n"'
]
</code>```

Can you help me to improve the RegEx to group the parameter and it's value?

答:
You could use a repeating pattern to first match any char except the ; and then optionally match from an opening till closing double quote and match the escaped double quotes in between.

After that optionally repeat the character class [^";\\]* to also match what comes after the closing double quote.

```<code>[^;"\\]+(?:"(?:[^"\\]*(?:\\.[^"\\]*)*)"[^";\\]*)*
</code>```

[^;"\\]+ Match 1+ times any char except ; " \

(?: Non capture group to repeat as a whole

" Match literally

(?: Non capture group

[^"\\]* Match 0+ times any char except " \

(?:\\.[^"\\]*)* Optionally repeat matching \ and any char followed by 0+ times any char except " and \

) Close the non capture group

" Match literally

[^";\\]* Optionally match any char except " ; \

)* Close the outer non capture group and optionally repeat

Regex demo

Body:
I would like to extract values from a string semicolon separated values that could also contains semicolon but not as separator. The RegEx I found on this website (I lost the post) is almost complete because it separates the key and it's value.

Example:
my.parameter 10; the.foo "Procedural Map"; pve; server.description "This; is \"my\", my description,.\n"

Current result with [^; "]+|"(?:\\"|[^"])*"/g

[
  'server.seed',
  '10',
  'pve',
  'server.level',
  '"Procedural Map"',
  'server.description',
  '"This; is \\"my\\", server; description,."'
]

Desired result

[
  'my.parameter 10',
  'the.foo "Procedural Map"',
  'pve',
  'server.description "This; is \"my\", server; description,.\n"'
]

Can you help me to improve the RegEx to group the parameter and it's value?

Body:
You could use a repeating pattern to first match any char except the ; and then optionally match from an opening till closing double quote and match the escaped double quotes in between.

After that optionally repeat the character class [^";\\]* to also match what comes after the closing double quote.

[^;"\\]+(?:"(?:[^"\\]*(?:\\.[^"\\]*)*)"[^";\\]*)*

[^;"\\]+ Match 1+ times any char except ; " \

(?: Non capture group to repeat as a whole

" Match literally

(?: Non capture group

[^"\\]* Match 0+ times any char except " \

(?:\\.[^"\\]*)* Optionally repeat matching \ and any char followed by 0+ times any char except " and \

) Close the non capture group

" Match literally

[^";\\]* Optionally match any char except " ; \

)* Close the outer non capture group and optionally repeat

Regex demo


答:
The Python documentation says this about list.insert:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

So this is what happens to the list:

```<code>>>> xs = [1, 2, 3, 4, 5]
>>> first = xs.pop()
>>>
>>> xs = [1, 2, 3, 4, 5]
>>> first = xs.pop(0)
>>> last = xs.pop(-1)
>>>
>>> xs
[2, 3, 4]
>>>
>>> xs.insert(0, first)
>>> xs
[1, 2, 3, 4]
>>> xs.insert(-1, last)
>>> xs
[1, 2, 3, 5, 4]
>>>
</code>```

The index you specify is "the index of the element before which to insert", so insert(-1, 5) inserts 5 before the last element. So if you change the line to list.insert(len(list), last), your function will work as expected

However, there's a better way to do this. If you want to swap the first and the last item in the list, you can use tuple unpacking:

xs[0], xs[-1] = xs[-1], xs[0]
```

Title: Issues with list index after swapping first and last number in the list

Body:
The Python documentation says this about list.insert:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

So this is what happens to the list:

>>> xs = [1, 2, 3, 4, 5]
>>> first = xs.pop()
>>>
>>> xs = [1, 2, 3, 4, 5]
>>> first = xs.pop(0)
>>> last = xs.pop(-1)
>>>
>>> xs
[2, 3, 4]
>>>
>>> xs.insert(0, first)
>>> xs
[1, 2, 3, 4]
>>> xs.insert(-1, last)
>>> xs
[1, 2, 3, 5, 4]
>>>

The index you specify is "the index of the element before which to insert", so insert(-1, 5) inserts 5 before the last element. So if you change the line to list.insert(len(list), last), your function will work as expected

However, there's a better way to do this. If you want to swap the first and the last item in the list, you can use tuple unpacking:

xs[0], xs[-1] = xs[-1], xs[0]


问:
How to use count and where function in MongoDB?
Need some help here..have been stuck for awhile.

List all Name, Company Name of clients who have applied more than 2 loans which has a yearly repayment plan.

I should get 3 outputs:

```<code>John Tan, Happy Food Industry Pte Ltd
Mary Lee, Nice Man Advertising Pte Ltd
Yuyu Lee, NAGM Tuition Centre
</code>```

My dataset:

```<code>[
  {
    "name": "John Tan",
    "contact_number": [
      "81726351",
      "92019283",
      "90192837"
    ],
    "company_name": "Happy Food Industry Pte Ltd",
    "company_registration_number": 950001819,
    "type_of_ownership": "owner",
    "last_roll_call": "16-06-21",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "Yes",
    "plan_next_call": "01-12-21",
    "financial_year_ended": "30-06-21",
    "profit_and_lost_as_on_last_closing": 8000,
    "cumulative_profit_and_lost_as_on_last_closing": 50000,
    "loan_applied": [
      "Purchase of delivery lorry",
      "Renovation of tuition centre"
    ],
    "commission_date": "01-12-19",
    "loan_duration_in_mths": 24,
    "interest_rate": 3,
    "repayment_plan": "yearly",
    "loan_amount": 138058298,
    "status": "Requesting for delay payments",
    "other_notes": null
  },
  {
    "name": "Mary Lee",
    "contact_number": [
      "95213355"
    ],
    "company_name": "Nice Man Advertising Pte Ltd",
    "company_registration_number": 960087657,
    "type_of_ownership": "Partner with 50% holding",
    "last_roll_call": "15-06-21",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "Yes",
    "plan_next_call": "Dec 21",
    "financial_year_ended": "30-01-21",
    "profit_and_lost_as_on_last_closing": 9000,
    "cumulative_profit_and_lost_as_on_last_closing": 40000,
    "loan_applied": [
      "Purchase of crane",
      "Purchase of machinery from USA"
    ],
    "commission_date": "01-11-19",
    "loan_duration_in_mths": 23,
    "interest_rate": 4,
    "repayment_plan": "yearly",
    "loan_amount": 1237162,
    "status": "Healthy",
    "other_notes": null
  },
  {
    "name": "Yuyu Lee",
    "contact_number": [
      "928371623"
    ],
    "company_name": "NAGM Tuition Centre",
    "type_of_ownership": "Partner with 20% holding",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "Yes",
    "plan_next_call": "12-12-21",
    "financial_year_ended": "30-01-21",
    "profit_and_lost_as_on_last_closing": 1000000,
    "cumulative_profit_and_lost_as_on_last_closing": 3002000,
    "loan_applied": [
      "Purchase of raw material from China",
      "Renovation of shopping mall"
    ],
    "commission_date": "01-11-19",
    "loan_duration_in_mths": 11,
    "interest_rate": 4,
    "repayment_plan": "yearly",
    "loan_amount": 918272,
    "status": "Completed",
    "other_notes": null
  },
  {
    "name": "Joseph Lee",
    "contact_number": [
      "918273615",
      "0192837176",
      "1827361923"
    ],
    "company_name": "Akaka Tuition Centre",
    "company_registration_number": 929381782,
    "type_of_ownership": "Director",
    "last_roll_call": "15-11-21",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "No",
    "plan_next_call": null,
    "financial_year_ended": "30-01-21",
    "profit_and_lost_as_on_last_closing": 999999,
    "cumulative_profit_and_lost_as_on_last_closing": 9000,
    "loan_applied": "Purchase of delivery lorry",
    "commission_date": "01-11-19",
    "loan_duration_in_mths": 11,
    "interest_rate": 4,
    "repayment_plan": "monthly",
    "loan_amount": 918272,
    "status": "Completed",
    "other_notes": null
  },
  {
    "name": "Tan Meh Meh",
    "contact_number": [
      "92837162",
      "9189278371"
    ],
    "company_name": "Target Pte Ltd",
    "company_registration_number": 293891823,
    "type_of_ownership": "Director",
    "last_roll_call": "15-12-21",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "Yes",
    "plan_next_call": "09-12-21",
    "financial_year_ended": "30-01-21",
    "profit_and_lost_as_on_last_closing": 12500000,
    "cumulative_profit_and_lost_as_on_last_closing": 1500000,
    "loan_applied": "Purchase of delivery lorry",
    "commission_date": "01-11-19",
    "loan_duration_in_mths": 55,
    "interest_rate": 4,
    "repayment_plan": "monthly",
    "loan_amount": 918272,
    "status": "Completed",
    "other_notes": null
  },
  {
    "name": "Teo Bee Bee",
    "contact_number": [
      "92039189278",
      "192838182",
      "192837172"
    ],
    "company_name": "Hello Kitty Pte Ltd",
    "company_registration_number": 102039192,
    "type_of_ownership": "Owner",
    "last_roll_call": "13-11-21",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "Yes",
    "plan_next_call": "09-01-21",
    "financial_year_ended": "30-01-21",
    "profit_and_lost_as_on_last_closing": 6000,
    "cumulative_profit_and_lost_as_on_last_closing": 24000000,
    "loan_applied": "Purchase of delivery lorry",
    "commission_date": "01-11-19",
    "loan_duration_in_mths": 33,
    "interest_rate": 4,
    "repayment_plan": "monthly",
    "loan_amount": 2312333,
    "status": "Requesting for delay payments",
    "other_notes": null
  }
]
</code>```

答:
The following query will get you what is needed.

```<code>db.collection.find( { "loan_applied.1": {  "$exists": true }, "repayment_plan": "yearly" } , {"name":1, "company_name": 1} );
</code>```

Explanation:

Since loan_applied is an array field, we can use the dot notation to see if any element exist after the index 1, which means more than 1 element. We add one more filter for repayment_plan.

In the second part of the query, we use projection to return back only name and company_name.

Body:
Need some help here..have been stuck for awhile.

List all Name, Company Name of clients who have applied more than 2 loans which has a yearly repayment plan.

I should get 3 outputs:

John Tan, Happy Food Industry Pte Ltd
Mary Lee, Nice Man Advertising Pte Ltd
Yuyu Lee, NAGM Tuition Centre

My dataset:

[
  {
    "name": "John Tan",
    "contact_number": [
      "81726351",
      "92019283",
      "90192837"
    ],
    "company_name": "Happy Food Industry Pte Ltd",
    "company_registration_number": 950001819,
    "type_of_ownership": "owner",
    "last_roll_call": "16-06-21",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "Yes",
    "plan_next_call": "01-12-21",
    "financial_year_ended": "30-06-21",
    "profit_and_lost_as_on_last_closing": 8000,
    "cumulative_profit_and_lost_as_on_last_closing": 50000,
    "loan_applied": [
      "Purchase of delivery lorry",
      "Renovation of tuition centre"
    ],
    "commission_date": "01-12-19",
    "loan_duration_in_mths": 24,
    "interest_rate": 3,
    "repayment_plan": "yearly",
    "loan_amount": 138058298,
    "status": "Requesting for delay payments",
    "other_notes": null
  },
  {
    "name": "Mary Lee",
    "contact_number": [
      "95213355"
    ],
    "company_name": "Nice Man Advertising Pte Ltd",
    "company_registration_number": 960087657,
    "type_of_ownership": "Partner with 50% holding",
    "last_roll_call": "15-06-21",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "Yes",
    "plan_next_call": "Dec 21",
    "financial_year_ended": "30-01-21",
    "profit_and_lost_as_on_last_closing": 9000,
    "cumulative_profit_and_lost_as_on_last_closing": 40000,
    "loan_applied": [
      "Purchase of crane",
      "Purchase of machinery from USA"
    ],
    "commission_date": "01-11-19",
    "loan_duration_in_mths": 23,
    "interest_rate": 4,
    "repayment_plan": "yearly",
    "loan_amount": 1237162,
    "status": "Healthy",
    "other_notes": null
  },
  {
    "name": "Yuyu Lee",
    "contact_number": [
      "928371623"
    ],
    "company_name": "NAGM Tuition Centre",
    "type_of_ownership": "Partner with 20% holding",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "Yes",
    "plan_next_call": "12-12-21",
    "financial_year_ended": "30-01-21",
    "profit_and_lost_as_on_last_closing": 1000000,
    "cumulative_profit_and_lost_as_on_last_closing": 3002000,
    "loan_applied": [
      "Purchase of raw material from China",
      "Renovation of shopping mall"
    ],
    "commission_date": "01-11-19",
    "loan_duration_in_mths": 11,
    "interest_rate": 4,
    "repayment_plan": "yearly",
    "loan_amount": 918272,
    "status": "Completed",
    "other_notes": null
  },
  {
    "name": "Joseph Lee",
    "contact_number": [
      "918273615",
      "0192837176",
      "1827361923"
    ],
    "company_name": "Akaka Tuition Centre",
    "company_registration_number": 929381782,
    "type_of_ownership": "Director",
    "last_roll_call": "15-11-21",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "No",
    "plan_next_call": null,
    "financial_year_ended": "30-01-21",
    "profit_and_lost_as_on_last_closing": 999999,
    "cumulative_profit_and_lost_as_on_last_closing": 9000,
    "loan_applied": "Purchase of delivery lorry",
    "commission_date": "01-11-19",
    "loan_duration_in_mths": 11,
    "interest_rate": 4,
    "repayment_plan": "monthly",
    "loan_amount": 918272,
    "status": "Completed",
    "other_notes": null
  },
  {
    "name": "Tan Meh Meh",
    "contact_number": [
      "92837162",
      "9189278371"
    ],
    "company_name": "Target Pte Ltd",
    "company_registration_number": 293891823,
    "type_of_ownership": "Director",
    "last_roll_call": "15-12-21",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "Yes",
    "plan_next_call": "09-12-21",
    "financial_year_ended": "30-01-21",
    "profit_and_lost_as_on_last_closing": 12500000,
    "cumulative_profit_and_lost_as_on_last_closing": 1500000,
    "loan_applied": "Purchase of delivery lorry",
    "commission_date": "01-11-19",
    "loan_duration_in_mths": 55,
    "interest_rate": 4,
    "repayment_plan": "monthly",
    "loan_amount": 918272,
    "status": "Completed",
    "other_notes": null
  },
  {
    "name": "Teo Bee Bee",
    "contact_number": [
      "92039189278",
      "192838182",
      "192837172"
    ],
    "company_name": "Hello Kitty Pte Ltd",
    "company_registration_number": 102039192,
    "type_of_ownership": "Owner",
    "last_roll_call": "13-11-21",
    "follow_up_notes": "Do not require any loan at this moment",
    "need_to_follow_up": "Yes",
    "plan_next_call": "09-01-21",
    "financial_year_ended": "30-01-21",
    "profit_and_lost_as_on_last_closing": 6000,
    "cumulative_profit_and_lost_as_on_last_closing": 24000000,
    "loan_applied": "Purchase of delivery lorry",
    "commission_date": "01-11-19",
    "loan_duration_in_mths": 33,
    "interest_rate": 4,
    "repayment_plan": "monthly",
    "loan_amount": 2312333,
    "status": "Requesting for delay payments",
    "other_notes": null
  }
]

Body:
The following query will get you what is needed.

db.collection.find( { "loan_applied.1": {  "$exists": true }, "repayment_plan": "yearly" } , {"name":1, "company_name": 1} );

Explanation:

Since loan_applied is an array field, we can use the dot notation to see if any element exist after the index 1, which means more than 1 element. We add one more filter for repayment_plan.

In the second part of the query, we use projection to return back only name and company_name.


答:
list.pop removes elements from the list, making the list shorter. You can avoid this:

```<code>tmp = list[0]
list[0] = list[-1]
list[-1] = tmp
</code>```

If you are required to use pop, then using insert to re-add that index to the list is needed:

```<code>tmp = list.pop(0)         # Remove 0 element from list, assign to tmp
list.insert(0, list[-1])  #Shifts elements by +1 for new 0th element
list[-1] = tmp            # Assign tmp to last element in list
</code>```

Body:
I am new to Python and with the swapping exercise, I cannot swap the first and last element of the list using the following code (the line with issue noted below).

def swapList(list):

    first = list.pop(0)
    last = list.pop(-1)

    list.insert(0, last)
    list.insert(-1, first)  # this line is the issue.
    # It does not swap first to the last position in the list,
    # but instead place it just before the last number. If I change
    # it to list.append(first) then the issue is solved.
    # I cannot understand why.

    return list

Can you please help?

Body:
list.pop removes elements from the list, making the list shorter. You can avoid this:

tmp = list[0]
list[0] = list[-1]
list[-1] = tmp

If you are required to use pop, then using insert to re-add that index to the list is needed:

tmp = list.pop(0)         # Remove 0 element from list, assign to tmp
list.insert(0, list[-1])  #Shifts elements by +1 for new 0th element
list[-1] = tmp            # Assign tmp to last element in list


问:
Initialising a C vector pointer throws a bus error but initialising a vector doesn't
This C code:

```<code>#include <stdlib.h>

typedef struct
{
    int *a;
    int sz, cap;
} Vector;

void vector_init(Vector *v)
{
    v->a = (int *)malloc(sizeof(int));
    v->sz = 0;
    v->cap = 1;
}

int main()
{
    Vector *v;
    vector_init(v);
}
</code>```

throws a bus error.
but replacing Vector *v with Vector v and vector_init(v) with vector_init(&v) solves it. why?

答:
I would use flexible array members instead of pointers.

In your code you need to pass double pointer In this case it is not the best idea, it is much better to use function return value instead side effects

You need to allocate the memory for the structure itself, bot only for the data.

Use correct types for sizes and indexes.

Check for allocation errors!!

Do not cast the result of malloc

```<code>typedef struct
{
    size_t sz, cap;
    int a[];
} Vector;

Vector *vector_init(void)
{
    Vector *vi = malloc(sizeof(*vi) + sizeof(vi->a[0]));

    if(vi)
    {
        vi->sz = 0;
        vi->cap = 1;
    }
    return vi;
}
</code>```

If you do not want to return the value

```<code>void vector_init(Vector **vi)
{
    *vi = malloc(sizeof(**vi) + sizeof((*vi)->a[0]));

    if(*vi)
    {
        (*vi)->sz = 0;
        (*vi)->cap = 1;
    }
}
</code>```

and usage

```<code>int main()
{
    Vector *v;
    vector_init(&v);
}
</code>```

Body:
This C code:

#include <stdlib.h>

typedef struct
{
    int *a;
    int sz, cap;
} Vector;

void vector_init(Vector *v)
{
    v->a = (int *)malloc(sizeof(int));
    v->sz = 0;
    v->cap = 1;
}

int main()
{
    Vector *v;
    vector_init(v);
}

throws a bus error.
but replacing Vector *v with Vector v and vector_init(v) with vector_init(&v) solves it. why?

Body:
I would use flexible array members instead of pointers.

In your code you need to pass double pointer In this case it is not the best idea, it is much better to use function return value instead side effects

You need to allocate the memory for the structure itself, bot only for the data.

Use correct types for sizes and indexes.

Check for allocation errors!!

Do not cast the result of malloc

typedef struct
{
    size_t sz, cap;
    int a[];
} Vector;

Vector *vector_init(void)
{
    Vector *vi = malloc(sizeof(*vi) + sizeof(vi->a[0]));

    if(vi)
    {
        vi->sz = 0;
        vi->cap = 1;
    }
    return vi;
}

If you do not want to return the value

void vector_init(Vector **vi)
{
    *vi = malloc(sizeof(**vi) + sizeof((*vi)->a[0]));

    if(*vi)
    {
        (*vi)->sz = 0;
        (*vi)->cap = 1;
    }
}

and usage

int main()
{
    Vector *v;
    vector_init(&v);
}


问:
A large database or several smaller?
After reading a lot about it and similar questions, I am still not clear about the following case.

I have an schema like this in one mysql database, where I store the probabilities of matches of more than 10 sports depending on the type of result
(is intended for an application that shows the odds for each sport on different pages but I will never mix sports on the same page):

Design 1: a single database

```<code>SPORT
id
name

TEAM
id
sportId
name
birth

MATCHES
id
sportId
teamId_1
teamId_2
result
date

PROBABILITIES
id
matchId
type
percentage
</code>```

(table Probabilities is very long, almost a billion rows, and will grow over time)

All necessary fields are correctly indexed. Then to see all the probabilities of the matches that do not have result with the football sport with id = 1, I would make the following query:

```<code>SELECT s.name, t1.name as nameTeam1, t2.name as nameTeam2, t1.birth as birthTeam1, t2.birth as birthTeam2, m.date, p.type, p.percentage
FROM matches m
INNER JOIN team t1 ON t1.id = m.teamId_1
INNER JOIN team t2 ON t2.id = m.teamId_2
INNER JOIN sport s ON s.id = m.sportId
INNER JOIN probabilities p ON p.matchId = m.id
WHERE result IS NULL
AND s.id = 1
</code>```

This database design is great because it allows me to work comfortably with ORM like Prisma. But for my team the most important thing is speed and performance.

Knowing this, is it a good idea to do it this way or would it be better to separate the tables into several databases?

Design 2: one database per sport

Database Football

```<code>TEAM
id
sportId
name
birth

MATCHES
id
teamId_1
teamId_2
date

PROBABILITIES
id
matchId
type
percentage
</code>```

Database Basketball

```<code>TEAM
id
sportId
name
birth

MATCHES
id
teamId_1
teamId_2
date

PROBABILITIES
id
matchId
type
percentage
</code>```

The probabilities table is much smaller, in some sports only thousands of rows.

So if, for example, I only need to take the football probabilities I make a query like this:

```<code>SELECT t1.name as nameTeam1, t2.name as nameTeam2, t1.birth as birthTeam1, t2.birth as birthTeam2, m.date, p.type, p.percentage
FROM football.matches m
INNER JOIN football.team t1 ON t1.id = m.teamId_1
INNER JOIN football.team t2 ON t2.id = m.teamId_2
INNER JOIN football.probabilities p ON p.matchId = m.id
WHERE result IS NULL
</code>```

Or is there some other way to improve the speed and performance of the database such as partitioning the probabilities table when we only query the most recent rows in the database?

答:
In MySQL, a "DATABASE" is a very lightweight thing.  It makes virtually no difference to MySQL and queries as to whether you have one db or two.  Or 20.

You might need a little bit of syntax to handle JOINs:

One db:

```<code>USE db;
SELECT a.x, b.y
    FROM a
    JOIN b ON ...;
</code>```

Two dbs:

```<code>USE db;
SELECT a.x, b.y
    FROM db1.a AS a
    JOIN db2.b AS b  ON ...;
</code>```

The performance of those two is the same.

Bottom Line:  Do what feels good to you, the developer.

Title: A large database or several smaller?

Body:
After reading a lot about it and similar questions, I am still not clear about the following case.

I have an schema like this in one mysql database, where I store the probabilities of matches of more than 10 sports depending on the type of result
(is intended for an application that shows the odds for each sport on different pages but I will never mix sports on the same page):

Design 1: a single database

SPORT
id
name

TEAM
id
sportId
name
birth

MATCHES
id
sportId
teamId_1
teamId_2
result
date

PROBABILITIES
id
matchId
type
percentage

(table Probabilities is very long, almost a billion rows, and will grow over time)

All necessary fields are correctly indexed. Then to see all the probabilities of the matches that do not have result with the football sport with id = 1, I would make the following query:

SELECT s.name, t1.name as nameTeam1, t2.name as nameTeam2, t1.birth as birthTeam1, t2.birth as birthTeam2, m.date, p.type, p.percentage
FROM matches m
INNER JOIN team t1 ON t1.id = m.teamId_1
INNER JOIN team t2 ON t2.id = m.teamId_2
INNER JOIN sport s ON s.id = m.sportId
INNER JOIN probabilities p ON p.matchId = m.id
WHERE result IS NULL
AND s.id = 1

This database design is great because it allows me to work comfortably with ORM like Prisma. But for my team the most important thing is speed and performance.

Knowing this, is it a good idea to do it this way or would it be better to separate the tables into several databases?

Design 2: one database per sport

Database Football

TEAM
id
sportId
name
birth

MATCHES
id
teamId_1
teamId_2
date

PROBABILITIES
id
matchId
type
percentage

Database Basketball

TEAM
id
sportId
name
birth

MATCHES
id
teamId_1
teamId_2
date

PROBABILITIES
id
matchId
type
percentage

The probabilities table is much smaller, in some sports only thousands of rows.

So if, for example, I only need to take the football probabilities I make a query like this:

SELECT t1.name as nameTeam1, t2.name as nameTeam2, t1.birth as birthTeam1, t2.birth as birthTeam2, m.date, p.type, p.percentage
FROM football.matches m
INNER JOIN football.team t1 ON t1.id = m.teamId_1
INNER JOIN football.team t2 ON t2.id = m.teamId_2
INNER JOIN football.probabilities p ON p.matchId = m.id
WHERE result IS NULL

Or is there some other way to improve the speed and performance of the database such as partitioning the probabilities table when we only query the most recent rows in the database?

Body:
In MySQL, a "DATABASE" is a very lightweight thing.  It makes virtually no difference to MySQL and queries as to whether you have one db or two.  Or 20.

You might need a little bit of syntax to handle JOINs:

One db:

USE db;
SELECT a.x, b.y
    FROM a
    JOIN b ON ...;

Two dbs:

USE db;
SELECT a.x, b.y
    FROM db1.a AS a
    JOIN db2.b AS b  ON ...;

The performance of those two is the same.

Bottom Line:  Do what feels good to you, the developer.


问:
ASP.NET AWS Serverless
After publishing the serverless API project to the AWS Lambda, the serverless Url not working. Running the project in local is still working, but the serverless Url just wont work. What can possibly be the reason?

答:
Looks like your API is not deployed.

To deploy your API go to the AWS console and try to deploy your API resource:

Use the following options:

Actions > Deploy API:

Title: ASP.NET AWS Serverless


问:
Using a static library in c (.a file)
I am trying to create a static library using a shell script.

For creating the library I used following script:

gcc -c -Wall -Wextra -Werror *.c
ar -cr libft.a *.o
```
<p>There are 5 different functions in 5 .c files.</p>
<p>Now I wanted to test the library and created a main.c file with this content:</p>
<pre class="lang-c prettyprint-override"><code>#include "libft.a"

int     main(void)
{
    ft_putstr("hello");
}
</code>```

Compiling the main.c (with gcc main.c) returns 419 warning and at least 20 errors looking something like this:

```<code>./libft.a:4:492: warning: null character ignored [-Wnull-character]
  ...<U+0000>UH<89><E5>H<83><EC><U+0010>@<88>}<FF><BF><U+0001><U+0000><U+0000><U+0000>H<8D>u...
</code>```

Before this I was working with .h files which worked fine but this time I wasn't supposed to create a .h file so I don't what to do know.

答:
When you compile your main.c, add the library name to it like this:

```<code>gcc main.c libft.a
</code>```

Title: Using a static library in c (.a file)

Body:
I am trying to create a static library using a shell script.

For creating the library I used following script:

gcc -c -Wall -Wextra -Werror *.c
ar -cr libft.a *.o

There are 5 different functions in 5 .c files.

Now I wanted to test the library and created a main.c file with this content:

#include "libft.a"

int     main(void)
{
    ft_putstr("hello");
}

Compiling the main.c (with gcc main.c) returns 419 warning and at least 20 errors looking something like this:

./libft.a:4:492: warning: null character ignored [-Wnull-character]
  ...UH<89><E5>H<83><EC>@<88>}<FF><BF>H<8D>u...

Before this I was working with .h files which worked fine but this time I wasn't supposed to create a .h file so I don't what to do know.

Body:
When you compile your main.c, add the library name to it like this:

gcc main.c libft.a


问:
Discord.py and OS module in Discord Bot (sorry description should explain better)
Basically I came up with this idea to allow for certain apps or features on my laptop to be operated through a private discord server. The bot is still in testing phase so I'm using System Preferences because it can be opened and closed the fastest.

Anyway I'm surprised to see that the bot has somewhat worked and I am able to close apps from my Discord server, but I also want to be notified whenever certain apps have been opened. As you'll see in the image I have attached: Discord Bot in action, whenever I open System Preferences, it doesn't send me a message until I say something in chat. It will keep saying "Someone has opened System Preferences" every time I say anything unless I close it.

```<code>@client.event
async def on_message(message):
  if message.author == client.user:
    return

  # Sytem Preferences
  SysPref=(is_running("System Preferences"))
  if SysPref == True:
    await message.channel.send("Someone has opened System Preferences!")

  if message.content.startswith("!close System_Preferences") and SysPref == True:
    os.system("pkill System Preferences")
    await message.channel.send("System Preferences closed!")
  elif message.content.startswith("!close System_Preferences") and SysPref == False:
    await message.channel.send("System Preferences is not open")
</code>```

I used this AppleScript incorporated into Python from somewhere on stack overflow:

```<code>def is_runnning(app):
    count = int(subprocess.check_output(["osascript",
          "-e", "tell application \"System Events\"",
          "-e", "count (every process whose name is \"" + app + "\")",
          "-e", "end tell"]).strip())
return count > 0
</code>```

答:
I dont understand you code perfectly but I think maybe you are not returning after an if statement. So it continues to execute the next if statement as well. This may sound dumb but try it

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  # Sytem Preferences
  SysPref=(is_running("System Preferences"))
  if SysPref == True:
    await message.channel.send("Someone has opened System Preferences!")
    return

  if message.content.startswith("!close System_Preferences") and SysPref == True:
    os.system("pkill System Preferences")
    await message.channel.send("System Preferences closed!")
    return

  elif message.content.startswith("!close System_Preferences") and SysPref == False:
    await message.channel.send("System Preferences is not open")
    return
```

Body:
Basically I came up with this idea to allow for certain apps or features on my laptop to be operated through a private discord server. The bot is still in testing phase so I'm using System Preferences because it can be opened and closed the fastest.

Anyway I'm surprised to see that the bot has somewhat worked and I am able to close apps from my Discord server, but I also want to be notified whenever certain apps have been opened. As you'll see in the image I have attached: Discord Bot in action, whenever I open System Preferences, it doesn't send me a message until I say something in chat. It will keep saying "Someone has opened System Preferences" every time I say anything unless I close it.

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  # Sytem Preferences
  SysPref=(is_running("System Preferences"))
  if SysPref == True:
    await message.channel.send("Someone has opened System Preferences!")

  if message.content.startswith("!close System_Preferences") and SysPref == True:
    os.system("pkill System Preferences")
    await message.channel.send("System Preferences closed!")
  elif message.content.startswith("!close System_Preferences") and SysPref == False:
    await message.channel.send("System Preferences is not open")

I used this AppleScript incorporated into Python from somewhere on stack overflow:

def is_runnning(app):
    count = int(subprocess.check_output(["osascript",
          "-e", "tell application \"System Events\"",
          "-e", "count (every process whose name is \"" + app + "\")",
          "-e", "end tell"]).strip())
return count > 0


问:
Getting confidence intervals for robust regression coefficient (MASS::rlm)
Is there any possible way to get 95% CI for regression coefficients from the robust regression, as implemented in MASS::rlm?

# libraries needed
library(MASS)
library(stats)
library(datasets)

# running robust regression
(x <-
  MASS::rlm(formula = scale(Sepal.Length) ~ scale(Sepal.Width),
            data = iris))
#> Call:
#> rlm(formula = scale(Sepal.Length) ~ scale(Sepal.Width), data = iris)
#> Converged in 5 iterations
#>
#> Coefficients:
#>        (Intercept) scale(Sepal.Width)
#>        -0.03728607        -0.14343268
#>
#> Degrees of freedom: 150 total; 148 residual
#> Scale estimate: 1.06

# getting confidence interval for the regression coefficient
stats::confint(object = x,
               parm = "scale(Sepal.Width)",
               level = 0.95)
#>                    2.5 % 97.5 %
#> scale(Sepal.Width)    NA     NA
```

答:
Late to the party, but note that CIs from the normal distribution will have lower than expected coverage for small sample sizes.

The residual degrees of freedom for the rlm object can be gotten from,

```<code>summary(x)$df[2]  # see code for MASS:::summary.rlm
</code>```

To write your own confint method for rlm results, assign the df to the df.residual slot, and then call confint.lm:

```<code>confint.rlm <- function(object, ...){
  object$df.residual <- MASS:::summary.rlm(object)$df[2]
  confint.lm(object, ...)
}
</code>```

Now confint behaves as expected, and is also based on Student's t:

```<code>confint(x)
                        2.5 %     97.5 %
(Intercept)        -0.2004593 0.12588715
scale(Sepal.Width) -0.3071526 0.02028719
</code>```

Body:
Late to the party, but note that CIs from the normal distribution will have lower than expected coverage for small sample sizes.

The residual degrees of freedom for the rlm object can be gotten from,

summary(x)$df[2]  # see code for MASS:::summary.rlm

To write your own confint method for rlm results, assign the df to the df.residual slot, and then call confint.lm:

confint.rlm <- function(object, ...){
  object$df.residual <- MASS:::summary.rlm(object)$df[2]
  confint.lm(object, ...)
}

Now confint behaves as expected, and is also based on Student's t:

confint(x)
                        2.5 %     97.5 %
(Intercept)        -0.2004593 0.12588715
scale(Sepal.Width) -0.3071526 0.02028719