问:
extract comma separated strings from txt file in C
I need to read from a file different strings that are comma-separated and storage them into an array.

I have the following code, that I developed reading different questions online.

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

int main (){
int N = 300;
int L = 1000;
char Nseq[N][L];

FILE *myfile;
char *token;
const char s[2] = ",";
char line[300];
char* filename = "pathtofile.txt";
int n = 0;

myfile = fopen(filename, "r");
if (myfile == NULL) {printf("could not open file %s", filename); exit(0);}
while (fgets(line, sizeof(line), myfile) != NULL){
  token = strtok(line, s);
  while (token != NULL){
    strcpy(Nseq[n], token);
    printf("%s\t%u\n", token, n);
    token = strtok(NULL, s);
    n++;
  }
}
fclose(myfile);
}
</code>```

my txt file is the following:

```<code>1AAAAAAAAAAAAAAAAAAAAAAAAAAAA,2AAAAAAAAAAAAAAAAAAAAAAAAAAAA,3AAAAAAAAAAAAAAAAAAAAAAAAAAAA,4AAAAAAAAAAAAAAAAAAAAAAAAAAAA,5AAAAAAAAAAAAAAAAAAAAAAAAAAAA,6AAAAAAAAAAAAAAAAAAAAAAAAAAAA,7AAAAAAAAAAAAAAAAAAAAAAAAAAAA,8AAAAAAAAAAAAAAAAAAAAAAAAAAAA,9AAAAAAAAAAAAAAAAAAAAAAAAAAAA,10AAAAAAAAAAAAAAAAAAAAAAAAAAAA,11AAAAAAAAAAAAAAAAAAAAAAAAAAAA,12AAAAAAAAAAAAAAAAAAAAAAAAAAAA,13AAAAAAAAAAAAAAAAAAAAAAAAAAAA,14AAAAAAAAAAAAAAAAAAAAAAAAAAAA,15AAAAAAAAAAAAAAAAAAAAAAAAAAAA,16AAAAAAAAAAAAAAAAAAAAAAAAAAAA,17AAAAAAAAAAAAAAAAAAAAAAAAAAAA,18AAAAAAAAAAAAAAAAAAAAAAAAAAAA,19AAAAAAAAAAAAAAAAAAAAAAAAAAAA,20AAAAAAAAAAAAAAAAAAAAAAAAAAAA,21AAAAAAAAAAAAAAAAAAAAAAAAAAAA,22AAAAAAAAAAAAAAAAAAAAAAAAAAAA,23AAAAAAAAAAAAAAAAAAAAAAAAAAAA,24AAAAAAAAAAAAAAAAAAAAAAAAAAAA,25AAAAAAAAAAAAAAAAAAAAAAAAAAAA,26AAAAAAAAAAAAAAAAAAAAAAAAAAAA,27AAAAAAAAAAAAAAAAAAAAAAAAAAAA,28AAAAAAAAAAAAAAAAAAAAAAAAAAAA,29AAAAAAAAAAAAAAAAAAAAAAAAAAAA,30AAAAAAAAAAAAAAAAAAAAAAAAAAAA,
</code>```

There are 30 strings and no new-line characters.

My issue is that when I run the code, I get the following output:

```<code>1AAAAAAAAAAAAAAAAAAAAAAAAAAAA   0
2AAAAAAAAAAAAAAAAAAAAAAAAAAAA   1
3AAAAAAAAAAAAAAAAAAAAAAAAAAAA   2
4AAAAAAAAAAAAAAAAAAAAAAAAAAAA   3
5AAAAAAAAAAAAAAAAAAAAAAAAAAAA   4
6AAAAAAAAAAAAAAAAAAAAAAAAAAAA   5
7AAAAAAAAAAAAAAAAAAAAAAAAAAAA   6
8AAAAAAAAAAAAAAAAAAAAAAAAAAAA   7
9AAAAAAAAAAAAAAAAAAAAAAAAAAAA   8
10AAAAAAAAAAAAAAAAAAAAAAAAAAA   9
A       10
11AAAAAAAAAAAAAAAAAAAAAAAAAAAA  11
12AAAAAAAAAAAAAAAAAAAAAAAAAAAA  12
13AAAAAAAAAAAAAAAAAAAAAAAAAAAA  13
14AAAAAAAAAAAAAAAAAAAAAAAAAAAA  14
15AAAAAAAAAAAAAAAAAAAAAAAAAAAA  15
16AAAAAAAAAAAAAAAAAAAAAAAAAAAA  16
17AAAAAAAAAAAAAAAAAAAAAAAAAAAA  17
18AAAAAAAAAAAAAAAAAAAAAAAAAAAA  18
19AAAAAAAAAAAAAAAAAAAAAAAAAAAA  19
20AAAAAAAAAAAAAAAA      20
AAAAAAAAAAAA    21
21AAAAAAAAAAAAAAAAAAAAAAAAAAAA  22
22AAAAAAAAAAAAAAAAAAAAAAAAAAAA  23
23AAAAAAAAAAAAAAAAAAAAAAAAAAAA  24
24AAAAAAAAAAAAAAAAAAAAAAAAAAAA  25
25AAAAAAAAAAAAAAAAAAAAAAAAAAAA  26
26AAAAAAAAAAAAAAAAAAAAAAAAAAAA  27
27AAAAAAAAAAAAAAAAAAAAAAAAAAAA  28
28AAAAAAAAAAAAAAAAAAAAAAAAAAAA  29
29AAAAAAAAAAAAAAAAAAAAAAAAAAAA  30
30AAAAA 31
AAAAAAAAAAAAAAAAAAAAAAA 32

        33
</code>```

I have tried with different lengths and sooner or later I get these weird splits.

Does someone know why is this happening? thank you!

答:
Your text file is 921 chars in size and is a single line.

Your line buffer is only 300 chars.

So, you're getting truncation.

Also, note that your file has no newline. And, your code didn't handle the case where there is a newline (particularly, if the line ended in ,<newline>).

The simple solution is to increase the size of line so that it is larger than the size of the file (e.g.) char line[10000];

The long term solution is to either read the file char-by-char with (e.g.) fgetc and copy into Nseq[n] and store/print the token after a delimiter.

Or, you can stat the file, and use malloc to allocate a buffer that is the file size.

But, although slightly more advanced, the fastest way [particularly for large files], is to stat the file, mmap it, and then scan the buffer. This will work well on any 64 bit machine, or you could map it in chunks on a 32 bit machine

Here's a version that uses fgetc:

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

int
main(void)
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    FILE *myfile;
    char *token;
    char *filename = "pathtofile.txt";
    int chr;
    int n = 0;

    myfile = fopen(filename, "r");
    if (myfile == NULL) {
        printf("could not open file %s", filename);
        exit(0);
    }

    token = Nseq[n];

    while (1) {
        chr = fgetc(myfile);
        if (chr == EOF)
            break;

        switch (chr) {
        case ',':
        case '\n':
            *token = 0;
            if (token > Nseq[n]) {
                printf("%s\t%u\n", Nseq[n], n);
                ++n;
            }
            token = Nseq[n];
            break;

        default:
            *token++ = chr;
            break;
        }
    }

    fclose(myfile);

    return 0;
}
</code>```

Here's a version that uses malloc:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int
main(void)
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    FILE *myfile;
    char *token;
    const char s[2] = ",";
    char *line;
    int len;
    char *filename = "pathtofile.txt";
    int err;
    struct stat st;
    int n = 0;

    err = stat(filename,&st);
    if (err < 0) {
        printf("could not stat file %s", filename);
        exit(1);
    }
    len = st.st_size + 1;

    line = malloc(len);

    myfile = fopen(filename, "r");
    if (myfile == NULL) {
        printf("could not open file %s", filename);
        exit(1);
    }

    while (fgets(line, len, myfile) != NULL) {
        token = strtok(line, s);
        while (token != NULL) {
            strcpy(Nseq[n], token);
            printf("%s\t%u\n", token, n);
            token = strtok(NULL, s);
            n++;
        }
    }

    fclose(myfile);

    return 0;
}
</code>```

Here's a version that uses mmap:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>

int
main(void)
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    char *token;
    char *line;
    char *cur;
    char *end;
    char *filename = "pathtofile.txt";
    int fd;
    int chr;
    int n = 0;
    int err;
    struct stat st;
    size_t len;

    fd = open(filename,O_RDONLY);
    if (fd < 0) {
        printf("could not open file %s", filename);
        exit(1);
    }

    err = fstat(fd,&st);
    if (err < 0) {
        printf("could not stat file %s", filename);
        exit(1);
    }
    len = st.st_size;

    line = mmap(NULL,len,PROT_READ,MAP_PRIVATE,fd,0);
    if (line == MAP_FAILED) {
        printf("could not mmap file %s", filename);
        exit(1);
    }

    cur = line;
    end = &line[len];
    token = Nseq[n];

    for (cur = line;  cur < end;  ++cur) {
        chr = *cur;

        switch (chr) {
        case ',':
        case '\n':
            *token = 0;
            if (token > Nseq[n]) {
                printf("%s\t%u\n", Nseq[n], n);
                ++n;
            }
            token = Nseq[n];
            break;

        default:
            *token++ = chr;
            break;
        }
    }

    munmap(line,len);
    close(fd);

    return 0;
}
</code>```

Body:
I need to read from a file different strings that are comma-separated and storage them into an array.

I have the following code, that I developed reading different questions online.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (){
int N = 300;
int L = 1000;
char Nseq[N][L];

FILE *myfile;
char *token;
const char s[2] = ",";
char line[300];
char* filename = "pathtofile.txt";
int n = 0;

myfile = fopen(filename, "r");
if (myfile == NULL) {printf("could not open file %s", filename); exit(0);}
while (fgets(line, sizeof(line), myfile) != NULL){
  token = strtok(line, s);
  while (token != NULL){
    strcpy(Nseq[n], token);
    printf("%s\t%u\n", token, n);
    token = strtok(NULL, s);
    n++;
  }
}
fclose(myfile);
}

my txt file is the following:

1AAAAAAAAAAAAAAAAAAAAAAAAAAAA,2AAAAAAAAAAAAAAAAAAAAAAAAAAAA,3AAAAAAAAAAAAAAAAAAAAAAAAAAAA,4AAAAAAAAAAAAAAAAAAAAAAAAAAAA,5AAAAAAAAAAAAAAAAAAAAAAAAAAAA,6AAAAAAAAAAAAAAAAAAAAAAAAAAAA,7AAAAAAAAAAAAAAAAAAAAAAAAAAAA,8AAAAAAAAAAAAAAAAAAAAAAAAAAAA,9AAAAAAAAAAAAAAAAAAAAAAAAAAAA,10AAAAAAAAAAAAAAAAAAAAAAAAAAAA,11AAAAAAAAAAAAAAAAAAAAAAAAAAAA,12AAAAAAAAAAAAAAAAAAAAAAAAAAAA,13AAAAAAAAAAAAAAAAAAAAAAAAAAAA,14AAAAAAAAAAAAAAAAAAAAAAAAAAAA,15AAAAAAAAAAAAAAAAAAAAAAAAAAAA,16AAAAAAAAAAAAAAAAAAAAAAAAAAAA,17AAAAAAAAAAAAAAAAAAAAAAAAAAAA,18AAAAAAAAAAAAAAAAAAAAAAAAAAAA,19AAAAAAAAAAAAAAAAAAAAAAAAAAAA,20AAAAAAAAAAAAAAAAAAAAAAAAAAAA,21AAAAAAAAAAAAAAAAAAAAAAAAAAAA,22AAAAAAAAAAAAAAAAAAAAAAAAAAAA,23AAAAAAAAAAAAAAAAAAAAAAAAAAAA,24AAAAAAAAAAAAAAAAAAAAAAAAAAAA,25AAAAAAAAAAAAAAAAAAAAAAAAAAAA,26AAAAAAAAAAAAAAAAAAAAAAAAAAAA,27AAAAAAAAAAAAAAAAAAAAAAAAAAAA,28AAAAAAAAAAAAAAAAAAAAAAAAAAAA,29AAAAAAAAAAAAAAAAAAAAAAAAAAAA,30AAAAAAAAAAAAAAAAAAAAAAAAAAAA,

There are 30 strings and no new-line characters.

My issue is that when I run the code, I get the following output:

1AAAAAAAAAAAAAAAAAAAAAAAAAAAA   0
2AAAAAAAAAAAAAAAAAAAAAAAAAAAA   1
3AAAAAAAAAAAAAAAAAAAAAAAAAAAA   2
4AAAAAAAAAAAAAAAAAAAAAAAAAAAA   3
5AAAAAAAAAAAAAAAAAAAAAAAAAAAA   4
6AAAAAAAAAAAAAAAAAAAAAAAAAAAA   5
7AAAAAAAAAAAAAAAAAAAAAAAAAAAA   6
8AAAAAAAAAAAAAAAAAAAAAAAAAAAA   7
9AAAAAAAAAAAAAAAAAAAAAAAAAAAA   8
10AAAAAAAAAAAAAAAAAAAAAAAAAAA   9
A       10
11AAAAAAAAAAAAAAAAAAAAAAAAAAAA  11
12AAAAAAAAAAAAAAAAAAAAAAAAAAAA  12
13AAAAAAAAAAAAAAAAAAAAAAAAAAAA  13
14AAAAAAAAAAAAAAAAAAAAAAAAAAAA  14
15AAAAAAAAAAAAAAAAAAAAAAAAAAAA  15
16AAAAAAAAAAAAAAAAAAAAAAAAAAAA  16
17AAAAAAAAAAAAAAAAAAAAAAAAAAAA  17
18AAAAAAAAAAAAAAAAAAAAAAAAAAAA  18
19AAAAAAAAAAAAAAAAAAAAAAAAAAAA  19
20AAAAAAAAAAAAAAAA      20
AAAAAAAAAAAA    21
21AAAAAAAAAAAAAAAAAAAAAAAAAAAA  22
22AAAAAAAAAAAAAAAAAAAAAAAAAAAA  23
23AAAAAAAAAAAAAAAAAAAAAAAAAAAA  24
24AAAAAAAAAAAAAAAAAAAAAAAAAAAA  25
25AAAAAAAAAAAAAAAAAAAAAAAAAAAA  26
26AAAAAAAAAAAAAAAAAAAAAAAAAAAA  27
27AAAAAAAAAAAAAAAAAAAAAAAAAAAA  28
28AAAAAAAAAAAAAAAAAAAAAAAAAAAA  29
29AAAAAAAAAAAAAAAAAAAAAAAAAAAA  30
30AAAAA 31
AAAAAAAAAAAAAAAAAAAAAAA 32

        33

I have tried with different lengths and sooner or later I get these weird splits.

Does someone know why is this happening? thank you!

Body:
Your text file is 921 chars in size and is a single line.

Your line buffer is only 300 chars.

So, you're getting truncation.

Also, note that your file has no newline. And, your code didn't handle the case where there is a newline (particularly, if the line ended in ,<newline>).

The simple solution is to increase the size of line so that it is larger than the size of the file (e.g.) char line[10000];

The long term solution is to either read the file char-by-char with (e.g.) fgetc and copy into Nseq[n] and store/print the token after a delimiter.

Or, you can stat the file, and use malloc to allocate a buffer that is the file size.

But, although slightly more advanced, the fastest way [particularly for large files], is to stat the file, mmap it, and then scan the buffer. This will work well on any 64 bit machine, or you could map it in chunks on a 32 bit machine

Here's a version that uses fgetc:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(void)
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    FILE *myfile;
    char *token;
    char *filename = "pathtofile.txt";
    int chr;
    int n = 0;

    myfile = fopen(filename, "r");
    if (myfile == NULL) {
        printf("could not open file %s", filename);
        exit(0);
    }

    token = Nseq[n];

    while (1) {
        chr = fgetc(myfile);
        if (chr == EOF)
            break;

        switch (chr) {
        case ',':
        case '\n':
            *token = 0;
            if (token > Nseq[n]) {
                printf("%s\t%u\n", Nseq[n], n);
                ++n;
            }
            token = Nseq[n];
            break;

        default:
            *token++ = chr;
            break;
        }
    }

    fclose(myfile);

    return 0;
}

Here's a version that uses malloc:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int
main(void)
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    FILE *myfile;
    char *token;
    const char s[2] = ",";
    char *line;
    int len;
    char *filename = "pathtofile.txt";
    int err;
    struct stat st;
    int n = 0;

    err = stat(filename,&st);
    if (err < 0) {
        printf("could not stat file %s", filename);
        exit(1);
    }
    len = st.st_size + 1;

    line = malloc(len);

    myfile = fopen(filename, "r");
    if (myfile == NULL) {
        printf("could not open file %s", filename);
        exit(1);
    }

    while (fgets(line, len, myfile) != NULL) {
        token = strtok(line, s);
        while (token != NULL) {
            strcpy(Nseq[n], token);
            printf("%s\t%u\n", token, n);
            token = strtok(NULL, s);
            n++;
        }
    }

    fclose(myfile);

    return 0;
}

Here's a version that uses mmap:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>

int
main(void)
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    char *token;
    char *line;
    char *cur;
    char *end;
    char *filename = "pathtofile.txt";
    int fd;
    int chr;
    int n = 0;
    int err;
    struct stat st;
    size_t len;

    fd = open(filename,O_RDONLY);
    if (fd < 0) {
        printf("could not open file %s", filename);
        exit(1);
    }

    err = fstat(fd,&st);
    if (err < 0) {
        printf("could not stat file %s", filename);
        exit(1);
    }
    len = st.st_size;

    line = mmap(NULL,len,PROT_READ,MAP_PRIVATE,fd,0);
    if (line == MAP_FAILED) {
        printf("could not mmap file %s", filename);
        exit(1);
    }

    cur = line;
    end = &line[len];
    token = Nseq[n];

    for (cur = line;  cur < end;  ++cur) {
        chr = *cur;

        switch (chr) {
        case ',':
        case '\n':
            *token = 0;
            if (token > Nseq[n]) {
                printf("%s\t%u\n", Nseq[n], n);
                ++n;
            }
            token = Nseq[n];
            break;

        default:
            *token++ = chr;
            break;
        }
    }

    munmap(line,len);
    close(fd);

    return 0;
}


来源: stackexchange

问:
Bitbucket pipeline with multiple branches
I want to use bitbucket pipelines, and I have bitbucket-pipelines.yml like this:

```<code>image: java:8

pipelines:
  default:
    - step:
        caches:
          - gradle
          - android-sdk

        script:
          /*SOME CODE*/

          # Build apk
          - chmod a+x ./gradlew
          - ./gradlew assembleDebug

  branches:
    develop:
      - step:
          caches:
            - gradle
            - android-sdk

          script:
            /*SOME CODE*/

            # Build apk
            - chmod a+x ./gradlew
            - ./gradlew assembleDebug

          artifacts:
            - app/build/outputs/apk/debug/*.apk

definitions:
  caches:
    android-sdk: android-sdk
</code>```

But there is a lot of equal code in "script", is there any way to fix this? Maybe move equal code to script?

I have trayed move code to build.sh, but got errors:

```<code>+ ./build.sh
./build.sh: line 4: -: command not found
./build.sh: line 5: -: command not found
./build.sh: line 8: -: command not found
</code>```

答:
Creating a build.sh file is a possibility. However, it looks as though you are not removing the '-' character when you copy the commands of the script to your file. For the file given, your build.sh should looks like:

```<code>/* SOME CODE*/

# Build apk
chmod a+x ./gradlew
./gradlew assembleDebug
</code>```

Note how there is no '-' before each command.
Your bitbucket-pipelines.yml file should then look like:

```<code>pipelines:
  default:
    - step:
        caches:
          - gradle
          - android-sdk

        script:
          - ./build.sh

  branches:
    develop:
      - step:
          caches:
            - gradle
            - android-sdk

          script:
            - ./build.sh

          artifacts:
            - app/build/outputs/apk/debug/*.apk

definitions:
  caches:
    android-sdk: android-sdk
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to use bitbucket pipelines, and I have bitbucket-pipelines.yml like this:

image: java:8

pipelines:
  default:
    - step:
        caches:
          - gradle
          - android-sdk

        script:
          /*SOME CODE*/

          # Build apk
          - chmod a+x ./gradlew
          - ./gradlew assembleDebug

  branches:
    develop:
      - step:
          caches:
            - gradle
            - android-sdk

          script:
            /*SOME CODE*/

            # Build apk
            - chmod a+x ./gradlew
            - ./gradlew assembleDebug

          artifacts:
            - app/build/outputs/apk/debug/*.apk

definitions:
  caches:
    android-sdk: android-sdk

But there is a lot of equal code in "script", is there any way to fix this? Maybe move equal code to script?

I have trayed move code to build.sh, but got errors:

+ ./build.sh
./build.sh: line 4: -: command not found
./build.sh: line 5: -: command not found
./build.sh: line 8: -: command not found

Body:
Creating a build.sh file is a possibility. However, it looks as though you are not removing the '-' character when you copy the commands of the script to your file. For the file given, your build.sh should looks like:

/* SOME CODE*/

# Build apk
chmod a+x ./gradlew
./gradlew assembleDebug

Note how there is no '-' before each command.
Your bitbucket-pipelines.yml file should then look like:

pipelines:
  default:
    - step:
        caches:
          - gradle
          - android-sdk

        script:
          - ./build.sh

  branches:
    develop:
      - step:
          caches:
            - gradle
            - android-sdk

          script:
            - ./build.sh

          artifacts:
            - app/build/outputs/apk/debug/*.apk

definitions:
  caches:
    android-sdk: android-sdk


问:
Calculate mean of df, BUT if =>1 of the values differs >20% from this mean, the mean is set to NaN
I want to calculate the mean of columns a,b,c,d of the dataframe BUT if one of four values in each dataframe row differs more then 20% from this mean (of the four values), the mean has to be set to NaN.

Calculation of the mean of 4 columns is easy, but I'm stuck at defining the condition 'if mean*0.8 <= one of the values in the data row <= mean*1,2 then mean == NaN.

In the example, one or more of the values in ID:5 en ID:87 don't fit in the interval and therefore the mean is set to NaN.
(NaN-values in the initial dataframe are ignored when calculating the mean and when applying the 20%-condition to the calculated mean)

So I'm trying to calculate the mean only for the data rows with no 'outliers'.

Initial df:

```<code> ID   a    b    c   d
  2  31   32   31  31
  5  33   52  159   2
  7  51  NaN   52  51
 87  30   52  421   2
 90  10   11   10  11
102  41   42  NaN  42
</code>```

Desired df:

```<code> ID   a    b    c   d    mean
  2  31   32   31  31   31.25
  5  33   52  159   2     NaN
  7  51  NaN   52  51   51.33
 87  30   52  421   2     NaN
 90  10   11   10  11   10.50
102  41   42  NaN  42   41.67
</code>```

Code:

```<code>import pandas as pd

import numpy as np

df = pd.DataFrame({"ID": [2,5,7,87,90,102],

                    "a": [31,33,51,30,10,41],

                    "b": [32,52,np.nan,52,11,42],

                    "c": [31,159,52,421,10,np.nan],

                    "d": [31,2,51,2,11,42]})

print(df)

a = df.loc[:, ['a','b','c','d']]

df['mean'] = (a.iloc[:,0:]).mean(1)

print(df)

b = df.mean.values[:,None]*0.8 < a.values[:,:] < df.mean.values[:,None]*1.2
print(b)
...

</code>```

答:
Try this:

```<code># extract related information
s = df.iloc[:,1:]

# calculate mean
mean = s.mean(1)

# where condition is violated
mask = s.lt(mean*.8, axis=0) | s.gt(mean*1.2, axis=0)

# mask where mask is True on any row
df['mean'] = mean.mask(mask.any(1))
</code>```

Output:

```<code>    ID   a     b      c   d       mean
0    2  31  32.0   31.0  31  31.250000
1    5  33  52.0  159.0   2        NaN
2    7  51   NaN   52.0  51  51.333333
3   87  30  52.0  421.0   2        NaN
4   90  10  11.0   10.0  11  10.500000
5  102  41  42.0    NaN  42  41.666667
</code>```

Body:
I want to calculate the mean of columns a,b,c,d of the dataframe BUT if one of four values in each dataframe row differs more then 20% from this mean (of the four values), the mean has to be set to NaN.

Calculation of the mean of 4 columns is easy, but I'm stuck at defining the condition 'if mean*0.8 <= one of the values in the data row <= mean*1,2 then mean == NaN.

In the example, one or more of the values in ID:5 en ID:87 don't fit in the interval and therefore the mean is set to NaN.
(NaN-values in the initial dataframe are ignored when calculating the mean and when applying the 20%-condition to the calculated mean)

So I'm trying to calculate the mean only for the data rows with no 'outliers'.

Initial df:

 ID   a    b    c   d
  2  31   32   31  31
  5  33   52  159   2
  7  51  NaN   52  51
 87  30   52  421   2
 90  10   11   10  11
102  41   42  NaN  42

Desired df:

 ID   a    b    c   d    mean
  2  31   32   31  31   31.25
  5  33   52  159   2     NaN
  7  51  NaN   52  51   51.33
 87  30   52  421   2     NaN
 90  10   11   10  11   10.50
102  41   42  NaN  42   41.67

Code:

import pandas as pd

import numpy as np

df = pd.DataFrame({"ID": [2,5,7,87,90,102],

                    "a": [31,33,51,30,10,41],

                    "b": [32,52,np.nan,52,11,42],

                    "c": [31,159,52,421,10,np.nan],

                    "d": [31,2,51,2,11,42]})

print(df)

a = df.loc[:, ['a','b','c','d']]

df['mean'] = (a.iloc[:,0:]).mean(1)

print(df)

b = df.mean.values[:,None]*0.8 < a.values[:,:] < df.mean.values[:,None]*1.2
print(b)
...

Body:
Try this:

# extract related information
s = df.iloc[:,1:]

# calculate mean
mean = s.mean(1)

# where condition is violated
mask = s.lt(mean*.8, axis=0) | s.gt(mean*1.2, axis=0)

# mask where mask is True on any row
df['mean'] = mean.mask(mask.any(1))

Output:

    ID   a     b      c   d       mean
0    2  31  32.0   31.0  31  31.250000
1    5  33  52.0  159.0   2        NaN
2    7  51   NaN   52.0  51  51.333333
3   87  30  52.0  421.0   2        NaN
4   90  10  11.0   10.0  11  10.500000
5  102  41  42.0    NaN  42  41.666667


问:
Upload Audio file using Retrofit to flask api
I am trying to use sound for processing so I need the sound to be uploaded from android device to API (Flask).

I used MultiPart with a retrofit call is successfully sent but at API side not detect file

retrofit

```<code>@POST("uploadfile")
    @Multipart
    Call<MLResponse> upload(@Part("file")RequestBody file);

</code>```

request body

```<code> requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("title", "Square Logo")
                .addFormDataPart("file", "aa.mp4",
                        RequestBody.create(MEDIA_TYPE_AUDIO, new File(path)))
                .build();
</code>```

API

```<code>@app.route('/uploadfile',methods=['GET','POST'])
def uploadfile():
     # check if the post request has the file part
        if 'file' not in request.files:
            return jsonify( result = "No file")
        try:
            file = request.files['file']
            return jsonify( result = str(file.filename)
        except :
            return jsonify( result = "Error")

</code>```

the result is No file however
I have checked the file using file.exists() it returns true and able to play it.

答:
In your API code you have no code for saving this file. Check this code and add the necessary lines.</p>

```<code>@app.route('/uploadfile',methods=['GET','POST'])
def uploadfile():
    if request.method == 'PUT':
        f = request.files['file']
        filePath = "./somedir/"+secure_filename(f.filename)
        f.save(filePath)
        return "success"
</code>```

Body:
I am trying to use sound for processing so I need the sound to be uploaded from android device to API (Flask).

I used MultiPart with a retrofit call is successfully sent but at API side not detect file

retrofit

@POST("uploadfile")
    @Multipart
    Call<MLResponse> upload(@Part("file")RequestBody file);

request body

 requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("title", "Square Logo")
                .addFormDataPart("file", "aa.mp4",
                        RequestBody.create(MEDIA_TYPE_AUDIO, new File(path)))
                .build();

API

@app.route('/uploadfile',methods=['GET','POST'])
def uploadfile():
     # check if the post request has the file part
        if 'file' not in request.files:
            return jsonify( result = "No file")
        try:
            file = request.files['file']
            return jsonify( result = str(file.filename)
        except :
            return jsonify( result = "Error")

the result is No file however
I have checked the file using file.exists() it returns true and able to play it.

Body:
In your API code you have no code for saving this file. Check this code and add the necessary lines.

@app.route('/uploadfile',methods=['GET','POST'])
def uploadfile():
    if request.method == 'PUT':
        f = request.files['file']
        filePath = "./somedir/"+secure_filename(f.filename)
        f.save(filePath)
        return "success"


问:
Youtube Data Api V3 using React js showing results of previous fetch
I was making a youtube clone in which user can search for a term and the youtube data API will show the desired results in react js but every time I am querying the data of the previous query is being shown.
When I am logging 'Post' ie the JSON data

**Searchquery Component*

```<code>    import React,{useEffect,useState} from 'react'
    import axios from 'axios'
    import Cards from './Cards'

    function SearchResults(props) {
        const query = props.match.params.query;
        const [posts, setPosts] = useState([])
        useEffect(() => {
            axios({
                "method": "GET",
                "url": 'https://www.googleapis.com/youtube/v3/search',
                "params":{
                    'part':'snippet',
                    'maxResults':'20',
                    'key':'[API_KEY]',
                    'q':query
                }
            })
                .then((res) => {
                    setPosts(res.data.items)
                })
                .catch((error) => {
                    console.log(error)
                })
                console.log(posts);
        },[query])

        return (
            <div>
                <Cards/>
            </div>
        )
    }

    export default SearchResults
</code>```

答:
In the useEffect hook you need to add [query] as a second parameter. It means that the callback function (first parameter of useEffect method) will not be executed until query variable is changed ==> I think you must change [query] by [posts].

Just use this code :

```<code>import React,{useEffect,useState} from 'react'
import axios from 'axios'
import Cards from './Cards'

function SearchResults(props) {
    const query = props.match.params.query;
    const [posts, setPosts] = useState([])
    useEffect(() => {
        axios({
            "method": "GET",
            "url": 'https://www.googleapis.com/youtube/v3/search',
            "params":{
                'part':'snippet',
                'maxResults':'20',
                'key':'[API_KEY]',
                'q':query
            }
        })
            .then((res) => {
                setPosts(res.data.items)
            })
            .catch((error) => {
                console.log(error)
            })
            console.log(posts);
    },[posts])

    return (
        <div>
            <Cards/>
        </div>
    )
}

export default SearchResults
</code>```

Body:
I was making a youtube clone in which user can search for a term and the youtube data API will show the desired results in react js but every time I am querying the data of the previous query is being shown.
When I am logging 'Post' ie the JSON data

**Searchquery Component*

    import React,{useEffect,useState} from 'react'
    import axios from 'axios'
    import Cards from './Cards'

    function SearchResults(props) {
        const query = props.match.params.query;
        const [posts, setPosts] = useState([])
        useEffect(() => {
            axios({
                "method": "GET",
                "url": 'https://www.googleapis.com/youtube/v3/search',
                "params":{
                    'part':'snippet',
                    'maxResults':'20',
                    'key':'[API_KEY]',
                    'q':query
                }
            })
                .then((res) => {
                    setPosts(res.data.items)
                })
                .catch((error) => {
                    console.log(error)
                })
                console.log(posts);
        },[query])

        return (

                <Cards/>

        )
    }

    export default SearchResults

Body:
In the useEffect hook you need to add [query] as a second parameter. It means that the callback function (first parameter of useEffect method) will not be executed until query variable is changed ==> I think you must change [query] by [posts].

Just use this code :

import React,{useEffect,useState} from 'react'
import axios from 'axios'
import Cards from './Cards'

function SearchResults(props) {
    const query = props.match.params.query;
    const [posts, setPosts] = useState([])
    useEffect(() => {
        axios({
            "method": "GET",
            "url": 'https://www.googleapis.com/youtube/v3/search',
            "params":{
                'part':'snippet',
                'maxResults':'20',
                'key':'[API_KEY]',
                'q':query
            }
        })
            .then((res) => {
                setPosts(res.data.items)
            })
            .catch((error) => {
                console.log(error)
            })
            console.log(posts);
    },[posts])

    return (
        <div>
            <Cards/>
        </div>
    )
}

export default SearchResults


问:
Java servlet not dispatching to another servlet
I have 2 servlets, "HomeController" and "SearchController". On the home.jsp I have a form that has a search box and when submitted actions to "Search"

```<code> <form action="Search" method="post" name="searchForm">
</code>```

So the first thing the SearchController does is:

```<code> @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!validator.isValidAlphaOnly(request.getParameter("breed"))) {
        request.setAttribute("error", "Breed search term invalid. Enter only letters");
        RequestDispatcher requestVar =  request.getRequestDispatcher("/Home");
        requestVar.forward(request, response);
    } else {
        processRequest(request, response);
    }
}
</code>```

Except is doesn't go to /Home even though I have mappings as follows:

```<code>  <servlet>
    <servlet-name>HomeController</servlet-name>
    <servlet-class>Controllers.HomeController</servlet-class>
</servlet>
<servlet>
    <servlet-name>SearchController</servlet-name>
    <servlet-class>Controllers.SearchController</servlet-class>
</servlet>
<servlet>
    <servlet-name>DogController</servlet-name>
    <servlet-class>Controllers.DogController</servlet-class>
</servlet>
<servlet>
    <servlet-name>LogoutController</servlet-name>
    <servlet-class>Controllers.LogoutController</servlet-class>
</servlet>
<servlet>
    <servlet-name>UpdateController</servlet-name>
    <servlet-class>Controllers.UpdateController</servlet-class>
</servlet>
<servlet>
    <servlet-name>AddController</servlet-name>
    <servlet-class>Controllers.AddController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SearchController</servlet-name>
    <url-pattern>/Search</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>LogoutController</servlet-name>
    <url-pattern>/Logout</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>UpdateController</servlet-name>
    <url-pattern>/Update</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>AddController</servlet-name>
    <url-pattern>/Add</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>DogController</servlet-name>
    <url-pattern>/Dog/View/*</url-pattern>
    <url-pattern>/Dog/Edit/*</url-pattern>
    <url-pattern>/Dog/Add</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>HomeController</servlet-name>
    <url-pattern>/Home</url-pattern>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</code>```

答:
Check if it is going into the condition.

Check if the response is getting committed before forward. It yes, then the forward will fail.

Worst case, it could be an issue with your app server.

Try using ServletContext.getNamedDispatcher("HomeController"); as an alternative.

ContentLicense: CC BY-SA 3.0

Body:
I have 2 servlets, "HomeController" and "SearchController". On the home.jsp I have a form that has a search box and when submitted actions to "Search"

 <form action="Search" method="post" name="searchForm">

So the first thing the SearchController does is:

 @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!validator.isValidAlphaOnly(request.getParameter("breed"))) {
        request.setAttribute("error", "Breed search term invalid. Enter only letters");
        RequestDispatcher requestVar =  request.getRequestDispatcher("/Home");
        requestVar.forward(request, response);
    } else {
        processRequest(request, response);
    }
}

Except is doesn't go to /Home even though I have mappings as follows:

  <servlet>
    <servlet-name>HomeController</servlet-name>
    <servlet-class>Controllers.HomeController</servlet-class>
</servlet>
<servlet>
    <servlet-name>SearchController</servlet-name>
    <servlet-class>Controllers.SearchController</servlet-class>
</servlet>
<servlet>
    <servlet-name>DogController</servlet-name>
    <servlet-class>Controllers.DogController</servlet-class>
</servlet>
<servlet>
    <servlet-name>LogoutController</servlet-name>
    <servlet-class>Controllers.LogoutController</servlet-class>
</servlet>
<servlet>
    <servlet-name>UpdateController</servlet-name>
    <servlet-class>Controllers.UpdateController</servlet-class>
</servlet>
<servlet>
    <servlet-name>AddController</servlet-name>
    <servlet-class>Controllers.AddController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SearchController</servlet-name>
    <url-pattern>/Search</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>LogoutController</servlet-name>
    <url-pattern>/Logout</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>UpdateController</servlet-name>
    <url-pattern>/Update</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>AddController</servlet-name>
    <url-pattern>/Add</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>DogController</servlet-name>
    <url-pattern>/Dog/View/*</url-pattern>
    <url-pattern>/Dog/Edit/*</url-pattern>
    <url-pattern>/Dog/Add</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>HomeController</servlet-name>
    <url-pattern>/Home</url-pattern>
    <url-pattern>/</url-pattern>
</servlet-mapping>


问:
what terminates a while loop when its expression is a conditional expression
the title says it all

in a loop likes this written in C

```<code>while(first_statement ? second_statement : third_statement)
</code>```

how can a loop like this be terminated?

答:
Taking they are just statements and not mathematical expressions,I think the while loop runs unless the expression inside it evaluates to 0.
So if n=5,
while(n--? 1:0)
This condition runs for 5 times. </p>

Body:
the title says it all

in a loop likes this written in C

while(first_statement ? second_statement : third_statement)

how can a loop like this be terminated?


问:
Is there a less costly option than gsutil rsync for backup to cloud storage?
We are currently utilizing the new coldline storage to backup files off site, the storage part is super cost effective. We are using gsutil rsync once a day to make sure our coldline storage is up to date.

The problem is that using gsutil rsync creates a massive number of class A requests, which are quite expensive. In this case it would be at least 5x the amount of the coldline storage making it no longer a good deal.

Are we going to have to custom code a custom solution to avoid these charges, is there a better option for this type of back, or is there some way get rsync to not generate so many requests?

答:
I think there is one pricing trick you can use if the expense is from the storage.objects.list operation. From the GCS operations pricing page: "When an operation applies to a bucket, such as listing the objects in a bucket, the default storage class set for that bucket determines the operation cost. So the trick is:

Set the bucket's default storage class to STANDARD

On upload, set the object's storage class to ARCHIVE (using gsutil cp -s ARCHIVE, or by setting the appropriate option on the upload requesting using the API).

As far as I understand: this now means you will be charged at the STANDARD rate for listing the bucket ($0.05/10k operations instead of $0.50/10k operations).

The one challenge is that gsutil rsync does not support the -s ARCHIVE flag that is supported by gsutil cp, so you won't be able to use it. You might want to look at other tools, like possibly rclone.


问:
FileNotFoundError: [Errno 2] No such file or directory: in jupyter notebook
```<code>from scipy.io import wavfile

train_audio_path = 'E:/'
filename = 'file_example_WAV_1MG'
sample_rate, samples = wavfile.read(train_audio_path + filename)
print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-27-cd74bbc41446> in <module>
      3 train_audio_path = 'E:/'
      4 filename = 'file_example_WAV_1MG'
----> 5 sample_rate, samples = wavfile.read(train_audio_path + filename)
      6 print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

E:\anaconda\lib\site-packages\scipy\io\wavfile.py in read(filename, mmap)
    262         mmap = False
    263     else:
--> 264         fid = open(filename, 'rb')
    265
    266     try:

FileNotFoundError: [Errno 2] No such file or directory: 'E:/file_example_WAV_1MG'
</code>```

I have a problem with my code. I tried to do everything but failed. I have no idea why this error is made. I changed path to everywhere from c to e but still not working at all. what's wrong in my code?

答:
I think you are missing the extension. Perhaps file_example_WAV_1MG.wav ?
Check it on your computer.

Body:
from scipy.io import wavfile

train_audio_path = 'E:/'
filename = 'file_example_WAV_1MG'
sample_rate, samples = wavfile.read(train_audio_path + filename)
print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-27-cd74bbc41446> in <module>
      3 train_audio_path = 'E:/'
      4 filename = 'file_example_WAV_1MG'
----> 5 sample_rate, samples = wavfile.read(train_audio_path + filename)
      6 print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))

E:\anaconda\lib\site-packages\scipy\io\wavfile.py in read(filename, mmap)
    262         mmap = False
    263     else:
--> 264         fid = open(filename, 'rb')
    265
    266     try:

FileNotFoundError: [Errno 2] No such file or directory: 'E:/file_example_WAV_1MG'

I have a problem with my code. I tried to do everything but failed. I have no idea why this error is made. I changed path to everywhere from c to e but still not working at all. what's wrong in my code?


问:
Why am I getting a HTTP 403 error with Pandas?
Looking to grab data from tables on a specific esport site and I appear to be struggling.

Was told that pandas library could help me achieve this with just a few lines.

```<code>import pandas as pd

tables = pd.read_html ('https://www.hltv.org/stats/teams/matches/5752/Cloud9')

print(tables[0])
</code>```

I try to edit it to make mine work yet I have no success.

```<code>import pandas as pd

from urllib.request import Request, urlopen

req = Request('https://www.hltv.org/stats/teams/matches/5752/Cloud9',     headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()

tables = pd.read_html ('https://www.hltv.org/stats/teams/matches/5752/Cloud9)

print(tables[0])
</code>```

I was lead to believe this may be the solution I was looking for, or something similar to it, but when I try to resolve the issue in this fashion, I have no success.

```<code>"Traceback (most recent call last):
  File "C:\Users\antho\OneDrive\Documents\Python\tables clloud9.py", line 6, in <module>
webpage = urlopen(req).read()
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 531, in open
response = meth(req, response)
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 641, in http_response
'http', request, response, code, msg, hdrs)
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 569, in error
return self._call_chain(*args)
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden"
</code>```

All I want at the moment is for the table on the link to be pulled.

答:
```<code>import pandas as pd

from urllib.request import Request, urlopen

req = Request('https://www.hltv.org/stats/teams/matches/5752/Cloud9',     headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()

tables = pd.read_html ('https://www.hltv.org/stats/teams/matches/5752/Cloud9') #here was the err

print(tables[0])
</code>```

Body:
Looking to grab data from tables on a specific esport site and I appear to be struggling.

Was told that pandas library could help me achieve this with just a few lines.

import pandas as pd

tables = pd.read_html ('https://www.hltv.org/stats/teams/matches/5752/Cloud9')

print(tables[0])

I try to edit it to make mine work yet I have no success.

import pandas as pd

from urllib.request import Request, urlopen

req = Request('https://www.hltv.org/stats/teams/matches/5752/Cloud9',     headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()

tables = pd.read_html ('https://www.hltv.org/stats/teams/matches/5752/Cloud9)

print(tables[0])

I was lead to believe this may be the solution I was looking for, or something similar to it, but when I try to resolve the issue in this fashion, I have no success.

"Traceback (most recent call last):
  File "C:\Users\antho\OneDrive\Documents\Python\tables clloud9.py", line 6, in <module>
webpage = urlopen(req).read()
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 531, in open
response = meth(req, response)
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 641, in http_response
'http', request, response, code, msg, hdrs)
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 569, in error
return self._call_chain(*args)
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
  File "C:\Users\antho\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden"

All I want at the moment is for the table on the link to be pulled.


问:
Not able to create a SignUp page using Django
I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model.
views.py

```<code>def SignUpView(request):

    if request.method == 'POST':
        user_form = SignUpForm(data=request.POST)
        profile_form = ProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            new_user = user_form.save(commit=False)
            new_profile = profile_form.save(commit=False)
            new_profile.user = new_user
            userName = new_user.username
            password = new_profile.password1
            new_user.save(commit=True)
            new_profile.save(commit=True)
            user = authenticate(username = userName, password = password)
            login(request, user)
            return redirect('blog-home')
    else:
        user_form = SignUpForm()
        profile_form = ProfileForm()

    context = {
        'user_form': user_form,
        'profile_form': profile_form,
    }

    return render(request, 'user/signup.html', context=context)
</code>```

forms.py:

```<code>class SignUpForm(UserCreationForm):
    class meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

class ProfileForm(forms.ModelForm):
    class meta:
        model = Profile
        fields = ['user', 'email']
</code>```

models.py:

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # img =
    date_of_birth = models.DateField(blank=True, null=True)
    bio = models.CharField(blank=True, max_length=500)
    location = models.CharField(blank=True, max_length=50)
    email = models.EmailField(unique=True, max_length=200)

    def __str__(self):
        return f'Profile for {self.user.username}'
</code>```

It is displaying an error message on the signup page as :
ValueError at /signup/
ModelForm has no model class specified.

答:
Did you try this to get the User model?

```<code>from django.contrib.auth import get_user_model
User = get_user_model()
</code>```

Body:
I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model.
views.py

def SignUpView(request):

    if request.method == 'POST':
        user_form = SignUpForm(data=request.POST)
        profile_form = ProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            new_user = user_form.save(commit=False)
            new_profile = profile_form.save(commit=False)
            new_profile.user = new_user
            userName = new_user.username
            password = new_profile.password1
            new_user.save(commit=True)
            new_profile.save(commit=True)
            user = authenticate(username = userName, password = password)
            login(request, user)
            return redirect('blog-home')
    else:
        user_form = SignUpForm()
        profile_form = ProfileForm()

    context = {
        'user_form': user_form,
        'profile_form': profile_form,
    }

    return render(request, 'user/signup.html', context=context)

forms.py:

class SignUpForm(UserCreationForm):
    class meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

class ProfileForm(forms.ModelForm):
    class meta:
        model = Profile
        fields = ['user', 'email']

models.py:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # img =
    date_of_birth = models.DateField(blank=True, null=True)
    bio = models.CharField(blank=True, max_length=500)
    location = models.CharField(blank=True, max_length=50)
    email = models.EmailField(unique=True, max_length=200)

    def __str__(self):
        return f'Profile for {self.user.username}'

It is displaying an error message on the signup page as :
ValueError at /signup/
ModelForm has no model class specified.

Body:
Did you try this to get the User model?

from django.contrib.auth import get_user_model
User = get_user_model()


问:
What is the best Scala library for writing/reading PNG image files?
What is the best Scala library for writing/reading PNG image files?   I'm looking for the Scala-equivalent of  libpng (c++) and  pypng (Python) </p>

答:
As java libraries can be used in scala; So you can use java library [javax imageIO] or [java awt] or both. You can find plenty of their examples on internet. Here I'm sharing one.

Below is sample code for the same.

```<code>import org.opencv.core.Mat
import javax.imageio.ImageIO
import java.io.ByteArrayInputStream
import java.awt.image.DataBufferByte
import org.opencv.core.CvType
import org.opencv.core.Core
import org.opencv.features2d.FeatureDetector
import org.opencv.core.MatOfKeyPoint
import org.opencv.features2d.Features2d
import org.opencv.highgui.Highgui
import java.awt.image.BufferedImage
import java.io.File

object OpenCVOps {

  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

  def imageToMat(byteArray: Array[Byte]): MatSer ={
      val bufferedImage = ImageIO.read(new ByteArrayInputStream(byteArray))
      val mat = new Mat(bufferedImage.getHeight(), bufferedImage.getWidth(), CvType.CV_8UC3);
      val data = bufferedImage.getRaster().getDataBuffer.asInstanceOf[DataBufferByte].getData();
      mat.put(0, 0, data);
      new MatSer(mat);
  }

  def matToImage(mat: Mat,file: String): Boolean ={

      val imageType = BufferedImage.TYPE_3BYTE_BGR;
      val image = new BufferedImage(mat.cols(),mat.rows(), imageType);
      val x = image.getRaster.getDataBuffer.asInstanceOf[DataBufferByte].getData
      mat.get(0,0,x)
      val fileName = new File("file")
      ImageIO.write(image, "jpg", fileName)

  }

  def detectFeatures(mat: Mat)
  {
    val featureDetector = FeatureDetector.create(FeatureDetector.SIFT)
    val matKeyPoint = new MatOfKeyPoint()
    featureDetector.detect(mat,matKeyPoint)
    println(mat.get(0, 0))
    println(matKeyPoint.toList())
    //writeToImage(mat,matKeyPoint)

  }

  def writeToImage(mat: Mat, matKeyPoint: MatOfKeyPoint){
    val outImage = new Mat()
    Features2d.drawKeypoints(mat, matKeyPoint, outImage)
    Highgui.imwrite("myfile.jpg",outImage)

  }

}
</code>```

Here is one more example ..

```<code>import javax.imageio.ImageIO

trait Settings {
  this: com.jme3.app.SimpleApplication =>

  protected val appSettings = new com.jme3.system.AppSettings(true)

  Seq(
    ("Width", 1920)
    , ("Height", 1080)
    , ("BitsPerPixel", 32)
    , ("Frequency", 60)
    , ("DepthBits", 24)
    , ("StencilBits", 0)
    , ("Samples", 2)
    , ("Fullscreen", false)
    , ("Title", "LW3D")
    , ("Renderer", com.jme3.system.AppSettings.LWJGL_OPENGL2)
    , ("AudioRenderer", com.jme3.system.AppSettings.LWJGL_OPENAL)
    , ("DisableJoysticks", true)
    , ("UseInput", true)
    , ("VSync", false)
    , ("FrameRate", 0)
    , ("SettingsDialogImage", "")
    , ("MinHeight", 1920)
    , ("MinWidth", 1080)
  ) foreach { case (k, v: Object) => appSettings.put(k, v) }

  appSettings.setIcons(
    List(
      ImageIO.read(getClass.getClassLoader.getResource("Yx/logo/Y256.png")),
      ImageIO.read(getClass.getClassLoader.getResource("Yx/logo/Y128.png")),
      ImageIO.read(getClass.getClassLoader.getResource("Yx/logo/Y64.png")),
      ImageIO.read(getClass.getClassLoader.getResource("Yx/logo/Y32.png")),
      ImageIO.read(getClass.getClassLoader.getResource("Yx/logo/Y16.png"))
    ).toArray
  )

  setSettings(appSettings)

  setShowSettings(false)
  setDisplayFps(true)
  setDisplayStatView(false)
  setPauseOnLostFocus(false)
}
</code>```

Body:
As java libraries can be used in scala; So you can use java library [javax imageIO] or [java awt] or both. You can find plenty of their examples on internet. Here I'm sharing one.

Below is sample code for the same.

import org.opencv.core.Mat
import javax.imageio.ImageIO
import java.io.ByteArrayInputStream
import java.awt.image.DataBufferByte
import org.opencv.core.CvType
import org.opencv.core.Core
import org.opencv.features2d.FeatureDetector
import org.opencv.core.MatOfKeyPoint
import org.opencv.features2d.Features2d
import org.opencv.highgui.Highgui
import java.awt.image.BufferedImage
import java.io.File

object OpenCVOps {

  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

  def imageToMat(byteArray: Array[Byte]): MatSer ={
      val bufferedImage = ImageIO.read(new ByteArrayInputStream(byteArray))
      val mat = new Mat(bufferedImage.getHeight(), bufferedImage.getWidth(), CvType.CV_8UC3);
      val data = bufferedImage.getRaster().getDataBuffer.asInstanceOf[DataBufferByte].getData();
      mat.put(0, 0, data);
      new MatSer(mat);
  }

  def matToImage(mat: Mat,file: String): Boolean ={

      val imageType = BufferedImage.TYPE_3BYTE_BGR;
      val image = new BufferedImage(mat.cols(),mat.rows(), imageType);
      val x = image.getRaster.getDataBuffer.asInstanceOf[DataBufferByte].getData
      mat.get(0,0,x)
      val fileName = new File("file")
      ImageIO.write(image, "jpg", fileName)

  }

  def detectFeatures(mat: Mat)
  {
    val featureDetector = FeatureDetector.create(FeatureDetector.SIFT)
    val matKeyPoint = new MatOfKeyPoint()
    featureDetector.detect(mat,matKeyPoint)
    println(mat.get(0, 0))
    println(matKeyPoint.toList())
    //writeToImage(mat,matKeyPoint)

  }

  def writeToImage(mat: Mat, matKeyPoint: MatOfKeyPoint){
    val outImage = new Mat()
    Features2d.drawKeypoints(mat, matKeyPoint, outImage)
    Highgui.imwrite("myfile.jpg",outImage)

  }

}

Here is one more example ..

import javax.imageio.ImageIO

trait Settings {
  this: com.jme3.app.SimpleApplication =>

  protected val appSettings = new com.jme3.system.AppSettings(true)

  Seq(
    ("Width", 1920)
    , ("Height", 1080)
    , ("BitsPerPixel", 32)
    , ("Frequency", 60)
    , ("DepthBits", 24)
    , ("StencilBits", 0)
    , ("Samples", 2)
    , ("Fullscreen", false)
    , ("Title", "LW3D")
    , ("Renderer", com.jme3.system.AppSettings.LWJGL_OPENGL2)
    , ("AudioRenderer", com.jme3.system.AppSettings.LWJGL_OPENAL)
    , ("DisableJoysticks", true)
    , ("UseInput", true)
    , ("VSync", false)
    , ("FrameRate", 0)
    , ("SettingsDialogImage", "")
    , ("MinHeight", 1920)
    , ("MinWidth", 1080)
  ) foreach { case (k, v: Object) => appSettings.put(k, v) }

  appSettings.setIcons(
    List(
      ImageIO.read(getClass.getClassLoader.getResource("Yx/logo/Y256.png")),
      ImageIO.read(getClass.getClassLoader.getResource("Yx/logo/Y128.png")),
      ImageIO.read(getClass.getClassLoader.getResource("Yx/logo/Y64.png")),
      ImageIO.read(getClass.getClassLoader.getResource("Yx/logo/Y32.png")),
      ImageIO.read(getClass.getClassLoader.getResource("Yx/logo/Y16.png"))
    ).toArray
  )

  setSettings(appSettings)

  setShowSettings(false)
  setDisplayFps(true)
  setDisplayStatView(false)
  setPauseOnLostFocus(false)
}


问:
Error in 'group by' stating its a character for looping through summarise R
still getting to grips with R, and as a newbie, as I have been doing most of my coding manual, ie copy and paste the same block of code 20 times. Here, I was trying to learn about looping and summarising. When I do the summarise with one individual dataset, it works fine, but now I try and loop it, it states its a character, so I added in 'as.numeric' to no prevail. Any advice would be helpful.

Error:

Error in UseMethod("group_by_") :
  no applicable method for 'group_by_' applied to an object of class "character"

```<code>#educationYears

fiv0_education <- subset(sf_education, Year  == '2005')
six0_education <- subset(sf_education, Year  == '2006')
sev0_education <- subset(sf_education, Year  == '2007')
eig0_education <- subset(sf_education, Year  == '2008')
nin0_education <- subset(sf_education, Year  == '2009')
ten_education <- subset(sf_education, Year  == '2010')
one_education <- subset(sf_education, Year  == '2011')
two_education <- subset(sf_education, Year  == '2012')
thr_education <- subset(sf_education, Year  == '2013')
for_education <- subset(sf_education, Year  == '2014')
fiv_education <- subset(sf_education, Year  == '2015')
six_education <- subset(sf_education, Year  == '2016')
sev_education <- subset(sf_education, Year  == '2017')
eig_education <- subset(sf_education, Year  == '2018')
nin_education <- subset(sf_education, Year  == '2019')

names <- c('fiv0', 'six0', 'sev0', 'eig0', 'nin0', 'ten', 'one', 'two', 'thr', 'for', 'fiv', 'six', 'sev', 'eig', 'nin')

test <- vector("list", length(names))

for (i in 1:length(names)) {
test[i] <- paste(names[i], '_education', sep = "", collapse = NULL) %>%
    group_by(as.numeric(as.character(Kod))) %>%
    summarise(Count=sum(as.numeric(as.character(Count))))
}
</code>```

答:
Here is a solution using built-in data set iris as an example. I believe it's easy to adapt to the problem in the question.

1. A solution with a for loop, like in the question.

```<code>library(dplyr)

names <- c('fiv0', 'six0', 'sev0')

test <- vector("list", length(names))
for (i in 1:length(names)) {
  tmp <- paste0(names[i], '_education')
  test[[i]] <- get(tmp, envir = .GlobalEnv) %>%
    mutate(Count = as.numeric(as.character(Count))) %>%
    group_by(Kod) %>%
    summarise(Count = sum(Count))
}

test
#[[1]]
## A tibble: 4 x 2
#    Kod Count
#  <int> <dbl>
#1     1   1.6
#2     2   3.7
#3     3   2.4
#4     4   4.6
#
#[[2]]
## A tibble: 4 x 2
#    Kod Count
#  <int> <dbl>
#1     1  24.5
#2     2  27.2
#3     3  19.1
#4     4  30.5
#
#[[3]]
## A tibble: 4 x 2
#    Kod Count
#  <int> <dbl>
#1     1  15.9
#2     2  18.9
#3     3  15.5
#4     4  16
</code>```

2. Here is another way, with purrr::map.

This code uses the data set already split in several with subset.

```<code>paste0(names, '_education') %>%
  mget(envir = .GlobalEnv) %>%
  purrr::map(
    function(X){
      X %>%
        mutate(Count = as.numeric(as.character(Count))) %>%
        group_by(Kod) %>%
        summarise(Count = sum(Count))
    }
  )
</code>```

3. Another purrr:map way, but this time from the original data set, with no need to subset multiple times first.

Note that the splitting column here is Species, in the question it's Year.

```<code>df1 %>%
  group_split(Species) %>%
  purrr::map(
    function(X){
      X %>%
        mutate(Count = as.numeric(as.character(Count))) %>%
        group_by(Kod) %>%
        summarise(Count = sum(Count))
    }
  )
</code>```

Data creation code.

```<code>set.seed(1234)
df1 <- iris[4:5]
names(df1)[1] <- "Count"
df1$Kod <- sample(4, 150, TRUE)
fiv0_education <- subset(df1, Species  == 'setosa')
six0_education <- subset(df1, Species  == 'virginica')
sev0_education <- subset(df1, Species  == 'versicolor')
</code>```

Body:
still getting to grips with R, and as a newbie, as I have been doing most of my coding manual, ie copy and paste the same block of code 20 times. Here, I was trying to learn about looping and summarising. When I do the summarise with one individual dataset, it works fine, but now I try and loop it, it states its a character, so I added in 'as.numeric' to no prevail. Any advice would be helpful.

Error:

Error in UseMethod("group_by_") :
  no applicable method for 'group_by_' applied to an object of class "character"

#educationYears

fiv0_education <- subset(sf_education, Year  == '2005')
six0_education <- subset(sf_education, Year  == '2006')
sev0_education <- subset(sf_education, Year  == '2007')
eig0_education <- subset(sf_education, Year  == '2008')
nin0_education <- subset(sf_education, Year  == '2009')
ten_education <- subset(sf_education, Year  == '2010')
one_education <- subset(sf_education, Year  == '2011')
two_education <- subset(sf_education, Year  == '2012')
thr_education <- subset(sf_education, Year  == '2013')
for_education <- subset(sf_education, Year  == '2014')
fiv_education <- subset(sf_education, Year  == '2015')
six_education <- subset(sf_education, Year  == '2016')
sev_education <- subset(sf_education, Year  == '2017')
eig_education <- subset(sf_education, Year  == '2018')
nin_education <- subset(sf_education, Year  == '2019')

names <- c('fiv0', 'six0', 'sev0', 'eig0', 'nin0', 'ten', 'one', 'two', 'thr', 'for', 'fiv', 'six', 'sev', 'eig', 'nin')

test <- vector("list", length(names))

for (i in 1:length(names)) {
test[i] <- paste(names[i], '_education', sep = "", collapse = NULL) %>%
    group_by(as.numeric(as.character(Kod))) %>%
    summarise(Count=sum(as.numeric(as.character(Count))))
}

Body:
Here is a solution using built-in data set iris as an example. I believe it's easy to adapt to the problem in the question.

1. A solution with a for loop, like in the question.

library(dplyr)

names <- c('fiv0', 'six0', 'sev0')

test <- vector("list", length(names))
for (i in 1:length(names)) {
  tmp <- paste0(names[i], '_education')
  test[[i]] <- get(tmp, envir = .GlobalEnv) %>%
    mutate(Count = as.numeric(as.character(Count))) %>%
    group_by(Kod) %>%
    summarise(Count = sum(Count))
}

test
#[[1]]
## A tibble: 4 x 2
#    Kod Count
#  <int> <dbl>
#1     1   1.6
#2     2   3.7
#3     3   2.4
#4     4   4.6
#
#[[2]]
## A tibble: 4 x 2
#    Kod Count
#  <int> <dbl>
#1     1  24.5
#2     2  27.2
#3     3  19.1
#4     4  30.5
#
#[[3]]
## A tibble: 4 x 2
#    Kod Count
#  <int> <dbl>
#1     1  15.9
#2     2  18.9
#3     3  15.5
#4     4  16

2. Here is another way, with purrr::map.

This code uses the data set already split in several with subset.

paste0(names, '_education') %>%
  mget(envir = .GlobalEnv) %>%
  purrr::map(
    function(X){
      X %>%
        mutate(Count = as.numeric(as.character(Count))) %>%
        group_by(Kod) %>%
        summarise(Count = sum(Count))
    }
  )

3. Another purrr:map way, but this time from the original data set, with no need to subset multiple times first.

Note that the splitting column here is Species, in the question it's Year.

df1 %>%
  group_split(Species) %>%
  purrr::map(
    function(X){
      X %>%
        mutate(Count = as.numeric(as.character(Count))) %>%
        group_by(Kod) %>%
        summarise(Count = sum(Count))
    }
  )

Data creation code.

set.seed(1234)
df1 <- iris[4:5]
names(df1)[1] <- "Count"
df1$Kod <- sample(4, 150, TRUE)
fiv0_education <- subset(df1, Species  == 'setosa')
six0_education <- subset(df1, Species  == 'virginica')
sev0_education <- subset(df1, Species  == 'versicolor')


问:
How to install let's encrypt ssl in Goautodial 4 CentOS 7?
I am having trouble in Goautodial 4 server that i installed recently. Bcz the index.php page it shows that ssl certificate is ok and installed, but when i login as user the agent.php page is unsecure. How can I manage that all the pages shows with https?
I would really appreciate some help.
Thanks </p>

答:
So far this is what i have done to install the let's encrypt ssl.

1- I have installed the EPEL repository as it is not available by default :

sudo yum install -y epel-release mod_ssl

2- Than I created virtual host for port 80

Created a file with server.domain.com.conf :

nano /etc/httpd/conf.d/server.domain.com.conf

and inserted inside this code :

<VirtualHost *:80>
  ServerName www.server.domain.com
  ServerAlias server.domain.com
  DocumentRoot /var/www/html/
</VirtualHost>

systemctl restart httpd

3- Installed the certbot client from the EPEL repository :

sudo yum install python-certbot-apache

4- Generated the certificate for the server.domain.com :

sudo certbot --apache -d server.domain.com

5- Entered yes for all the questions during installation and redirect all to https.

6- I set up a crontab for the renewal process :

sudo crontab -e

0 0 * * 1 / usr / bin / certbot renew >> /var/log/sslrenew.log

That's all.


问:
while updating pom xml - PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException
issue recently occurred after reinstalling intellij and now there are issues like: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target</p>

答:
Go to File -> Settings -> Tools -> Server Certificates , and check the box "Accept non-trusted Certificates Automatically". That might solve your problem.
Also check your jdk version. I had to change to 1.8.0_192 on my Intellij. I was trying to build a spring boot application.</p>


问:
How can I insert elements in an alphabetically sorted list in C?
I'm trying to implement a linked list consisting of Nodes which have a char item as a payload.
New nodes should be insered alphabetically.

When trying to retrieve the elements of the list, I receive a Segmentation Fault. That means I'm accessing an invalid address somehow.

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

typedef struct node {
    struct node *next;
    char *item;
} Node;

static Node *list = NULL;

void insert(char *item) {
    Node *currentNode = list;
    while (strcmp(currentNode->item, item) < 0) {
        printf("next..\n");
        currentNode = currentNode->next;
    }
    Node *new = malloc(sizeof(Node));
    new->item = item;
    Node *tmp = currentNode->next;
    currentNode->next = new;
    new->next = tmp;
}

void retrieve() {
    Node *current = list;
    while (current->next != NULL) {
        printf("%c", *(current->item));
        current = current->next;
    }
    printf("\n");
}

int main() {

    // Initialize.
    list = malloc(sizeof(Node));
    char a = 'a';
    list->item = &a;
    retrieve();

    char b = 'b';
    char c = 'c';

    insert(&b);
    retrieve();

    return 0;
}
</code>```

答:
The use of strcmp implies that item is a null terminated sequence of characters. But in main you pass a pointer to a single character which is by the way a local variable allocated on the stack. This is not a null terminated string.

You should use the call insert(strdup("abc")); for instance. strdup("abc") will copy the string given as argument in a block allocated with malloc. The returned address is of a null terminated string and can be inserted as item value in new item nodes.

Another problem is in the insertion function. You don't check if the end of list is reached. currentNode may be null.

There is another problem with the insertion function. It will not insert the item at the correct position. The faulty code searches the first node with an item bigger or equal to the item to insert. It then insert the item after the node. The order may thus be invalid since the node item may be bigger than the item to insert. The correct insertion should insert before the found node.

Here is a fixed version of insert:

```<code>void insert(char *item) {
    Node **nodePtr = &list;
    while (*nodePtr != NULL && strcmp((*nodePtr)->item, item) < 0) {
        printf("next..\n");
        nodePtr = &(*nodePtr)->next;
    }
    Node *new = malloc(sizeof(Node));
    new->item = item;
    new->next = *nodePtr;
    *nodePtr = new;
}
</code>```

In this code nodePtr is a pointer to a pointer on a node. It is initialized as a pointer to list which holds a pointer to the first node or null if the list is empty. nodePtr is updated to move along the list until the end is reached or the pointed node has an item big or equal to the item to insert. We insert the new node in front of it.

Body:
I'm trying to implement a linked list consisting of Nodes which have a char item as a payload.
New nodes should be insered alphabetically.

When trying to retrieve the elements of the list, I receive a Segmentation Fault. That means I'm accessing an invalid address somehow.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct node {
    struct node *next;
    char *item;
} Node;

static Node *list = NULL;

void insert(char *item) {
    Node *currentNode = list;
    while (strcmp(currentNode->item, item) < 0) {
        printf("next..\n");
        currentNode = currentNode->next;
    }
    Node *new = malloc(sizeof(Node));
    new->item = item;
    Node *tmp = currentNode->next;
    currentNode->next = new;
    new->next = tmp;
}

void retrieve() {
    Node *current = list;
    while (current->next != NULL) {
        printf("%c", *(current->item));
        current = current->next;
    }
    printf("\n");
}

int main() {

    // Initialize.
    list = malloc(sizeof(Node));
    char a = 'a';
    list->item = &a;
    retrieve();

    char b = 'b';
    char c = 'c';

    insert(&b);
    retrieve();

    return 0;
}

Body:
The use of strcmp implies that item is a null terminated sequence of characters. But in main you pass a pointer to a single character which is by the way a local variable allocated on the stack. This is not a null terminated string.

You should use the call insert(strdup("abc")); for instance. strdup("abc") will copy the string given as argument in a block allocated with malloc. The returned address is of a null terminated string and can be inserted as item value in new item nodes.

Another problem is in the insertion function. You don't check if the end of list is reached. currentNode may be null.

There is another problem with the insertion function. It will not insert the item at the correct position. The faulty code searches the first node with an item bigger or equal to the item to insert. It then insert the item after the node. The order may thus be invalid since the node item may be bigger than the item to insert. The correct insertion should insert before the found node.

Here is a fixed version of insert:

void insert(char *item) {
    Node **nodePtr = &list;
    while (*nodePtr != NULL && strcmp((*nodePtr)->item, item) < 0) {
        printf("next..\n");
        nodePtr = &(*nodePtr)->next;
    }
    Node *new = malloc(sizeof(Node));
    new->item = item;
    new->next = *nodePtr;
    *nodePtr = new;
}

In this code nodePtr is a pointer to a pointer on a node. It is initialized as a pointer to list which holds a pointer to the first node or null if the list is empty. nodePtr is updated to move along the list until the end is reached or the pointed node has an item big or equal to the item to insert. We insert the new node in front of it.


问:
Difference between confint and predict
I'm analyzing a linear model with 2 factors and I need to find a confidence interval for the response variable. As I understand it confint() and predict(, interval='confidence') both find confidence intervals so what is the difference between them?

答:
confint() finds confidence intervals on the model parameters

predict(., interval="confidence") finds confidence intervals on the model predictions

Title: Difference between confint and predict


答:
```<code># Make date into datetime
df['Date'] = pd.to_datetime(df['Date'])
# Get rid of time part
df['Day'] = df['Date'].dt.strftime('%Y-%m-%d')

# Taking rolling sum of Alarms
k = df.groupby('Day')['Alarm'].rolling(3).sum().reset_index()
# Take last set of consecutive 3's per day
k = k[k['Alarm']==3].groupby('Day').last()
# Capture the index of each row in the original data frame
k = k['level_1'].values
# Drop day column
df.drop(columns=['Day'], inplace=True)
# Join the rows together
df = pd.concat([df.loc[x-2:].head(3) for x in k])
</code>```

Output

```<code> Category                Date  Alarm
6         A 1999-11-10 12:07:00      1
7         A 1999-11-10 12:08:00      1
8         A 1999-11-10 12:09:00      1
15        B 1999-11-23 13:15:00      1
16        B 1999-11-23 13:16:00      1
17        B 1999-11-23 13:17:00      1
</code>```

Title: Find the last sequence of occurance of a value in a time series data in pandas

Body:
I have per minute time series data for 10 days with three columns: time stamp, category, alarm. Given a date, I want to groupby category and find the timestamps for which the alarm was set to 1 consecutively before the given date and create a dataframe from this subset.

   'Category'       'Date'              'Alarm'
0      A        1999-11-10 12:01:00        1
1      A        1999-11-10 12:02:00        1
2      A        1999-11-10 12:03:00        1
3      A        1999-11-10 12:04:00        1
4      A        1999-11-10 12:05:00        0
5      A        1999-11-10 12:06:00        0
.
.
.
1101   A        1999-11-13 10:07:00        1
1102   A        1999-11-13 10:08:00        1
1103   A        1999-11-13 10:09:00        1
1104   B        1999-11-23 13:09:00        0
1105   B        1999-11-23 13:10:00        0
1106   B        1999-11-23 13:11:00        1
1107   B        1999-11-23 13:12:00        1
1108   B        1999-11-23 13:13:00        1
1109   B        1999-11-23 13:14:00        0
.
.
.
.
2110   B        1999-11-26 13:13:00        0
2110   B        1999-11-26 13:14:00        0
2110   B        1999-11-26 13:15:00        1
2111   B        1999-11-26 13:16:00        1
2112   B        1999-11-26 13:17:00        1
2113   B        1999-11-26 13:18:00        1
2114   B        1999-11-26 13:19:00        1
2115   B        1999-11-26 13:20:00        0
2116   B        1999-11-26 13:21:00        0
2117   C        1999-12-02 17:11:00        1
.
.
.

I would like the output to be a new dataframe which has only these rows:

     'Category'       'Date'              'Alarm'
 1101   A        1999-11-13 10:07:00        1
 1102   A        1999-11-13 10:08:00        1
 1103   A        1999-11-13 10:09:00        1
 2110   B        1999-11-23 13:15:00        1
 2111   B        1999-11-23 13:16:00        1
 2112   B        1999-11-23 13:17:00        1
 2113   B        1999-11-23 13:18:00        1
 2114   B        1999-11-23 13:19:00        1

i.e, the rows in each group with the last consecutive sequence of 1s in alarm.
What I have tried:

df.groupby('category')['alarm'].apply(lambda x: x==1)

But this gives all the rows which have alarm as 1 and not just the last sequence of consecutive 1. Any directions on how to get this is appreciated. Thanks! :)

Edit 1: I just provided a subset of the dataframe.The the last consecutive sequence of 1s can occur any number of days before (e.g, if the timeseries is from Nov 1- Nov 10, for a category the last consecutive 1s could have occurred on nov 2 or nov 8. And the length of the 1s can also vary.

Body:
# Make date into datetime
df['Date'] = pd.to_datetime(df['Date'])
# Get rid of time part
df['Day'] = df['Date'].dt.strftime('%Y-%m-%d')

# Taking rolling sum of Alarms
k = df.groupby('Day')['Alarm'].rolling(3).sum().reset_index()
# Take last set of consecutive 3's per day
k = k[k['Alarm']==3].groupby('Day').last()
# Capture the index of each row in the original data frame
k = k['level_1'].values
# Drop day column
df.drop(columns=['Day'], inplace=True)
# Join the rows together
df = pd.concat([df.loc[x-2:].head(3) for x in k])

Output

 Category                Date  Alarm
6         A 1999-11-10 12:07:00      1
7         A 1999-11-10 12:08:00      1
8         A 1999-11-10 12:09:00      1
15        B 1999-11-23 13:15:00      1
16        B 1999-11-23 13:16:00      1
17        B 1999-11-23 13:17:00      1


问:
examine the pixel values of certain region of Interest in an image through 'statement'
I need help with a trivial problem. I have an image in which i defined a region of interest in that image.
now i want to examine the pixel values of my ROI, so that if the ROI color range e.g.between (105,105,105) and (255,255,255) then print 'left' otherwise print write.

The problem is that im unable to formulate to if statement

example code:

```<code>import cv2
import matplotlib.pyplot as pltl
import numpy as np

frame=cv2.imread('frame 8 sec.jpg')

ROI=frame[450:500,380:391]

**if the color of ROI is in range of (105,105,105) and (255,255,255):!!!???**

cv2.putText(frame,"Status {}".format('left'), (10,20), cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0,3))
else:
cv2.putText(frame,"Status {}".format('write'), (10,20), cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255,3))

cv2.imshow('img',frame)
counter=counter+1

cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

I would be grateful to get some help
thanks in advance

Body:
I need help with a trivial problem. I have an image in which i defined a region of interest in that image.
now i want to examine the pixel values of my ROI, so that if the ROI color range e.g.between (105,105,105) and (255,255,255) then print 'left' otherwise print write.

The problem is that im unable to formulate to if statement

example code:

import cv2
import matplotlib.pyplot as pltl
import numpy as np

frame=cv2.imread('frame 8 sec.jpg')

ROI=frame[450:500,380:391]

**if the color of ROI is in range of (105,105,105) and (255,255,255):!!!???**

cv2.putText(frame,"Status {}".format('left'), (10,20), cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0,3))
else:
cv2.putText(frame,"Status {}".format('write'), (10,20), cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255,3))

cv2.imshow('img',frame)
counter=counter+1

cv2.waitKey(0)
cv2.destroyAllWindows()

I would be grateful to get some help
thanks in advance

Body:
Try this.

if (ROI>=105).all() and (ROI<=255).all():


问:
Library providing various hash algorithms (MD5, SHA1, SHA256, etc) in Java?
Is there a simple library out there for Java in a Maven repository that will give me simple, one-liner hash methods for the popular hash functions such as MD5, SHA1, SHA256, and SHA512? I'd really hate to have to reinvent the wheel to do this. </p>

答: The DigestUtils class of Apache Commons Codec is suitable for the purpose of simplifying the use of the MessageDigest class, which appears to be what you are attempting to use in the first place.</p>


问:
Cannot create and open File using file handling
I am writing a basic code but run into an error when trying to open a file. I've had a rough break and am having to start from the basics. Following is the part of the code where I run into the error:

```<code>int main()
{
    string name;
    fstream file;
    cout << " Enter file name and type (E.g filname.txt) : ";
    cin >> name;
    file.open(name);
</code>```

Following is the error:

[Error] no matching function for call to 'std::basic_fstream<char>::open(std::string&)'

I am returning after a long break so I apologize for any inconsistencies.

答:
If the std::basic_fstream::open(std::string&) overload isn't available you are probably compiling using some C++ version prior to C++11.

Make sure you compile using at least C++11 and it should be fine.

Body:
I am writing a basic code but run into an error when trying to open a file. I've had a rough break and am having to start from the basics. Following is the part of the code where I run into the error:

int main()
{
    string name;
    fstream file;
    cout << " Enter file name and type (E.g filname.txt) : ";
    cin >> name;
    file.open(name);

Following is the error:

[Error] no matching function for call to 'std::basic_fstream<char>::open(std::string&)'

I am returning after a long break so I apologize for any inconsistencies.


问:
MSAccess subform using BIGINT (Large Number)
I'm getting the error when trying to link a form and a subform with ID beeing type BIGINT

"One of your parameter is invalid"

Form is done using record like :

```<code>ID : bigint
Value A : int
</code>```

Subform is done using record like :

```<code>ID : bigint
Value B : int
</code>```

The ID type cannot be change to INT as they come from SQL linked table created by an external software

```<code>Linked Master Field : ID
Linked Child Field : ID
</code>```

答:
As Gustav proposed :

Creating a value ID2: CLng(ID) and use this value to link the form solved the issue

Body:
I'm getting the error when trying to link a form and a subform with ID beeing type BIGINT

"One of your parameter is invalid"

Form is done using record like :

ID : bigint
Value A : int

Subform is done using record like :

ID : bigint
Value B : int

The ID type cannot be change to INT as they come from SQL linked table created by an external software

Linked Master Field : ID
Linked Child Field : ID


问:
django graphene rate limit (throttling)
I am building a REST Api on Django RF. I need to set a requests limit from IP. It's easy to do that for a regular Api endpoint in views.py just adding following settings

```<code>REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }
}
</code>```

But I also have a Graphene django for a graphql api.

How can I set up a rate limit for that view? I have tried django-ratelimit, but it didn't work for me.

答:
The issue was solved by customising GraphQL view to the following:</p>

```<code>from graphene_django.views import GraphQLView

class CustomGraphQL(GraphQLView):
    def parse_body(self, request):
        if isinstance(request, Request):
            return request.data
        return super().parse_body(request)

    @classmethod
    def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        view = authentication_classes((TokenAuthentication,))(view)
        view = throttle_classes((AnonRateThrottle, AnonMinutesThrottle,
                                 AnonSecondsThrottle, UserRateThrottle))(view)
        view = api_view(['GET', 'POST'])(view)
        return view
</code>```

Title: django graphene rate limit (throttling)

Body:
I am building a REST Api on Django RF. I need to set a requests limit from IP. It's easy to do that for a regular Api endpoint in views.py just adding following settings

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }
}

But I also have a Graphene django for a graphql api.

How can I set up a rate limit for that view? I have tried django-ratelimit, but it didn't work for me.

Body:
The issue was solved by customising GraphQL view to the following:

from graphene_django.views import GraphQLView

class CustomGraphQL(GraphQLView):
    def parse_body(self, request):
        if isinstance(request, Request):
            return request.data
        return super().parse_body(request)

    @classmethod
    def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        view = authentication_classes((TokenAuthentication,))(view)
        view = throttle_classes((AnonRateThrottle, AnonMinutesThrottle,
                                 AnonSecondsThrottle, UserRateThrottle))(view)
        view = api_view(['GET', 'POST'])(view)
        return view


问:
Issues when Debugging PHP in VSCode using Docker and WSL2
I've been working with VSCode + Docker in Windows for some years now, and managed to have a fully working dev environment without any issues.

Recently i setup a new development environment with WSL2. Moved all my projects, libraries, CLIs, etc, into WSL, using Docker Windows with WSL2 containers and VSCode on Windows with remote connection to WSL. Everything is working very smoothly and i like the fact i can have everything separated.

But recently i came across an issue that i'm unable to solve, i lost the ability to debug PHP files.
I'm using VSCode Remote WSL extension to work on my projects inside WSL, but when i try to debug, nothing happens.

I have tree debugging settings in my VSCode for each dev environment that i use (Windows, MacOS and WSL). All work except for the WSL. When i try to debug with WSL, literally nothing happens, no output erros, no debug console information, nothing...

Here are my VSCode debug settings:

```<code>{
    "version": "0.2.0",
    "configurations": [{
            "name": "Listen for XDebug Win10",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "log": true,
            "externalConsole": false,
            "pathMappings": {
                "/var/www/project-a/api": "\\\\wsl$\\Ubuntu\\home\\ubuntu\\PROJECTS\\project-a\\api",
            },
            "ignore": [
                "**/vendor/**/*.php"
            ]
        },
        {
            "name": "Listen for XDebug MacOS",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "log": true,
            "externalConsole": false,
            "pathMappings": {
                "/var/www/project-a/api": "/Users/ricky/PROJECTS/project-a/api",
            },
            "ignore": [
                "**/vendor/**/*.php"
            ]
        },
        {
            "name": "Listen for XDebug WSL",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "log": true,
            "externalConsole": false,
            "pathMappings": {
                "/var/www/project-a/api": "/home/ubuntu/PROJECTS/project-a/api",
            },
            "ignore": [
                "**/vendor/**/*.php"
            ]
        },
    ]
}
</code>```

What am i doing wrong? Any ideas on how to solve this issue?

### UPDATE: I've changed the original right answer to a new one. Although @romain-prevost's solution worked, I think @dark's approach is wayyy much simpler :)

答:
I have been struggling with PHP xdebug in Docker using WSL2 as well. It all comes down to the remote host.

What is your xdebug config in php.ini? You should set xdebug.remote_host to your WSL2 local IP address (which you can get in a terminal using hostame -I).

I have tried several times to set the remote host IP address in my Docker—composing a file to pass to the container on startup—but it always fails. Thanks to another StackOverflow answer, however, I have a solution for that too:

In WSL2, set an environment variable for your local IP in your .bashrc file. I have set mine to

```<code>export IP=$(hostname -I)
</code>```

In your Docker compose file for the PHP service, pass the IP address as a new host with the extra_hosts key. For compose v3.2 it is

```<code>extra_hosts:
 - "docker.host:${IP}"
</code>```

You can look here for other compose versions: https://docs.docker.com/compose/compose-file/

Finally, edit your php.ini file for xdebug to have this line:

```<code>xdebug.remote_host=docker.host
</code>```

Your container will be able to reach the WSL2 distribution with your docker.host and connect to the port you set for xdebug.

I spent a lot of time figuring this out, mainly because WSL2 was released officially a few days ago and there are not many guides about it.
It was not so complicated in the end, but without the extra_hosts key I could not get the WSL2 IP address to work. It was in the container and in xdebug config, but I always got an error about the resource being unavailable, so don't forget it

Body:
I've been working with VSCode + Docker in Windows for some years now, and managed to have a fully working dev environment without any issues.

Recently i setup a new development environment with WSL2. Moved all my projects, libraries, CLIs, etc, into WSL, using Docker Windows with WSL2 containers and VSCode on Windows with remote connection to WSL. Everything is working very smoothly and i like the fact i can have everything separated.

But recently i came across an issue that i'm unable to solve, i lost the ability to debug PHP files.
I'm using VSCode Remote WSL extension to work on my projects inside WSL, but when i try to debug, nothing happens.

I have tree debugging settings in my VSCode for each dev environment that i use (Windows, MacOS and WSL). All work except for the WSL. When i try to debug with WSL, literally nothing happens, no output erros, no debug console information, nothing...

Here are my VSCode debug settings:

{
    "version": "0.2.0",
    "configurations": [{
            "name": "Listen for XDebug Win10",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "log": true,
            "externalConsole": false,
            "pathMappings": {
                "/var/www/project-a/api": "\\\\wsl$\\Ubuntu\\home\\ubuntu\\PROJECTS\\project-a\\api",
            },
            "ignore": [
                "**/vendor/**/*.php"
            ]
        },
        {
            "name": "Listen for XDebug MacOS",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "log": true,
            "externalConsole": false,
            "pathMappings": {
                "/var/www/project-a/api": "/Users/ricky/PROJECTS/project-a/api",
            },
            "ignore": [
                "**/vendor/**/*.php"
            ]
        },
        {
            "name": "Listen for XDebug WSL",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "log": true,
            "externalConsole": false,
            "pathMappings": {
                "/var/www/project-a/api": "/home/ubuntu/PROJECTS/project-a/api",
            },
            "ignore": [
                "**/vendor/**/*.php"
            ]
        },
    ]
}

What am i doing wrong? Any ideas on how to solve this issue?

### UPDATE: I've changed the original right answer to a new one. Although @romain-prevost's solution worked, I think @dark's approach is wayyy much simpler :)

Body:
I have been struggling with PHP xdebug in Docker using WSL2 as well. It all comes down to the remote host.

What is your xdebug config in php.ini? You should set xdebug.remote_host to your WSL2 local IP address (which you can get in a terminal using hostame -I).

I have tried several times to set the remote host IP address in my Docker—composing a file to pass to the container on startup—but it always fails. Thanks to another StackOverflow answer, however, I have a solution for that too:

In WSL2, set an environment variable for your local IP in your .bashrc file. I have set mine to

export IP=$(hostname -I)

In your Docker compose file for the PHP service, pass the IP address as a new host with the extra_hosts key. For compose v3.2 it is

extra_hosts:
 - "docker.host:${IP}"

You can look here for other compose versions: https://docs.docker.com/compose/compose-file/

Finally, edit your php.ini file for xdebug to have this line:

xdebug.remote_host=docker.host

Your container will be able to reach the WSL2 distribution with your docker.host and connect to the port you set for xdebug.

I spent a lot of time figuring this out, mainly because WSL2 was released officially a few days ago and there are not many guides about it.
It was not so complicated in the end, but without the extra_hosts key I could not get the WSL2 IP address to work. It was in the container and in xdebug config, but I always got an error about the resource being unavailable, so don't forget it


问:
Create a method that will replace all repeating characters with a given character. Method signature will be replaceRepeating(String, char)
Create a method that will replace all repeating characters with a given character. Method
signature will be replaceRepeating(String, char). For example, if I invoke
replaceRepeating(“Krishnan Aravind”, ‘’), the output should be “Ksh *vd”. The
repeating characters are r, i, n and a. They all have been replaced with *

答:
There can be multiple ways to solve this problem.

The one that seems pretty common to me would be using a hash table. The exact name for the data structure will depend on the programming language you are using. Ex - unordered map in c++.

The peculiarity of this data structure is that the time complexity of insertion, removal, and deletion operations is O(1).

Let's look at the algorithm

Your Map will have characters as keys and their count as value for that key in the hashtable.

Iterate over the whole string and store the characters and their counts as key-value pairs.
Iterate again over the string. This time for each character, look at its count from the hostable. If the count exceeds one, then replace it with the character that is passed in the second argument of your replaceRepeating function.

You can google the implementation details. Here is the link for c++
unordered map