问:
Does Spring boot Support Fast fail on Liquibase
From Spring DB Initialization docs, Spring boot DB initialization using Spring JDBC supports
feature Fast fail - that means if there are any issues in DB init script or migration scripts then Spring boot Context initialization failed. as result Spring boot server won't start.

now can we have this functionality when we use Advanced DB Migration tool like liquibase?

Spring Docs Doesn't say anything about this in liquibase section. Does this feature only works in Spring JDBC initialization?

答:
You can specify the desired behaviour using 'Preconditions'.

On default, it actually will fail fast, but you can overwrite it (example using SQL syntax):

```<code>-- preconditions onFail:WARN onError:WARN
</code>```

Available parameters:

HALT: Immediately halt the execution of the entire changelog. [DEFAULT]

  CONTINUE: Skip over the changeset. Execution of the change set will be
  attempted again on the next update. Continue with the changelog.

  MARK_RAN: Skip over the changeset, but mark it as executed. Continue
  with the changelog.   WARN    Output a warning and continue executing the
  changeset / changelog as normal.

see https://docs.liquibase.com/concepts/advanced/preconditions.html

Body:
You can specify the desired behaviour using 'Preconditions'.

On default, it actually will fail fast, but you can overwrite it (example using SQL syntax):

-- preconditions onFail:WARN onError:WARN

Available parameters:

HALT: Immediately halt the execution of the entire changelog. [DEFAULT]

  CONTINUE: Skip over the changeset. Execution of the change set will be
  attempted again on the next update. Continue with the changelog.

  MARK_RAN: Skip over the changeset, but mark it as executed. Continue
  with the changelog.   WARN    Output a warning and continue executing the
  changeset / changelog as normal.

see https://docs.liquibase.com/concepts/advanced/preconditions.html


来源: stackexchange

问:
Powershell cmdlet differences for the same operation
I have got three commands for the same operation from documentation.
These commands copies a file from azure data lake store to local machine.
I am not able to understand whether these are aliases or different commands.

Export-AdlStoreItem

Export-AzDataLakeStoreItem

Export-AzureRmDataLakeStoreItem

Please help

答:
The Export-AdlStoreItem is an alias of Export-AzDataLakeStoreItem, which belongs to the new Az powershell module Az.DataLakeStore.

Use this to check:

```<code>Get-Command Export-AdlStoreItem -ShowCommandInfo
</code>```

The Export-AzureRmDataLakeStoreItem belongs to the old AzureRm powrshell module AzureRM.DataLakeStore, it is a different command from the ones before.

ContentLicense: CC BY-SA 4.0

Body:
The Export-AdlStoreItem is an alias of Export-AzDataLakeStoreItem, which belongs to the new Az powershell module Az.DataLakeStore.

Use this to check:

Get-Command Export-AdlStoreItem -ShowCommandInfo

The Export-AzureRmDataLakeStoreItem belongs to the old AzureRm powrshell module AzureRM.DataLakeStore, it is a different command from the ones before.


Title: How to load csv data containing dates into a numpy array?

Body:
I tried different things for too long now.

How do I load csv data containing dates into a numpy array?
This is what doesn't work. It creates a single line with everything that is supposed to be a line now being in a single cell.

import io
import numpy as np
import datetime as dt

def date_parser(d_bytes):
    s = d_bytes.decode('utf-8')
    return np.datetime64(dt.datetime.strptime(s, "%Y-%m-%d %H:%M:%S"))

def read_csv():
    five_min_candles_str = """2020-06-01 17:05:00,9506.01,9523.31,9500.0,9514.52
2020-06-01 17:10:00,9513.44,9525.22,9500.32,9522.0
2020-06-01 17:15:00,9521.56,9525.59,9513.75,9523.53
2020-06-01 17:20:00,9523.21,9525.53,9518.78,9524.55
2020-06-01 17:25:00,9524.55,9538.4,9522.93,9528.73
2020-06-01 17:30:00,9528.73,9548.98,9527.95,9543.72
2020-06-01 17:35:00,9542.71,9547.34,9536.57,9543.66
2020-06-01 17:40:00,9543.67,9543.67,9530.0,9531.85
2020-06-01 17:45:00,9530.84,9535.01,9524.1,9526.75
2020-06-01 17:50:00,9526.47,9538.64,9521.87,9534.57
2020-06-01 17:55:00,9534.58,9548.9,9533.04,9546.98
2020-06-01 18:00:00,9548.18,9558.9,9536.99,9556.25
2020-06-01 18:05:00,9556.15,9579.8,9547.7,9574.09
2020-06-01 18:10:00,9575.0,9592.59,9571.3,9573.93
2020-06-01 18:15:00,9573.68,9610.0,9569.6,9597.78
2020-06-01 18:20:00,9597.78,9598.85,9578.0,9591.39
                """
    nparray = np.genfromtxt(io.StringIO(five_min_candles_str),
                            delimiter=',',
                            dtype=[('Timestamp','datetime64[us]'),
                                   ('Open','object'),
                                   ('High','object'),
                                   ('Low','object'),
                                   ('Close','object')],
                            converters={0: date_parser},
                            )
    print(nparray)

if __name__ == "__main__":
    read_csv()

A solution or hint would be much appreciated!

Edit:
It turned out that it was indeed working already but I expected an 2D array while it became an array of tuples after I've added the types or the converter. The reason for that are the different types in a row. See the other SO question

I marked the answer below as correct anyways as I like it more because it doesn't need any custom parsing of the date and I also like the splitlines() solution more compared to io.StringIO()

Body:
for completeness, this is pretty much a one-liner using pandas:

from  io import StringIO
import pandas as pd

s="""2020-06-01 17:05:00,9506.01,9523.31,9500.0,9514.52
2020-06-01 17:10:00,9513.44,9525.22,9500.32,9522.0
2020-06-01 17:15:00,9521.56,9525.59,9513.75,9523.53
2020-06-01 17:20:00,9523.21,9525.53,9518.78,9524.55
2020-06-01 17:25:00,9524.55,9538.4,9522.93,9528.73
2020-06-01 17:30:00,9528.73,9548.98,9527.95,9543.72
2020-06-01 17:35:00,9542.71,9547.34,9536.57,9543.66
2020-06-01 17:40:00,9543.67,9543.67,9530.0,9531.85
2020-06-01 17:45:00,9530.84,9535.01,9524.1,9526.75
2020-06-01 17:50:00,9526.47,9538.64,9521.87,9534.57
2020-06-01 17:55:00,9534.58,9548.9,9533.04,9546.98
2020-06-01 18:00:00,9548.18,9558.9,9536.99,9556.25
2020-06-01 18:05:00,9556.15,9579.8,9547.7,9574.09
2020-06-01 18:10:00,9575.0,9592.59,9571.3,9573.93
2020-06-01 18:15:00,9573.68,9610.0,9569.6,9597.78
2020-06-01 18:20:00,9597.78,9598.85,9578.0,9591.39"""

df = pd.read_csv(StringIO(s), names=['Timestamp','Open','High','Low','Close'],
                 parse_dates=[0])

for c in df.columns:
    print(f"{c} - {df[c].dtype}")
# Timestamp - datetime64[ns]
# Open - float64
# High - float64
# Low - float64
# Close - float64


问:
Shiny deployment error: upgrade GEOS to 3.6.0 or later while installing package ‘lwgeom’
I have a shiny app that runs fine on my computer. I use packages sf, leaflet, and tmap. One of these requires the package lwgeom as a dependency. While installing the package lwgeom, shiny deployment gives me the following error message. What is GEOS? And how can I upgrade GEOS to 3.6.0 or later?

```<code>Building R package: lwgeom (0.2-4)

/mnt/packages/build /mnt

* installing to library ‘/opt/R/4.0.0/lib/R/library’

* installing *source* package ‘lwgeom’ ...

** package ‘lwgeom’ successfully unpacked and MD5 sums checked

** using staged installation

configure: CC: gcc

configure: CXX: g++ -std=gnu++11

configure: pkg-config proj exists, will use it

configure: PROJ: 4.9.2

checking for pj_init_plus in -lproj... yes

checking PROJ: epsg found and readable... yes

configure: POSTGIS_PROJ_VERSION: 49

checking for geos-config... /usr/bin/geos-config

checking geos-config usability... yes

configure: GEOS: 3.5.1

checking GEOS version >= 3.6.0... no

configure: error: upgrade GEOS to 3.6.0 or later

ERROR: configuration failed for package ‘lwgeom’

* removing ‘/opt/R/4.0.0/lib/R/library/lwgeom’

################################# End Task Log #################################
Error: Unhandled Exception: Child Task 741115836 failed: Error building image: Error building lwgeom (0.2-4). Build exited with non-zero status: 1
Execution halted
</code>```

答:
From the lwgeom readme:

lwgeom depends on sf, which has to be installed first. This package uses the liblwgeom library, and compiles a shipped (and modified) version of liblwgeom. It links to the GEOS and PROJ libraries.

To install from source, it should be enough to have installed sf from source; the resources for this package (PROJ, GEOS) are being reused.

From the sf homepage

Simple Features for R

A package that provides simple features access for R. Package sf:

[snip]

interfaces to GEOS to support geometrical operations including the DE9-IM

That should answer your "What is GEOS?" question, but you might want to visit the GEOS homepage for a longer version.

In any case, you seem to be building lwgeom from source on Linux, so do read its install-from-source instructions. You'll probably want to upgrade the libgeos-dev system package, but the procedure to do so depends on your linux distribution. Let me quote the sf homepage once again, assuming you're running Ubuntu as your distro:

Ubuntu

[snip]

However, to get more up-to-date versions of dependencies such as GDAL, we recommend adding the ubuntugis-unstable PPA to the package repositories and installing them as follows:

```<code>sudo add-apt-repository ppa:ubuntugis/ubuntugis-unstable
sudo apt-get update
sudo apt-get install libudunits2-dev libgdal-dev libgeos-dev libproj-dev
</code>```

(It should be obvious that a different distro shall require a different method to install/upgrade system packages)

Body:
I have a shiny app that runs fine on my computer. I use packages sf, leaflet, and tmap. One of these requires the package lwgeom as a dependency. While installing the package lwgeom, shiny deployment gives me the following error message. What is GEOS? And how can I upgrade GEOS to 3.6.0 or later?

Building R package: lwgeom (0.2-4)

/mnt/packages/build /mnt

* installing to library ‘/opt/R/4.0.0/lib/R/library’

* installing *source* package ‘lwgeom’ ...

** package ‘lwgeom’ successfully unpacked and MD5 sums checked

** using staged installation

configure: CC: gcc

configure: CXX: g++ -std=gnu++11

configure: pkg-config proj exists, will use it

configure: PROJ: 4.9.2

checking for pj_init_plus in -lproj... yes

checking PROJ: epsg found and readable... yes

configure: POSTGIS_PROJ_VERSION: 49

checking for geos-config... /usr/bin/geos-config

checking geos-config usability... yes

configure: GEOS: 3.5.1

checking GEOS version >= 3.6.0... no

configure: error: upgrade GEOS to 3.6.0 or later

ERROR: configuration failed for package ‘lwgeom’

* removing ‘/opt/R/4.0.0/lib/R/library/lwgeom’

################################# End Task Log #################################
Error: Unhandled Exception: Child Task 741115836 failed: Error building image: Error building lwgeom (0.2-4). Build exited with non-zero status: 1
Execution halted

Body:
From the lwgeom readme:

lwgeom depends on sf, which has to be installed first. This package uses the liblwgeom library, and compiles a shipped (and modified) version of liblwgeom. It links to the GEOS and PROJ libraries.

To install from source, it should be enough to have installed sf from source; the resources for this package (PROJ, GEOS) are being reused.

From the sf homepage

Simple Features for R

A package that provides simple features access for R. Package sf:

[snip]

interfaces to GEOS to support geometrical operations including the DE9-IM

That should answer your "What is GEOS?" question, but you might want to visit the GEOS homepage for a longer version.

In any case, you seem to be building lwgeom from source on Linux, so do read its install-from-source instructions. You'll probably want to upgrade the libgeos-dev system package, but the procedure to do so depends on your linux distribution. Let me quote the sf homepage once again, assuming you're running Ubuntu as your distro:

Ubuntu

[snip]

However, to get more up-to-date versions of dependencies such as GDAL, we recommend adding the ubuntugis-unstable PPA to the package repositories and installing them as follows:

sudo add-apt-repository ppa:ubuntugis/ubuntugis-unstable
sudo apt-get update
sudo apt-get install libudunits2-dev libgdal-dev libgeos-dev libproj-dev

(It should be obvious that a different distro shall require a different method to install/upgrade system packages)


问:
Build mongodb docker image for arm64 raspberry pi 4 using official or bitnami mongodb docker image
I tried to install helm chart from bitnami/mongodb on arm64 raspberry pi 4 running Ubuntu 20.04 LTS 64bit. The container starts but then immediately terminates itself. I think it's because the mongodb image from bitnami isn't compatible with arm64 architecture.

How can I build mongodb or any other arm64 architecture compatible docker image or helm chart using the corresponding official docker image from x86_x64 laptop?

答:
I made it work by modifying helm chart to pull arm64 compatible image of mongodb. Here is the code:

```<code>helm install mongodb bitnami/mongodb
  --set image.repository=arm64v8/mongo
  --set image.tag=latest
  --set persistence.mountPath=/data/db
</code>```

These are the minimum set of config we need to override inorder to make it work. The rest of the environment parameters like --set mongodbRootPassword=<?> --set mongodbUsername=<?> --set mongodbPassword=<?> --set mongodbDatabase=<?> will not work on arm64v8/mongo image as these env params are bitnami/mongodb image specific. I suggest to modify bitnami/mongodb helm templete's to make it compatible with arm64v8/mongo environment variables

Body:
I made it work by modifying helm chart to pull arm64 compatible image of mongodb. Here is the code:

helm install mongodb bitnami/mongodb
  --set image.repository=arm64v8/mongo
  --set image.tag=latest
  --set persistence.mountPath=/data/db

These are the minimum set of config we need to override inorder to make it work. The rest of the environment parameters like --set mongodbRootPassword=<?> --set mongodbUsername=<?> --set mongodbPassword=<?> --set mongodbDatabase=<?> will not work on arm64v8/mongo image as these env params are bitnami/mongodb image specific. I suggest to modify bitnami/mongodb helm templete's to make it compatible with arm64v8/mongo environment variables


问:
How can I align my text/border to the center of my page with the
 element?

div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div1 style="font-size: 30px; text-align: center;">
    <b>Text here</b>
  </div1>
</body></code>```

I'm trying to align both my border and text to the center of my page, but somethings not working. If I haven't explained it well enough please ask for more details :). Here is the code:

HTML

```<code><body>
  <div1 style="font-size: 30px; text-align: center;">
    <b>Text here</b>
  </div1>
</body>
</code>```

CSS

```<code>div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }
</code>```

答:
you have some mistake in your code the tag name is div no div1 like you have there, if you change that you might see the result that you'r looking for!
I hope this help you!

Title: How can I align my text/border to the center of my page with the <div> element?

Body:
div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }

  <div1 style="font-size: 30px; text-align: center;">
    Text here
  </div1>

I'm trying to align both my border and text to the center of my page, but somethings not working. If I haven't explained it well enough please ask for more details :). Here is the code:

HTML

  <div1 style="font-size: 30px; text-align: center;">
    Text here
  </div1>

CSS

div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }


问:
Why does malloc/calloc fail to allocate memory to certain members in an array of structures?
I want some function (save()) to get a pointer to array of structures dbEntry and fill it with data. This is where memory management issues come in.

This is my code:

Structure itself:

```<code>typedef struct dbEntry {
          unsigned int id;
          char* type;
          char* name;
          unsigned int parent_id;
          unsigned char* md5;
} dbEntry;
</code>```

Memory allocation and calling save():

```<code>int main(int argc, char const* argv[]){
          if (argc != 5) arg_error();

          if (strcmp(argv[1], "-s") == 0){
              FILE* database = fopen(argv[2], "wb");
              if (database == NULL) file_error();
              dbEntry* entries = malloc(150*sizeof(dbEntry*));
              for (int i=0; i<150; i++){
                  entries[i].id = 0;
                  entries[i].parent_id = 0;
                  entries[i].name = malloc(50*sizeof(char));
                  entries[i].type = malloc(10*sizeof(char));
                  entries[i].md5 = malloc(MD5_DIGEST_LENGTH*sizeof(unsigned char));
              }
              int entry_num = save(argv[4], 0, &entries);
</code>```

save()

```<code>int save(char* dir_path, unsigned int parent, dbEntry** entries) {
          size_t path_len = strlen(dir_path);
          if (dir_path[path_len - 1] != '/') strcat(dir_path, "/");
          char dp_copy[path_len];
          strcpy(dp_copy, dir_path);
          DIR* dir = opendir(dir_path);
          struct dirent* dirent = readdir(dir);
          dirent = readdir(dir);
          dirent = readdir(dir);
          unsigned int id = 0;
          char* fpath;

          if (dirent == NULL) {
                  fprintf(stderr,
                          "Directory %s doesn't exist or can't be "
                          "opened. Check permissions\n",
                          dir_path);
                  exit(-1);
          }

          while (dirent != NULL) {
                  entries[id]->id = id;
                  strcpy(entries[id]->name, dirent->d_name);
                  entries[id]->parent_id = parent;

                  if (dirent->d_type == 8) {
                          strcpy(entries[id]->type, "file");
                          size_t len = strlen(dir_path)+strlen(dirent->d_name);
                          fpath = malloc(len);
                          strcpy(fpath, dir_path);
                          strcat(fpath, dirent->d_name);
                          FILE* file = fopen(fpath, "rb");
                          if (file == NULL){
                                  printf("Could not open file %s for reading\n", fpath);
                                  exit(-1);
                          }
                          md5digest(file, entries[id]->md5);
                          fclose(file);
                          printf("Saved %s\n", strcat(dir_path, dirent->d_name));

</code>```

GDB output:

```<code>57              while (dirent != NULL) {
(gdb) n
58                      entries[id]->id = id;
(gdb) n
59                      strcpy(entries[id]->name, dirent->d_name);
(gdb) n
60                      entries[id]->parent_id = parent;
(gdb) n
62                      if (dirent->d_type == 8) {
(gdb) n
63                              strcpy(entries[id]->type, "file");
(gdb) n
64                              size_t len = strlen(dir_path)+strlen(dirent->d_name);
(gdb) n
65                              fpath = malloc(len);
(gdb) n
66                              strcpy(fpath, dir_path);
(gdb) n
67                              strcat(fpath, dirent->d_name);
(gdb) p entries
$1 = (dbEntry **) 0x7ffffffee110
(gdb) p entries[0]
$2 = (dbEntry *) 0x8403490
(gdb) p entries[1]
$3 = (dbEntry *) 0x0
(gdb) p entries[2]
$4 = (dbEntry *) 0x8403260
(gdb) p entries[3]
$5 = (dbEntry *) 0xf625f4cc70b40b00
(gdb) p entries[4]
$6 = (dbEntry *) 0x7ffffffee220
(gdb) p entries[5]
$7 = (dbEntry *) 0x0
(gdb) p entries[6]
$8 = (dbEntry *) 0x8001890 <__libc_csu_init>
(gdb) p entries[7]
$9 = (dbEntry *) 0x7ffffeb51b97 <__libc_start_main+231>
(gdb) p entries[8]
$10 = (dbEntry *) 0x2000000000
(gdb) p entries[0]->name
$11 = 0x8403950 ".bash_history"
(gdb)
</code>```

For some reason, it failed to allocate memory for entries[1], entries[5] and some more, so the program returns Address boundary error when trying to reference entries[1].

Tried almost everything, but the issue persists. Looking for your help.

答:
You have two problems:

With

```<code>malloc(150*sizeof(dbEntry*))
</code>```

you allocate memory for 150 pointers to dbEntry structures, not
the dbEntry structures themselves.

I recommend that you get the size of the data to allocate from the
variable itself, as in:

```<code>dbEntry *entries = malloc(150 * sizeof *entries);
</code>```

In the save function the variable entries is essentially a pointer to an array of dbEntry structures. You treat it as an array of pointers to structures (a pointer to an array is not the same as an array of pointers). You need to dereference the pointer to get the original pointer, which can then be dereferenced like an array of structures:

```<code>(*entries)[id].id = id;
</code>```

Or simply not pass it as a pointer to a pointer:

```<code>//                                       Note only one asterisk
//                                                   v
int save(char* dir_path, unsigned int parent, dbEntry* entries) {
    ...
    entries[id].id = id;  // Entries can be treated like a normal array of structures
    ...
}
</code>```

Body:
I want some function (save()) to get a pointer to array of structures dbEntry and fill it with data. This is where memory management issues come in.

This is my code:

Structure itself:

typedef struct dbEntry {
          unsigned int id;
          char* type;
          char* name;
          unsigned int parent_id;
          unsigned char* md5;
} dbEntry;

Memory allocation and calling save():

int main(int argc, char const* argv[]){
          if (argc != 5) arg_error();

          if (strcmp(argv[1], "-s") == 0){
              FILE* database = fopen(argv[2], "wb");
              if (database == NULL) file_error();
              dbEntry* entries = malloc(150*sizeof(dbEntry*));
              for (int i=0; i<150; i++){
                  entries[i].id = 0;
                  entries[i].parent_id = 0;
                  entries[i].name = malloc(50*sizeof(char));
                  entries[i].type = malloc(10*sizeof(char));
                  entries[i].md5 = malloc(MD5_DIGEST_LENGTH*sizeof(unsigned char));
              }
              int entry_num = save(argv[4], 0, &entries);

save()

int save(char* dir_path, unsigned int parent, dbEntry** entries) {
          size_t path_len = strlen(dir_path);
          if (dir_path[path_len - 1] != '/') strcat(dir_path, "/");
          char dp_copy[path_len];
          strcpy(dp_copy, dir_path);
          DIR* dir = opendir(dir_path);
          struct dirent* dirent = readdir(dir);
          dirent = readdir(dir);
          dirent = readdir(dir);
          unsigned int id = 0;
          char* fpath;

          if (dirent == NULL) {
                  fprintf(stderr,
                          "Directory %s doesn't exist or can't be "
                          "opened. Check permissions\n",
                          dir_path);
                  exit(-1);
          }

          while (dirent != NULL) {
                  entries[id]->id = id;
                  strcpy(entries[id]->name, dirent->d_name);
                  entries[id]->parent_id = parent;

                  if (dirent->d_type == 8) {
                          strcpy(entries[id]->type, "file");
                          size_t len = strlen(dir_path)+strlen(dirent->d_name);
                          fpath = malloc(len);
                          strcpy(fpath, dir_path);
                          strcat(fpath, dirent->d_name);
                          FILE* file = fopen(fpath, "rb");
                          if (file == NULL){
                                  printf("Could not open file %s for reading\n", fpath);
                                  exit(-1);
                          }
                          md5digest(file, entries[id]->md5);
                          fclose(file);
                          printf("Saved %s\n", strcat(dir_path, dirent->d_name));

GDB output:

57              while (dirent != NULL) {
(gdb) n
58                      entries[id]->id = id;
(gdb) n
59                      strcpy(entries[id]->name, dirent->d_name);
(gdb) n
60                      entries[id]->parent_id = parent;
(gdb) n
62                      if (dirent->d_type == 8) {
(gdb) n
63                              strcpy(entries[id]->type, "file");
(gdb) n
64                              size_t len = strlen(dir_path)+strlen(dirent->d_name);
(gdb) n
65                              fpath = malloc(len);
(gdb) n
66                              strcpy(fpath, dir_path);
(gdb) n
67                              strcat(fpath, dirent->d_name);
(gdb) p entries
$1 = (dbEntry **) 0x7ffffffee110
(gdb) p entries[0]
$2 = (dbEntry *) 0x8403490
(gdb) p entries[1]
$3 = (dbEntry *) 0x0
(gdb) p entries[2]
$4 = (dbEntry *) 0x8403260
(gdb) p entries[3]
$5 = (dbEntry *) 0xf625f4cc70b40b00
(gdb) p entries[4]
$6 = (dbEntry *) 0x7ffffffee220
(gdb) p entries[5]
$7 = (dbEntry *) 0x0
(gdb) p entries[6]
$8 = (dbEntry *) 0x8001890 <__libc_csu_init>
(gdb) p entries[7]
$9 = (dbEntry *) 0x7ffffeb51b97 <__libc_start_main+231>
(gdb) p entries[8]
$10 = (dbEntry *) 0x2000000000
(gdb) p entries[0]->name
$11 = 0x8403950 ".bash_history"
(gdb)

For some reason, it failed to allocate memory for entries[1], entries[5] and some more, so the program returns Address boundary error when trying to reference entries[1].

Tried almost everything, but the issue persists. Looking for your help.

Body:
You have two problems:

With

malloc(150*sizeof(dbEntry*))

you allocate memory for 150 pointers to dbEntry structures, not
the dbEntry structures themselves.

I recommend that you get the size of the data to allocate from the
variable itself, as in:

dbEntry *entries = malloc(150 * sizeof *entries);

In the save function the variable entries is essentially a pointer to an array of dbEntry structures. You treat it as an array of pointers to structures (a pointer to an array is not the same as an array of pointers). You need to dereference the pointer to get the original pointer, which can then be dereferenced like an array of structures:

(*entries)[id].id = id;

Or simply not pass it as a pointer to a pointer:

//                                       Note only one asterisk
//                                                   v
int save(char* dir_path, unsigned int parent, dbEntry* entries) {
    ...
    entries[id].id = id;  // Entries can be treated like a normal array of structures
    ...
}


问:
How to implement resource files localization ASP-NET.core?
I am asked to implement localization in a net.core solution as following:

Resource files must be in a separated project (like "MyProject.Common") to be used in all other projects in the solution,

Resources must be split by "sections", for example, we have 3 areas in the Web project like following :

Users,

Content,

Administration,

So I'm asked to have something like:

UsersResources.fr-CA.resx,

UsersResources.en-CA.resx,

ContentResources.fr-Ca.resx,

...

I started to read documentation for Localization is AP-NET core and I'm a bit confused on how itr works.
Doesn't seem like what i'm told to do is possible.

Thing is, I may need to use resources in Business, Views and Controllers so I'm searching for a way to implement it so the team could use the old way, by calling ContentResources.MyCustomResource.

Is there a way to get close from that?

I found a post where someone was mentioning https://www.nuget.org/packages/ResXResourceReader.NetStandard.

But I don't know if it will fit my needs...

#EDIT :
So, trying to implement Laz's solution for shared resources.

So far, in startup I have this :
in ConfigureServices :

```<code>services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddDataAnnotationsLocalization(options => {
                            options.DataAnnotationLocalizerProvider = (type, factory) =>
                            factory.Create(typeof(SharedResources));

services.AddLocalization();

services.Configure<RequestLocalizationOptions>(
            opts =>
            {
                    /* your configurations*/
                    var supportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("en"),
                        new CultureInfo("fr")
                    };
                opts.DefaultRequestCulture = new RequestCulture("fr", "fr");
                opts.SupportedCultures = supportedCultures;
                opts.SupportedUICultures = supportedCultures;
            }
        );

</code>```

and in Configure :

```<code>app.UseRequestLocalization();
// used to force culture to fr but doen't seem to work
var cultureInfo = new CultureInfo("fr");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
</code>```

in MyProject.Common, I have this structure:

```<code>MyProject.Common
-Resources
 --SharedResources.cs
  ---SharedResources.fr.resx
  ---SharedResources.en.resx
 --UsersResources.cs
  ---UsersResources.fr.resx
  ---UsersResources.en.resx
</code>```

Let's say I want to use SharedResources.

In SharedResources.en.resx I added resources:

In SharedResources.fr.resx I added resources:

Now in my UserService, in Business layer, I did this:

```<code> private readonly IStringLocalizer Localizer;

    public UserService(IStringLocalizerFactory factory)
    {
        var type = typeof(SharedResources);
        var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
        _localizer = factory.Create(type);
    }

    public void Test()
    {
        var test = Localizer["Test"]; //using the key of resources file i want
    }
</code>```

but all I get as a result in test variable is "Test", which is the key of the resource, and not the value.

答:
The default localization setup of .net core can be based on one shared resource file or based on the class name.

In your case, you can use the shared resource approach, but you have to create the cutomized localizer in each controller/class by providing the factory with the desired resource type.

First create a class library with the desired resources, create a public dummy class for each resource type you want, so the class library structure can be like below:

```<code>// SharedResourcesLibrary.csproj

- UsersResources.cs
 - UsersResources.fr-ca.resx
 - UsersResources.en-ca.resx

- ContentResources.cs
  - ContentResources.fr-ca.resx
  - ContentResources.en-ca.resx

...

</code>```

The dummy classes are empty, they are used just as a type to call the relevant resx file.

// Dummy users resources class
public class UsersResources { }
```

<p>Then after referencing the ResourcesLibrary project into other projects, you can use the resources by calling the relevant resource type (the dummy class).:</p>

<pre class="lang-cs prettyprint-override"><code>using SharedResourcesLibrary;

public class UsersController : Controller
{
    private readonly IStringLocalizer _localizer;

    public UsersController(IStringLocalizerFactory factory)
    {
        var type = typeof(UsersResources);
        _localizer = factory.Create(type);
    }

    public IActionResult About()
    {
         ViewData["Message"] = _localizer["Welcome."];
    }
}
</code>```

To use other resources just create the localizer using the relevant resource type.

Another approach can be done by creating custom multiple IStringLocalizers according to your areas, then inject them in the controllers.

// Create one localizer for each area
public class UsersLocalizer : IStringLocalizer
{
    private readonly IStringLocalizer _localizer;

    public UsersLocalizer(IStringLocalizerFactory factory)
    {
        var type = typeof(UsersResources);
        var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
        _localizer = factory.Create(type);
    }

    public LocalizedString this[string name] => _localizer[name];

    public LocalizedString this[string name, params object[] arguments] => _localizer[name, arguments];

    // ...
}
```

<p>Similarly you can create localizers for other areas... then register in startup:</p>

<pre class="lang-cs prettyprint-override"><code>services.AddTransient<IStringLocalizer, UsersLocalizer>();
services.AddTransient<IStringLocalizer, AdminsLocalizer>();
services.AddTransient<IStringLocalizer, ContentLocalizer>();
// ...
</code>```

This way all localizers will be registered, and if you simply inject IStringLocalizer it will get the last registered one, because all localizers are implementing the same IStringLocalizer interface.

So you have to do type selection for injecting the correct localizer:

public UsersController : Controller
{
    private readonly IStringLocalizer _localizer;

    public UsersController(IEnumerable<IStringLocalizer> localizers)
    {
        _localizer = localizers.FirstOrDefault(x => x.GetType() == typeof(UsersLocalizer));
    }

    public IActionResult About()
    {
        ViewData["Message"] = _localizer["Welcome."];
    }
}
```

You can refere to this article for different ways of Registering multiple implementation with the same interface in Asp.Net Core

Body:
I am asked to implement localization in a net.core solution as following:

Resource files must be in a separated project (like "MyProject.Common") to be used in all other projects in the solution,

Resources must be split by "sections", for example, we have 3 areas in the Web project like following :

Users,

Content,

Administration,

So I'm asked to have something like:

UsersResources.fr-CA.resx,

UsersResources.en-CA.resx,

ContentResources.fr-Ca.resx,

...

I started to read documentation for Localization is AP-NET core and I'm a bit confused on how itr works.
Doesn't seem like what i'm told to do is possible.

Thing is, I may need to use resources in Business, Views and Controllers so I'm searching for a way to implement it so the team could use the old way, by calling ContentResources.MyCustomResource.

Is there a way to get close from that?

I found a post where someone was mentioning https://www.nuget.org/packages/ResXResourceReader.NetStandard.

But I don't know if it will fit my needs...

#EDIT :
So, trying to implement Laz's solution for shared resources.

So far, in startup I have this :
in ConfigureServices :

services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddDataAnnotationsLocalization(options => {
                            options.DataAnnotationLocalizerProvider = (type, factory) =>
                            factory.Create(typeof(SharedResources));

services.AddLocalization();

services.Configure<RequestLocalizationOptions>(
            opts =>
            {
                    /* your configurations*/
                    var supportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("en"),
                        new CultureInfo("fr")
                    };
                opts.DefaultRequestCulture = new RequestCulture("fr", "fr");
                opts.SupportedCultures = supportedCultures;
                opts.SupportedUICultures = supportedCultures;
            }
        );

and in Configure :

app.UseRequestLocalization();
// used to force culture to fr but doen't seem to work
var cultureInfo = new CultureInfo("fr");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

in MyProject.Common, I have this structure:

MyProject.Common
-Resources
 --SharedResources.cs
  ---SharedResources.fr.resx
  ---SharedResources.en.resx
 --UsersResources.cs
  ---UsersResources.fr.resx
  ---UsersResources.en.resx

Let's say I want to use SharedResources.

In SharedResources.en.resx I added resources:

In SharedResources.fr.resx I added resources:

Now in my UserService, in Business layer, I did this:

 private readonly IStringLocalizer Localizer;

    public UserService(IStringLocalizerFactory factory)
    {
        var type = typeof(SharedResources);
        var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
        _localizer = factory.Create(type);
    }

    public void Test()
    {
        var test = Localizer["Test"]; //using the key of resources file i want
    }

but all I get as a result in test variable is "Test", which is the key of the resource, and not the value.

Body:
The default localization setup of .net core can be based on one shared resource file or based on the class name.

In your case, you can use the shared resource approach, but you have to create the cutomized localizer in each controller/class by providing the factory with the desired resource type.

First create a class library with the desired resources, create a public dummy class for each resource type you want, so the class library structure can be like below:

// SharedResourcesLibrary.csproj

- UsersResources.cs
 - UsersResources.fr-ca.resx
 - UsersResources.en-ca.resx

- ContentResources.cs
  - ContentResources.fr-ca.resx
  - ContentResources.en-ca.resx

...

The dummy classes are empty, they are used just as a type to call the relevant resx file.

// Dummy users resources class
public class UsersResources { }

Then after referencing the ResourcesLibrary project into other projects, you can use the resources by calling the relevant resource type (the dummy class).:

using SharedResourcesLibrary;

public class UsersController : Controller
{
    private readonly IStringLocalizer _localizer;

    public UsersController(IStringLocalizerFactory factory)
    {
        var type = typeof(UsersResources);
        _localizer = factory.Create(type);
    }

    public IActionResult About()
    {
         ViewData["Message"] = _localizer["Welcome."];
    }
}

To use other resources just create the localizer using the relevant resource type.

Another approach can be done by creating custom multiple IStringLocalizers according to your areas, then inject them in the controllers.

// Create one localizer for each area
public class UsersLocalizer : IStringLocalizer
{
    private readonly IStringLocalizer _localizer;

    public UsersLocalizer(IStringLocalizerFactory factory)
    {
        var type = typeof(UsersResources);
        var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
        _localizer = factory.Create(type);
    }

    public LocalizedString this[string name] => _localizer[name];

    public LocalizedString this[string name, params object[] arguments] => _localizer[name, arguments];

    // ...
}

Similarly you can create localizers for other areas... then register in startup:

services.AddTransient<IStringLocalizer, UsersLocalizer>();
services.AddTransient<IStringLocalizer, AdminsLocalizer>();
services.AddTransient<IStringLocalizer, ContentLocalizer>();
// ...

This way all localizers will be registered, and if you simply inject IStringLocalizer it will get the last registered one, because all localizers are implementing the same IStringLocalizer interface.

So you have to do type selection for injecting the correct localizer:

public UsersController : Controller
{
    private readonly IStringLocalizer _localizer;

    public UsersController(IEnumerable<IStringLocalizer> localizers)
    {
        _localizer = localizers.FirstOrDefault(x => x.GetType() == typeof(UsersLocalizer));
    }

    public IActionResult About()
    {
        ViewData["Message"] = _localizer["Welcome."];
    }
}

You can refere to this article for different ways of Registering multiple implementation with the same interface in Asp.Net Core


问:
How to pass params from one screen to another via reactnavigation v5
I have an issue: thre is a list of users, and I want to add appointment to any user, so on user screen a PlusButton sending user on the add appointment screen (the PlusButton rendered from headerRight of the user screen). BUT I dont know how to pass to AddAppointmentScreen users id, because link to screen not via button, its via react-navigation v5.

here is a link to my project on github

App.js

```<code>const HeaderRight = ({ navigation, target }) => {
    return (
        <Button transparent onPress={() => navigation.navigate(target)}>
            <Icon name='plus' type='Entypo' style={{ fontSize: 26 }} />
        </Button>
    )
}

<Stack.Screen
                name='Patient'
                component={PatientScreen}
                options={{
                    title: 'Карта пациента',
                    headerTintColor: '#2A86FF',
                    headerTitleAlign: 'center',
                    headerTitleStyle: {
                        fontWeight: 'bold',
                        fontSize: 20,
                    },
                    headerBackTitleVisible: false,
                    headerRight: () => <HeaderRight navigation={navigation} target={'AddAppointment'} />,
                }}
/>
</code>```

AddAppointmentScreen.js

```<code>import React, { useState } from 'react'
import { Keyboard } from 'react-native'
import { Container, Content, Form, Item, Input, Label, Icon, Text, Button } from 'native-base'
import DateTimePicker from '@react-native-community/datetimepicker'
import styled from 'styled-components/native'

import { appointmentsApi } from '../utils/api'

const AddAppointmentScreen = ({ route, navigation }) => {
    const [values, setValues] = useState({ patientId: route.params?.patientId._id ?? 'defaultValue' })
    const [date, setDate] = useState(new Date())
    const [mode, setMode] = useState('date')
    const [show, setShow] = useState(false)

    console.log(values.patientId)
    //I need to get patientId in this screen to create appointment to THIS user with its ID

    const setFieldValue = (name, value) => {
        setValues({
            ...values,
            [name]: value,
        })
    }

    const handleChange = (name, e) => {
        const text = e.nativeEvent.text
        setFieldValue(name, text)
    }

    const submitHandler = () => {
        appointmentsApi
            .add(values)
            .then(() => {
                navigation.navigate('Patient')
            })
            .catch((e) => {
                alert(e)
            })
        /* alert(JSON.stringify(values)) */
    }

    const formatDate = (date) => {
        var d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear()

        if (month.length < 2) month = '0' + month
        if (day.length < 2) day = '0' + day

        return [year, month, day].join('-')
    }

    const onChange = (event, selectedDate) => {
        Keyboard.dismiss()
        const currentDate = selectedDate || date
        const date = formatDate(currentDate)
        const time = currentDate.toTimeString().split(' ')[0].slice(0, 5)
        setShow(Platform.OS === 'ios')
        setDate(currentDate)
        setValues({
            ...values,
            ['date']: date,
            ['time']: time,
        })
    }

    const showMode = (currentMode) => {
        show ? setShow(false) : setShow(true)
        setMode(currentMode)
    }

    const showDatepicker = () => {
        Keyboard.dismiss()
        showMode('datetime')
    }

    return (
        <Container>
            <Content style={{ paddingLeft: 20, paddingRight: 20 }}>
                <Form>
                    <Item picker style={{ borderWidth: 0 }} /* floatingLabel */>
                        <Input
                            onChange={handleChange.bind(this, 'dentNumber')}
                            value={values.dentNumber}
                            keyboardType='number-pad'
                            clearButtonMode='while-editing'
                            placeholder='* Номер зуба'
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'diagnosis')}
                            value={values.diagnosis}
                            clearButtonMode='while-editing'
                            placeholder='* Диагноз'
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'description')}
                            value={values.description}
                            multiline
                            clearButtonMode='while-editing'
                            placeholder='Подробное описание или заметка'
                            style={{ paddingTop: 15, paddingBottom: 15 }}
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'price')}
                            value={values.price}
                            keyboardType='number-pad'
                            clearButtonMode='while-editing'
                            placeholder='* Цена'
                        />
                    </Item>

                    <ButtonRN onPress={showDatepicker}>
                        <Text style={{ fontSize: 18, fontWeight: '400' }}>
                            Дата: {formatDate(date)}, время: {date.toTimeString().split(' ')[0].slice(0, 5)}
                        </Text>
                    </ButtonRN>

                    {show && (
                        <DateTimePicker
                            timeZoneOffsetInSeconds={21600}
                            minimumDate={new Date()}
                            value={date}
                            mode={mode}
                            is24Hour={true}
                            display='default'
                            locale='ru-RU'
                            minuteInterval={10}
                            onChange={onChange}
                        />
                    )}

                    <ButtonView>
                        <Button
                            onPress={submitHandler}
                            rounded
                            block
                            iconLeft
                            style={{ backgroundColor: '#84D269' }}
                        >
                            <Icon type='Entypo' name='plus' style={{ color: '#fff' }} />
                            <Text style={{ color: '#fff' }}>Добавить прием</Text>
                        </Button>
                    </ButtonView>
                    <Label style={{ marginTop: 10, fontSize: 16 }}>
                        Поля помеченные звездочкой <TomatoText>*</TomatoText> обязательны для заполнения
                    </Label>
                </Form>
            </Content>
        </Container>
    )
}

const ButtonRN = styled.TouchableOpacity({
    paddingTop: 15,
    paddingLeft: 5,
})

const ButtonView = styled.View({
    marginTop: 15,
})

const TomatoText = styled.Text({
    color: 'tomato',
})

export default AddAppointmentScreen
</code>```

答:
This can be done using the useNavigation hook as you are inside the Navigation Container.

```<code>import { NavigationContainer, useNavigation } from '@react-navigation/native';
const HeaderRight = ({ navigation, target }) => {
  const navigation = useNavigation();
    return (
        <Button transparent onPress={() => navigation.navigate(target)}>
            <Icon name='plus' type='Entypo' style={{ fontSize: 26 }} />
        </Button>
    )
}
</code>```

And you have to pass the target like below, as navigation is not accessible from there there is no point on passing that anyway.

```<code>headerRight: () => <HeaderRight target={'Profile'} />,
</code>```

Hope this helps.

Body:
I have an issue: thre is a list of users, and I want to add appointment to any user, so on user screen a PlusButton sending user on the add appointment screen (the PlusButton rendered from headerRight of the user screen). BUT I dont know how to pass to AddAppointmentScreen users id, because link to screen not via button, its via react-navigation v5.

here is a link to my project on github

App.js

const HeaderRight = ({ navigation, target }) => {
    return (
        <Button transparent onPress={() => navigation.navigate(target)}>
            <Icon name='plus' type='Entypo' style={{ fontSize: 26 }} />
        </Button>
    )
}

<Stack.Screen
                name='Patient'
                component={PatientScreen}
                options={{
                    title: 'Карта пациента',
                    headerTintColor: '#2A86FF',
                    headerTitleAlign: 'center',
                    headerTitleStyle: {
                        fontWeight: 'bold',
                        fontSize: 20,
                    },
                    headerBackTitleVisible: false,
                    headerRight: () => <HeaderRight navigation={navigation} target={'AddAppointment'} />,
                }}
/>

AddAppointmentScreen.js

import React, { useState } from 'react'
import { Keyboard } from 'react-native'
import { Container, Content, Form, Item, Input, Label, Icon, Text, Button } from 'native-base'
import DateTimePicker from '@react-native-community/datetimepicker'
import styled from 'styled-components/native'

import { appointmentsApi } from '../utils/api'

const AddAppointmentScreen = ({ route, navigation }) => {
    const [values, setValues] = useState({ patientId: route.params?.patientId._id ?? 'defaultValue' })
    const [date, setDate] = useState(new Date())
    const [mode, setMode] = useState('date')
    const [show, setShow] = useState(false)

    console.log(values.patientId)
    //I need to get patientId in this screen to create appointment to THIS user with its ID

    const setFieldValue = (name, value) => {
        setValues({
            ...values,
            [name]: value,
        })
    }

    const handleChange = (name, e) => {
        const text = e.nativeEvent.text
        setFieldValue(name, text)
    }

    const submitHandler = () => {
        appointmentsApi
            .add(values)
            .then(() => {
                navigation.navigate('Patient')
            })
            .catch((e) => {
                alert(e)
            })
        /* alert(JSON.stringify(values)) */
    }

    const formatDate = (date) => {
        var d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear()

        if (month.length < 2) month = '0' + month
        if (day.length < 2) day = '0' + day

        return [year, month, day].join('-')
    }

    const onChange = (event, selectedDate) => {
        Keyboard.dismiss()
        const currentDate = selectedDate || date
        const date = formatDate(currentDate)
        const time = currentDate.toTimeString().split(' ')[0].slice(0, 5)
        setShow(Platform.OS === 'ios')
        setDate(currentDate)
        setValues({
            ...values,
            ['date']: date,
            ['time']: time,
        })
    }

    const showMode = (currentMode) => {
        show ? setShow(false) : setShow(true)
        setMode(currentMode)
    }

    const showDatepicker = () => {
        Keyboard.dismiss()
        showMode('datetime')
    }

    return (
        <Container>
            <Content style={{ paddingLeft: 20, paddingRight: 20 }}>
                <Form>
                    <Item picker style={{ borderWidth: 0 }} /* floatingLabel */>
                        <Input
                            onChange={handleChange.bind(this, 'dentNumber')}
                            value={values.dentNumber}
                            keyboardType='number-pad'
                            clearButtonMode='while-editing'
                            placeholder='* Номер зуба'
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'diagnosis')}
                            value={values.diagnosis}
                            clearButtonMode='while-editing'
                            placeholder='* Диагноз'
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'description')}
                            value={values.description}
                            multiline
                            clearButtonMode='while-editing'
                            placeholder='Подробное описание или заметка'
                            style={{ paddingTop: 15, paddingBottom: 15 }}
                        />
                    </Item>
                    <Item picker>
                        <Input
                            onChange={handleChange.bind(this, 'price')}
                            value={values.price}
                            keyboardType='number-pad'
                            clearButtonMode='while-editing'
                            placeholder='* Цена'
                        />
                    </Item>

                    <ButtonRN onPress={showDatepicker}>
                        <Text style={{ fontSize: 18, fontWeight: '400' }}>
                            Дата: {formatDate(date)}, время: {date.toTimeString().split(' ')[0].slice(0, 5)}
                        </Text>
                    </ButtonRN>

                    {show && (
                        <DateTimePicker
                            timeZoneOffsetInSeconds={21600}
                            minimumDate={new Date()}
                            value={date}
                            mode={mode}
                            is24Hour={true}
                            display='default'
                            locale='ru-RU'
                            minuteInterval={10}
                            onChange={onChange}
                        />
                    )}

                    <ButtonView>
                        <Button
                            onPress={submitHandler}
                            rounded
                            block
                            iconLeft
                            style={{ backgroundColor: '#84D269' }}
                        >
                            <Icon type='Entypo' name='plus' style={{ color: '#fff' }} />
                            <Text style={{ color: '#fff' }}>Добавить прием</Text>
                        </Button>
                    </ButtonView>

                        Поля помеченные звездочкой <TomatoText>*</TomatoText> обязательны для заполнения

                </Form>
            </Content>
        </Container>
    )
}

const ButtonRN = styled.TouchableOpacity({
    paddingTop: 15,
    paddingLeft: 5,
})

const ButtonView = styled.View({
    marginTop: 15,
})

const TomatoText = styled.Text({
    color: 'tomato',
})

export default AddAppointmentScreen

Body:
This can be done using the useNavigation hook as you are inside the Navigation Container.

import { NavigationContainer, useNavigation } from '@react-navigation/native';
const HeaderRight = ({ navigation, target }) => {
  const navigation = useNavigation();
    return (
        <Button transparent onPress={() => navigation.navigate(target)}>
            <Icon name='plus' type='Entypo' style={{ fontSize: 26 }} />
        </Button>
    )
}

And you have to pass the target like below, as navigation is not accessible from there there is no point on passing that anyway.

headerRight: () => <HeaderRight target={'Profile'} />,

Hope this helps.


问:
How do you return a JSON object from a Java Servlet
How do you return a JSON object form a Java servlet.

Previously when doing AJAX with a servlet I have returned a string. Is there a JSON object type that needs to be used, or do you just return a String that looks like a JSON object e.g.

```<code>String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
</code>```

答:
You may use bellow like.

If you want use json array:

download  json-simple-1.1.1.jar & add to your project class path

Create A class named Model like bellow

```<code>public class Model {

 private String id = "";
 private String name = "";

 //getter sertter here
}
</code>```

In sevlet getMethod you can use like bellow

```<code>@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

  //begin get data from databse or other source
  List<Model> list = new ArrayList<>();
  Model model = new Model();
  model.setId("101");
  model.setName("Enamul Haque");
  list.add(model);

  Model model1 = new Model();
  model1.setId("102");
  model1.setName("Md Mohsin");
  list.add(model1);
  //End get data from databse or other source
try {

    JSONArray ja = new JSONArray();
    for (Model m : list) {
        JSONObject jSONObject = new JSONObject();
        jSONObject.put("id", m.getId());
        jSONObject.put("name", m.getName());
        ja.add(jSONObject);
    }
    System.out.println(" json ja = " + ja);
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().print(ja.toString());
    response.getWriter().flush();
   } catch (Exception e) {
     e.printStackTrace();
  }

 }
</code>```

Output:

```<code>    [{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]
</code>```

I you want json Object just use like:

```<code>@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {

        JSONObject json = new JSONObject();
        json.put("id", "108");
        json.put("name", "Enamul Haque");
        System.out.println(" json JSONObject= " + json);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        // System.out.println("Response Completed... ");
    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

Above function Output:

```<code>{"name":"Enamul Haque","id":"108"}
</code>```

Full source is given to GitHub: https://github.com/enamul95/ServeletJson.git

ContentLicense: CC BY-SA 3.0

Body:
How do you return a JSON object form a Java servlet.

Previously when doing AJAX with a servlet I have returned a string. Is there a JSON object type that needs to be used, or do you just return a String that looks like a JSON object e.g.

String objectToReturn = "{ key1: 'value1', key2: 'value2' }";

Body:
You may use bellow like.

If you want use json array:

download  json-simple-1.1.1.jar & add to your project class path

Create A class named Model like bellow

public class Model {

 private String id = "";
 private String name = "";

 //getter sertter here
}

In sevlet getMethod you can use like bellow

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

  //begin get data from databse or other source
  List<Model> list = new ArrayList<>();
  Model model = new Model();
  model.setId("101");
  model.setName("Enamul Haque");
  list.add(model);

  Model model1 = new Model();
  model1.setId("102");
  model1.setName("Md Mohsin");
  list.add(model1);
  //End get data from databse or other source
try {

    JSONArray ja = new JSONArray();
    for (Model m : list) {
        JSONObject jSONObject = new JSONObject();
        jSONObject.put("id", m.getId());
        jSONObject.put("name", m.getName());
        ja.add(jSONObject);
    }
    System.out.println(" json ja = " + ja);
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().print(ja.toString());
    response.getWriter().flush();
   } catch (Exception e) {
     e.printStackTrace();
  }

 }

Output:

    [{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]

I you want json Object just use like:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {

        JSONObject json = new JSONObject();
        json.put("id", "108");
        json.put("name", "Enamul Haque");
        System.out.println(" json JSONObject= " + json);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        // System.out.println("Response Completed... ");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Above function Output:

{"name":"Enamul Haque","id":"108"}

Full source is given to GitHub: https://github.com/enamul95/ServeletJson.git


问:
DateTime.Now vs. DateTime.UtcNow
I've been wondering what exactly are the principles of how the two properties work. I know the second one is universal and basically doesn't deal with time zones, but can someone explain in detail how they work and which one should be used in what scenario?</p>

答:
When you need a local time for the machine your application runs at (like CEST for Europe), use Now. If you want a universal time - UtcNow. It's just matter of your preferences - probably making a local website / standalone application you'd want to use the time user has - so affected by his/her timezone setting - DateTime.Now.

Just remember, for a website it's the timezone setting of the server. So if you're displaying the time for the user, either get his prefered timezone and shift the time (just save Utc time to database then, and modify it) or specify it's UTC. If you forget to do so, user can see something like: posted 3 minuses ago and then a time in the future near it :)

OwnerDisplayName: Slavo

ContentLicense: CC BY-SA 2.5

Title: DateTime.Now vs. DateTime.UtcNow

LastEditorDisplayName: Jedi Master Spooky

OwnerDisplayName: Pawel


问:
how to upload a parquet file into Azure ADLS 2 Blob
Hi i want to upload Parquet files to ADLS gen 2 blob. I am using below line of code to create blob and upload parquet file in it.

```<code>blob = BlobClient.from_connection_string(conn_str="Connection String", container_name="parquet", blob_name=outdir)
df.to_parquet('logs.parquet',compression='GZIP') #df is dataframe
with open("./logs.parquet", "rb") as data:
blob.upload_blob(data)
os.remove("logs.parquet")
</code>```

i do not face any error and the files are also written in the blob. But , i don't think i am doing it right as ADX/kusto query can not understand the file and no data is visible there.

Below are the steps i performed in Azure Data Explorer to fetch records from uploaded parquet file in ADLS gen 2.

Created External Table:

```<code>.create external table LogDataParquet(AppId_s:string,UserId_g:string,Email_s:string,RoleName_s:string,Operation_s:string,EntityId_s:string,EntityType_s:string,EntityName_s:string,TargetTitle_s:string,TimeGenerated:datetime)
kind=blob
dataformat=parquet
(
   h@'https://streamoutalds2.blob.core.windows.net/stream-api-raw-testing;secret'
)
with
(
   folder = "ExternalTables"
)
</code>```

External Table Column Mapping :

```<code>.create external table LogDataParquet parquet mapping "LogDataMapparquet" '[{ "column" : "AppId_s", "path" : "$.AppId_s"},{ "column" : "UserId_g", "path" : "$"},{ "column" : "Email_s", "path" : "$.Email_s"},{ "column" : "RoleName_s", "path" : "$.RoleName_s"},{ "column" : "Operation_s", "path" : "$.Operation_s"},{ "column" : "EntityId_s", "path" : "$.EntityId_s"}]'
</code>```

External Tables Gives no records

```<code>external_table('LogDataParquet')
</code>```

No records

```<code>external_table('LogDataParquet') | count
</code>```

1 record - count 0

I have used similar scenario using stream analytics , where i receive incoming streams and save it in parquet format to ADLS. External table in ADX fetches records well in that case. I feel i am making mistake in the way parquet files are written in blob - (with open("./logs.parquet", "rb") as data: )

答:
According to logs, external table was defined as follows:

```<code>.create external table LogDataParquet(AppId_s:string,UserId_g:string,Email_s:string,RoleName_s:string,Operation_s:string,EntityId_s:string,EntityType_s:string,EntityName_s:string,TargetTitle_s:string,TimeGenerated:datetime)
kind=blob
partition by
   AppId_s,
   bin(TimeGenerated,1d)
dataformat=parquet
(
   '******'
)
with
(
   folder = "ExternalTables"
)
</code>```

The PARTITION BY clause tells ADX that the expected folder layout is:

```<code><AppId_s>/<TimeGenerated, formatted as 'yyyy/MM/dd'>
</code>```

For example:

```<code>https://streamoutalds2.blob.core.windows.net/stream-api-raw-testing;secret/SuperApp/2020/01/31
</code>```

You can find more info on how ADX locates files on external storage during a query, in this section: https://learn.microsoft.com/en-us/azure/data-explorer/kusto/management/external-tables-azurestorage-azuredatalake#artifact-filtering-logic

To fix the external table definition in accordance to folders layout, please use .alter command:

```<code>.alter external table LogDataParquet(AppId_s:string,UserId_g:string,Email_s:string,RoleName_s:string,Operation_s:string,EntityId_s:string,EntityType_s:string,EntityName_s:string,TargetTitle_s:string,TimeGenerated:datetime)
kind=blob
dataformat=parquet
(
  h@'https://streamoutalds2.blob.core.windows.net/stream-api-raw-testing;secret'
)
with
(
   folder = "ExternalTables"
)
</code>```

BTW, if a mapping is naive (e.g. mapped column names match data source column names), then it's not needed for Parquet format.

Body:
Hi i want to upload Parquet files to ADLS gen 2 blob. I am using below line of code to create blob and upload parquet file in it.

blob = BlobClient.from_connection_string(conn_str="Connection String", container_name="parquet", blob_name=outdir)
df.to_parquet('logs.parquet',compression='GZIP') #df is dataframe
with open("./logs.parquet", "rb") as data:
blob.upload_blob(data)
os.remove("logs.parquet")

i do not face any error and the files are also written in the blob. But , i don't think i am doing it right as ADX/kusto query can not understand the file and no data is visible there.

Below are the steps i performed in Azure Data Explorer to fetch records from uploaded parquet file in ADLS gen 2.

Created External Table:

.create external table LogDataParquet(AppId_s:string,UserId_g:string,Email_s:string,RoleName_s:string,Operation_s:string,EntityId_s:string,EntityType_s:string,EntityName_s:string,TargetTitle_s:string,TimeGenerated:datetime)
kind=blob
dataformat=parquet
(
   h@'https://streamoutalds2.blob.core.windows.net/stream-api-raw-testing;secret'
)
with
(
   folder = "ExternalTables"
)

External Table Column Mapping :

.create external table LogDataParquet parquet mapping "LogDataMapparquet" '[{ "column" : "AppId_s", "path" : "$.AppId_s"},{ "column" : "UserId_g", "path" : "$"},{ "column" : "Email_s", "path" : "$.Email_s"},{ "column" : "RoleName_s", "path" : "$.RoleName_s"},{ "column" : "Operation_s", "path" : "$.Operation_s"},{ "column" : "EntityId_s", "path" : "$.EntityId_s"}]'

External Tables Gives no records

external_table('LogDataParquet')

No records

external_table('LogDataParquet') | count

1 record - count 0

I have used similar scenario using stream analytics , where i receive incoming streams and save it in parquet format to ADLS. External table in ADX fetches records well in that case. I feel i am making mistake in the way parquet files are written in blob - (with open("./logs.parquet", "rb") as data: )

Body:
According to logs, external table was defined as follows:

.create external table LogDataParquet(AppId_s:string,UserId_g:string,Email_s:string,RoleName_s:string,Operation_s:string,EntityId_s:string,EntityType_s:string,EntityName_s:string,TargetTitle_s:string,TimeGenerated:datetime)
kind=blob
partition by
   AppId_s,
   bin(TimeGenerated,1d)
dataformat=parquet
(
   '******'
)
with
(
   folder = "ExternalTables"
)

The PARTITION BY clause tells ADX that the expected folder layout is:

<AppId_s>/<TimeGenerated, formatted as 'yyyy/MM/dd'>

For example:

https://streamoutalds2.blob.core.windows.net/stream-api-raw-testing;secret/SuperApp/2020/01/31

You can find more info on how ADX locates files on external storage during a query, in this section: https://learn.microsoft.com/en-us/azure/data-explorer/kusto/management/external-tables-azurestorage-azuredatalake#artifact-filtering-logic

To fix the external table definition in accordance to folders layout, please use .alter command:

.alter external table LogDataParquet(AppId_s:string,UserId_g:string,Email_s:string,RoleName_s:string,Operation_s:string,EntityId_s:string,EntityType_s:string,EntityName_s:string,TargetTitle_s:string,TimeGenerated:datetime)
kind=blob
dataformat=parquet
(
  h@'https://streamoutalds2.blob.core.windows.net/stream-api-raw-testing;secret'
)
with
(
   folder = "ExternalTables"
)

BTW, if a mapping is naive (e.g. mapped column names match data source column names), then it's not needed for Parquet format.


问:
getting 405 http error when reading form data in asp.net core web api controller
Since I am new to webapi my project fornt-end is react js and backend is Asp.net core 3.1 webapi
so i am redirecting to page given below  with query string format username|redirecturl

```<code>username:Identify user
redirecturl:controller url where i will receive posted form data

--Request Url----
https://example.com/anonymouspage.aspx?req=username|https://localhost:5001/api/ControllerName/PostTodoItem
</code>```

above page will redirect back to controller url which i have share in query string with following given response

```<code>---Response---
<form name='ecom' id='test' action='Returm URL' method='post'>
  <input  type='hidden' name='txtUserName' value='Process Completed Successfully'/>
<input  type='hidden' name='givenUserName' value='abc'/>
</form>

---Controller----

[AllowAnonymous]
[HttpPost]
public async Task<string> PostTodoItem()
{
    NameValueCollection nvc = Request.Form;
    userName = nvc["givenUserName"];
    status = nvc["txtUserName"];
}
</code>```

but i am getting 405 http error i need help on this

答:
i am redirecting to page given below with query string format username|redirecturl

```<code>https://example.com/anonymouspage.aspx?req=username|https://localhost:5001/api/ControllerName/PostTodoItem
</code>```

above page will redirect back to controller url

If you do redirection via HttpResponse.Redirect Method in your .aspx code behind, it would make a GET request to your API action, but you applied [HttpPost] attribute to your API action, which cause the issue.

If you'd like to make a POST request to you API action PostTodoItem, you can refer to the following code snippet.

```<code>using (HttpClient httpClient = new HttpClient())
{
    // in your code logic
    // you may need to generate following contnet
    // based on the retrieved from data

    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("givenUserName", "abc"),
        new KeyValuePair<string, string>("txtUserName", "Process Completed Successfully")
    });

    var result = httpClient.PostAsync("https://localhost:5001/api/ControllerName/PostTodoItem", content).Result;

    //code logic here
    //...
</code>```

Test Result

Body:
Since I am new to webapi my project fornt-end is react js and backend is Asp.net core 3.1 webapi
so i am redirecting to page given below  with query string format username|redirecturl

username:Identify user
redirecturl:controller url where i will receive posted form data

--Request Url----
https://example.com/anonymouspage.aspx?req=username|https://localhost:5001/api/ControllerName/PostTodoItem

above page will redirect back to controller url which i have share in query string with following given response

---Response---
<form name='ecom' id='test' action='Returm URL' method='post'>
  <input  type='hidden' name='txtUserName' value='Process Completed Successfully'/>
<input  type='hidden' name='givenUserName' value='abc'/>
</form>

---Controller----

[AllowAnonymous]
[HttpPost]
public async Task<string> PostTodoItem()
{
    NameValueCollection nvc = Request.Form;
    userName = nvc["givenUserName"];
    status = nvc["txtUserName"];
}

but i am getting 405 http error i need help on this

Body:
i am redirecting to page given below with query string format username|redirecturl

https://example.com/anonymouspage.aspx?req=username|https://localhost:5001/api/ControllerName/PostTodoItem

above page will redirect back to controller url

If you do redirection via HttpResponse.Redirect Method in your .aspx code behind, it would make a GET request to your API action, but you applied [HttpPost] attribute to your API action, which cause the issue.

If you'd like to make a POST request to you API action PostTodoItem, you can refer to the following code snippet.

using (HttpClient httpClient = new HttpClient())
{
    // in your code logic
    // you may need to generate following contnet
    // based on the retrieved from data

    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("givenUserName", "abc"),
        new KeyValuePair<string, string>("txtUserName", "Process Completed Successfully")
    });

    var result = httpClient.PostAsync("https://localhost:5001/api/ControllerName/PostTodoItem", content).Result;

    //code logic here
    //...

Test Result


问:
TextFormField selection handle is overlapping when scrolled offscreen
The problem I'm facing is that when my ListView is scrolled off view, the text selection handle can still be seen. Here's a photo for reference, it will explain it much better: https://imgur.com/a/Lg93cV9

I've only tested it on Android, I don't have an iOS device to test it on.

Here's my main widget

```<code>  @override
  Widget body() {
    return StoreConnector<AppState, Step1IntroViewModel>(
      converter: (store) => Step1IntroViewModel.fromStore(store),
      builder: (context, viewModel) {
        return StepMainTemplate.build(
          this.context,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              _buildImageWidget(),
              Text(
                'Upload image',
                style: TextStyle(
                  color: Colors.red,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Expanded(
                child: ListView(
                  children: <Widget>[
                    StepMainTemplate.title(
                      subtitle: 'Step 1 of 2',
                      title: 'Introduce yourself',
                    ),
                    ProfileForm(
                      key: _profileFormKey,
                      initProfile: viewModel.profileState?.data,
                    ),
                    Container(
                      padding: const EdgeInsets.fromLTRB(0, 40, 0, 20),
                      width: double.infinity,
                      child: RedOneButton.text(
                          text: "Next",
                          function: () {
                            var profile = _profileFormKey.currentState.save();
                            if (profile != null) {
                              viewModel.saveProfile(profile);
                              ExtendedNavigator.ofRouter<Router>()
                                  .pushNamed(Routes.step2Route);
                            }
                          }),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
</code>```

And here's the ProfileForm

```<code>class ProfileForm extends StatefulWidget {
  final Profile initProfile;

  const ProfileForm({Key key, this.initProfile}) : super(key: key);

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

class ProfileFormState extends State<ProfileForm> {
  final _formKey = GlobalKey<FormState>();

  List<String> genders = ['Male', 'Female'];
  List<String> positions = ['SA', 'PSA', 'PS', 'VPS'];
  String _fullName;
  String _position;
  String _gender;
  String _number;
  String _email;
  String _urlName;

  @override
  void initState() {
    if (widget.initProfile != null) {
      _fullName = widget.initProfile.fullName;
      _position = widget.initProfile.position;
      _gender = widget.initProfile.gender;
      _number = widget.initProfile.phone;
      _email = widget.initProfile.email;
      _urlName = widget.initProfile.urlName;
    }
    super.initState();
  }

  Profile save() {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      var profile = Profile(
          fullName: _fullName,
          position: _position,
          gender: _gender,
          phone: _number,
          email: _email,
          urlName: _urlName);
      return profile;
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(12.0),
      child: Form(
          key: _formKey,
          child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                ProfileTextFormField(
                  initialValue: _fullName,
                  labelText: 'Full name',
                  hintText: 'Please enter your full name',
                  validator: (value) => Validator.validateFullName(value),
                  textInputAction: TextInputAction.next,
                  textCapitalization: TextCapitalization.words,
                  onSaved: (value) => _fullName = value,
                ),
                ProfileDropDownField(
                    initialValue: _position,
                    labelText: 'Position',
                    hintText: 'Please enter your position',
                    items: positions,
                    onSelected: (value) => _position = value),
                ProfileTextFormField(
                  initialValue: _number,
                  labelText: 'Phone number',
                  hintText: 'Please enter your phone number',
                  validator: (value) => Validator.validatePhone(value),
                  keyboardType: TextInputType.phone,
                  textInputAction: TextInputAction.next,
                  onSaved: (value) => _number = value,
                ),
                ProfileTextFormField(
                  initialValue: _email,
                  labelText: 'Email',
                  hintText: 'Please enter your email',
                  validator: (value) => Validator.validateEmail(value),
                  keyboardType: TextInputType.emailAddress,
                  textInputAction: TextInputAction.next,
                  onSaved: (value) => _email = value,
                  textCapitalization: TextCapitalization.none,
                ),
                ProfileRadioField(
                  initialValue: _gender,
                  labelText: 'Gender',
                  items: genders,
                  onSelected: (value) => _gender = value,
                ),
                ProfileTextFormField(
                  initialValue: _urlName,
                  labelText: 'URL name',
                  hintText: 'Your preferred URL name',
                  textInputAction: TextInputAction.done,
                  onSaved: (value) => _urlName = value,
                  textCapitalization: TextCapitalization.none,
                ),
              ])),
    );
  }
}
</code>```

Also related to https://github.com/flutter/flutter/issues/13182

答:
I have managed to fix this problem by directly putting the TextFormField directly inside a ListView. This is the only way I could get it to work properly.</p>

```<code>  @override
  Widget build(BuildContext context) {
    return Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(8.0),
          children: <Widget>[
            widget.header ?? SizedBox.shrink(),
            ..._buildContentList(),
            widget.footer ?? SizedBox.shrink(),
          ],
        ));
  }

  List<Widget> _buildContentList() {
    var list = <Widget>[];
    if (widget.hasProfile) list.addAll(_buildProfileFormList());
    if (widget.hasStory) list.addAll(_buildStoryFormList());
    return list;
  }

  List<Widget> _buildProfileFormList() {
    return <Widget>[
      ProfileTextFormField(
        initialValue: _profile.fullName,
        labelText: 'Full name',
        hintText: 'Please enter your full name',
        validator: (value) => Validator.validateFullName(value),
        textInputAction: TextInputAction.next,
        textCapitalization: TextCapitalization.words,
        onSaved: (value) => _profile.fullName = value,
      ),
      ProfileDropDownField(
          initialValue: _profile.position,
          labelText: 'Position',
          hintText: 'Please enter your position',
          items: positions,
          onSelected: (value) => _profile.position = value),
      ProfileTextFormField(
        initialValue: _profile.phone,
        labelText: 'Phone number',
        hintText: 'Please enter your phone number',
        validator: (value) => Validator.validatePhone(value),
        keyboardType: TextInputType.phone,
        textInputAction: TextInputAction.next,
        onSaved: (value) => _profile.phone = value,
      ),
      ProfileTextFormField(
        initialValue: _profile.email,
        labelText: 'Email',
        hintText: 'Please enter your email',
        validator: (value) => Validator.validateEmail(value),
        keyboardType: TextInputType.emailAddress,
        textInputAction: TextInputAction.next,
        onSaved: (value) => _profile.email = value,
        textCapitalization: TextCapitalization.none,
      ),
      ProfileRadioField(
        initialValue: _profile.gender,
        labelText: 'Gender',
        items: genders,
        onSelected: (value) => _profile.gender = value,
      ),
      ProfileTextFormField(
        initialValue: _profile.urlName,
        labelText: 'URL name',
        hintText: 'Your preferred URL name',
        textInputAction: TextInputAction.done,
        onSaved: (value) => _profile.urlName = value,
        textCapitalization: TextCapitalization.none,
      ),
    ];
  }

  List<Widget> _buildStoryFormList() {
    return <Widget>[
      ProfileTextFormField(
        initialValue: _profile.aboutYourself,
        labelText: '',
        hintText:
            '',
        textInputAction: TextInputAction.next,
        textCapitalization: TextCapitalization.sentences,
        keyboardType: TextInputType.multiline,
        onSaved: (value) => _profile.aboutYourself = value,
        maxLines: 3,
      ),
      ProfileTextFormField(
        initialValue: _profile.sharingMessage,
        labelText: '',
        hintText: '',
        keyboardType: TextInputType.multiline,
        textInputAction: TextInputAction.done,
        maxLength: 300,
        onSaved: (value) => _profile.sharingMessage = value,
        maxLines: 5,
      ),
    ];
  }

</code>```

Body:
The problem I'm facing is that when my ListView is scrolled off view, the text selection handle can still be seen. Here's a photo for reference, it will explain it much better: https://imgur.com/a/Lg93cV9

I've only tested it on Android, I don't have an iOS device to test it on.

Here's my main widget

  @override
  Widget body() {
    return StoreConnector<AppState, Step1IntroViewModel>(
      converter: (store) => Step1IntroViewModel.fromStore(store),
      builder: (context, viewModel) {
        return StepMainTemplate.build(
          this.context,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              _buildImageWidget(),
              Text(
                'Upload image',
                style: TextStyle(
                  color: Colors.red,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Expanded(
                child: ListView(
                  children: <Widget>[
                    StepMainTemplate.title(
                      subtitle: 'Step 1 of 2',
                      title: 'Introduce yourself',
                    ),
                    ProfileForm(
                      key: _profileFormKey,
                      initProfile: viewModel.profileState?.data,
                    ),
                    Container(
                      padding: const EdgeInsets.fromLTRB(0, 40, 0, 20),
                      width: double.infinity,
                      child: RedOneButton.text(
                          text: "Next",
                          function: () {
                            var profile = _profileFormKey.currentState.save();
                            if (profile != null) {
                              viewModel.saveProfile(profile);
                              ExtendedNavigator.ofRouter<Router>()
                                  .pushNamed(Routes.step2Route);
                            }
                          }),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

And here's the ProfileForm

class ProfileForm extends StatefulWidget {
  final Profile initProfile;

  const ProfileForm({Key key, this.initProfile}) : super(key: key);

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

class ProfileFormState extends State<ProfileForm> {
  final _formKey = GlobalKey<FormState>();

  List<String> genders = ['Male', 'Female'];
  List<String> positions = ['SA', 'PSA', 'PS', 'VPS'];
  String _fullName;
  String _position;
  String _gender;
  String _number;
  String _email;
  String _urlName;

  @override
  void initState() {
    if (widget.initProfile != null) {
      _fullName = widget.initProfile.fullName;
      _position = widget.initProfile.position;
      _gender = widget.initProfile.gender;
      _number = widget.initProfile.phone;
      _email = widget.initProfile.email;
      _urlName = widget.initProfile.urlName;
    }
    super.initState();
  }

  Profile save() {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      var profile = Profile(
          fullName: _fullName,
          position: _position,
          gender: _gender,
          phone: _number,
          email: _email,
          urlName: _urlName);
      return profile;
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(12.0),
      child: Form(
          key: _formKey,
          child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                ProfileTextFormField(
                  initialValue: _fullName,
                  labelText: 'Full name',
                  hintText: 'Please enter your full name',
                  validator: (value) => Validator.validateFullName(value),
                  textInputAction: TextInputAction.next,
                  textCapitalization: TextCapitalization.words,
                  onSaved: (value) => _fullName = value,
                ),
                ProfileDropDownField(
                    initialValue: _position,
                    labelText: 'Position',
                    hintText: 'Please enter your position',
                    items: positions,
                    onSelected: (value) => _position = value),
                ProfileTextFormField(
                  initialValue: _number,
                  labelText: 'Phone number',
                  hintText: 'Please enter your phone number',
                  validator: (value) => Validator.validatePhone(value),
                  keyboardType: TextInputType.phone,
                  textInputAction: TextInputAction.next,
                  onSaved: (value) => _number = value,
                ),
                ProfileTextFormField(
                  initialValue: _email,
                  labelText: 'Email',
                  hintText: 'Please enter your email',
                  validator: (value) => Validator.validateEmail(value),
                  keyboardType: TextInputType.emailAddress,
                  textInputAction: TextInputAction.next,
                  onSaved: (value) => _email = value,
                  textCapitalization: TextCapitalization.none,
                ),
                ProfileRadioField(
                  initialValue: _gender,
                  labelText: 'Gender',
                  items: genders,
                  onSelected: (value) => _gender = value,
                ),
                ProfileTextFormField(
                  initialValue: _urlName,
                  labelText: 'URL name',
                  hintText: 'Your preferred URL name',
                  textInputAction: TextInputAction.done,
                  onSaved: (value) => _urlName = value,
                  textCapitalization: TextCapitalization.none,
                ),
              ])),
    );
  }
}

Also related to https://github.com/flutter/flutter/issues/13182

Body:
I have managed to fix this problem by directly putting the TextFormField directly inside a ListView. This is the only way I could get it to work properly.

  @override
  Widget build(BuildContext context) {
    return Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(8.0),
          children: <Widget>[
            widget.header ?? SizedBox.shrink(),
            ..._buildContentList(),
            widget.footer ?? SizedBox.shrink(),
          ],
        ));
  }

  List<Widget> _buildContentList() {
    var list = <Widget>[];
    if (widget.hasProfile) list.addAll(_buildProfileFormList());
    if (widget.hasStory) list.addAll(_buildStoryFormList());
    return list;
  }

  List<Widget> _buildProfileFormList() {
    return <Widget>[
      ProfileTextFormField(
        initialValue: _profile.fullName,
        labelText: 'Full name',
        hintText: 'Please enter your full name',
        validator: (value) => Validator.validateFullName(value),
        textInputAction: TextInputAction.next,
        textCapitalization: TextCapitalization.words,
        onSaved: (value) => _profile.fullName = value,
      ),
      ProfileDropDownField(
          initialValue: _profile.position,
          labelText: 'Position',
          hintText: 'Please enter your position',
          items: positions,
          onSelected: (value) => _profile.position = value),
      ProfileTextFormField(
        initialValue: _profile.phone,
        labelText: 'Phone number',
        hintText: 'Please enter your phone number',
        validator: (value) => Validator.validatePhone(value),
        keyboardType: TextInputType.phone,
        textInputAction: TextInputAction.next,
        onSaved: (value) => _profile.phone = value,
      ),
      ProfileTextFormField(
        initialValue: _profile.email,
        labelText: 'Email',
        hintText: 'Please enter your email',
        validator: (value) => Validator.validateEmail(value),
        keyboardType: TextInputType.emailAddress,
        textInputAction: TextInputAction.next,
        onSaved: (value) => _profile.email = value,
        textCapitalization: TextCapitalization.none,
      ),
      ProfileRadioField(
        initialValue: _profile.gender,
        labelText: 'Gender',
        items: genders,
        onSelected: (value) => _profile.gender = value,
      ),
      ProfileTextFormField(
        initialValue: _profile.urlName,
        labelText: 'URL name',
        hintText: 'Your preferred URL name',
        textInputAction: TextInputAction.done,
        onSaved: (value) => _profile.urlName = value,
        textCapitalization: TextCapitalization.none,
      ),
    ];
  }

  List<Widget> _buildStoryFormList() {
    return <Widget>[
      ProfileTextFormField(
        initialValue: _profile.aboutYourself,
        labelText: '',
        hintText:
            '',
        textInputAction: TextInputAction.next,
        textCapitalization: TextCapitalization.sentences,
        keyboardType: TextInputType.multiline,
        onSaved: (value) => _profile.aboutYourself = value,
        maxLines: 3,
      ),
      ProfileTextFormField(
        initialValue: _profile.sharingMessage,
        labelText: '',
        hintText: '',
        keyboardType: TextInputType.multiline,
        textInputAction: TextInputAction.done,
        maxLength: 300,
        onSaved: (value) => _profile.sharingMessage = value,
        maxLines: 5,
      ),
    ];
  }


问:
unique_for_date parameter for SlugField
```<code>First, I am reading a book on django and from it have created the following models.py (entire models.py included at the end, the two fields related to the question are here):
    slug = models.SlugField(max_length = 250,
                unique_for_date = 'publish') #unique_for_date ensures that there will be only one post with a slug for a given date, thus we can retrieve single posts using date and slug
    publish = models.DateTimeField(default = timezone.now)
</code>```

Anyway, I have been searching online and have seen that you can use the unique_for_date parameter when creating a DateTimeField() but when it comes to using the parameter in a SlugField() I found one question asked on here almost ten years ago (How to create a unique_for_field slug in Django?) and so figured it wouldn't hurt to ask. If this can be done, can someone explain what that parameter is doing? Is this maybe something that is now obsolete in django? Thanks in advance.

models.py:

```<code># Create your models here.
class Post(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Pusblished'),
    )
    title = models.CharField(max_length = 250)
    slug = models.SlugField(max_length = 250,
                unique_for_date = 'publish') #unique_for_date ensures that there will be only one post with a slug for a given date, thus we can retrieve single posts using date and slug
    author = models.ForeignKey(User,
                on_delete= models.CASCADE,
                related_name= 'blog_posts'
                )
    body = models.TextField()
    publish = models.DateTimeField(default = timezone.now)
    created = models.DateTimeField(auto_now_add = True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length = 10,
                choices = STATUS_CHOICES,
                default = 'draft')
</code>```

答:
referring to django docs which states the following:
Field.unique_for_date¶
Set this to the name of a DateField or DateTimeField to require that this field be unique for the value of the date field.

For example, if you have a field title that has unique_for_date="pub_date", then Django wouldn’t allow the entry of two records with the same title and pub_date.

Note that if you set this to point to a DateTimeField, only the date portion of the field will be considered. Besides, when USE_TZ is True, the check will be performed in the current time zone at the time the object gets saved.

This is enforced by Model.validate_unique() during model validation but not at the database level. If any unique_for_date constraint involves fields that are not part of a ModelForm (for example, if one of the fields is listed in exclude or has editable=False), Model.validate_unique() will skip validation for that particular constraint.

https://docs.djangoproject.com/en/3.0/ref/models/fields/#unique-for-date

this you can consider as unique_together which in your case you cant save same post with the same slug in same day

example:
if you at 3/6/2020 and your slug is Hello if you try to write same slug with name Hello again in same day it will be refused but if you write the same slug in other day it will be accepted

Title: unique_for_date parameter for SlugField

Body:
First, I am reading a book on django and from it have created the following models.py (entire models.py included at the end, the two fields related to the question are here):
    slug = models.SlugField(max_length = 250,
                unique_for_date = 'publish') #unique_for_date ensures that there will be only one post with a slug for a given date, thus we can retrieve single posts using date and slug
    publish = models.DateTimeField(default = timezone.now)

Anyway, I have been searching online and have seen that you can use the unique_for_date parameter when creating a DateTimeField() but when it comes to using the parameter in a SlugField() I found one question asked on here almost ten years ago (How to create a unique_for_field slug in Django?) and so figured it wouldn't hurt to ask. If this can be done, can someone explain what that parameter is doing? Is this maybe something that is now obsolete in django? Thanks in advance.

models.py:

# Create your models here.
class Post(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Pusblished'),
    )
    title = models.CharField(max_length = 250)
    slug = models.SlugField(max_length = 250,
                unique_for_date = 'publish') #unique_for_date ensures that there will be only one post with a slug for a given date, thus we can retrieve single posts using date and slug
    author = models.ForeignKey(User,
                on_delete= models.CASCADE,
                related_name= 'blog_posts'
                )
    body = models.TextField()
    publish = models.DateTimeField(default = timezone.now)
    created = models.DateTimeField(auto_now_add = True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length = 10,
                choices = STATUS_CHOICES,
                default = 'draft')