问:
Only omit NA that does not overlap with other NA in a certain column
Let say I have a data frame that looks like this :

```<code>>df
col1   col2   col3

 12    NA      2
 21    11     NA
 NA     2     NA
 3     NA     NA
 NA    NA      4
 8     12      5
 41    39      9
</code>```

I want to omit the NA, but the NA in col3 is a piece of precious information, so I don't want to fill it in with any other value without more information. Thus, I want to omit the NA that does not overlap with the NA in col3 only.

So it would look like this :

```<code>>df
col1   col2   col3

 21    11     NA
 NA     2     NA
 3     NA     NA
 8     12      5
 41    39      9
</code>```

The only reason why NA in col2 and col1 is still there because deleting their row will cause the NA in col3 to be deleted also, which is what I want to prevent. Thus, I can tolerate those leftover NA from col1 and col2.

Is there any convenient way for me to do this or any package to tackle this problem? I have tried using filter :

```<code>df <- df %>% filter(complete.cases(df[, -3]))
</code>```

But it became like this instead since there is overlapping NA :

```<code> >df
 col1   col2   col3

 21    11     NA
 8     12      5
 41    39      9
</code>```

Any thoughts? Thanks in advance~

答:
We can create a condition with rowSums

```<code>df1[!(rowSums(is.na(df1[-3])) > 0 & !is.na(df1[[3]])),]
#  col1 col2 col3
#2   21   11   NA
#3   NA    2   NA
#4    3   NA   NA
#6    8   12    5
#7   41   39    9
</code>```

When we do the rowSums(is.na(df1[-3])) > 0, it is checking for any NA in the first two columns and returns TRUE for those cases

```<code>rowSums(is.na(df1[-3])) > 0
#[1]  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE
</code>```

But, we want to remove that first row because there is no NA for that row in 'col3'

Next we check for NAs in 'col3'

```<code>is.na(df1[[3]])
#[1] FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE
</code>```

Wherever, there is TRUE, we want to keep it.  So, if we do &, it will return the NA common in both

```<code>(rowSums(is.na(df1[-3])) > 0 & !is.na(df1[[3]]))
#[1]  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE
</code>```

i.e. 1st and 5th row have NA in both blocks of columns.  Negating it changes TRUE-> FALSE and FALSE-> TRUE

```<code>!(rowSums(is.na(df1[-3])) > 0 & !is.na(df1[[3]]))
#[1] FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE
</code>```

which are the rows that can have both sets not having any NA or 'col3' having NA and other rows may or not have NA

Or use the same logic in filter

```<code>library(dplyr)
df1  %>%
     filter(!(rowSums(is.na(.[-3])) > 0 & !is.na(col3)))
</code>```

data

```<code>df1 <- structure(list(col1 = c(12L, 21L, NA, 3L, NA, 8L, 41L), col2 = c(NA,
11L, 2L, NA, NA, 12L, 39L), col3 = c(2L, NA, NA, NA, 4L, 5L,
9L)), class = "data.frame", row.names = c(NA, -7L))
</code>```

Body:
Let say I have a data frame that looks like this :

>df
col1   col2   col3

 12    NA      2
 21    11     NA
 NA     2     NA
 3     NA     NA
 NA    NA      4
 8     12      5
 41    39      9

I want to omit the NA, but the NA in col3 is a piece of precious information, so I don't want to fill it in with any other value without more information. Thus, I want to omit the NA that does not overlap with the NA in col3 only.

So it would look like this :

>df
col1   col2   col3

 21    11     NA
 NA     2     NA
 3     NA     NA
 8     12      5
 41    39      9

The only reason why NA in col2 and col1 is still there because deleting their row will cause the NA in col3 to be deleted also, which is what I want to prevent. Thus, I can tolerate those leftover NA from col1 and col2.

Is there any convenient way for me to do this or any package to tackle this problem? I have tried using filter :

df <- df %>% filter(complete.cases(df[, -3]))

But it became like this instead since there is overlapping NA :

 >df
 col1   col2   col3

 21    11     NA
 8     12      5
 41    39      9

Any thoughts? Thanks in advance~

Body:
We can create a condition with rowSums

df1[!(rowSums(is.na(df1[-3])) > 0 & !is.na(df1[[3]])),]
#  col1 col2 col3
#2   21   11   NA
#3   NA    2   NA
#4    3   NA   NA
#6    8   12    5
#7   41   39    9

When we do the rowSums(is.na(df1[-3])) > 0, it is checking for any NA in the first two columns and returns TRUE for those cases

rowSums(is.na(df1[-3])) > 0
#[1]  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE

But, we want to remove that first row because there is no NA for that row in 'col3'

Next we check for NAs in 'col3'

is.na(df1[[3]])
#[1] FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE

Wherever, there is TRUE, we want to keep it.  So, if we do &, it will return the NA common in both

(rowSums(is.na(df1[-3])) > 0 & !is.na(df1[[3]]))
#[1]  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE

i.e. 1st and 5th row have NA in both blocks of columns.  Negating it changes TRUE-> FALSE and FALSE-> TRUE

!(rowSums(is.na(df1[-3])) > 0 & !is.na(df1[[3]]))
#[1] FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE

which are the rows that can have both sets not having any NA or 'col3' having NA and other rows may or not have NA

Or use the same logic in filter

library(dplyr)
df1  %>%
     filter(!(rowSums(is.na(.[-3])) > 0 & !is.na(col3)))

data

df1 <- structure(list(col1 = c(12L, 21L, NA, 3L, NA, 8L, 41L), col2 = c(NA,
11L, 2L, NA, NA, 12L, 39L), col3 = c(2L, NA, NA, NA, 4L, 5L,
9L)), class = "data.frame", row.names = c(NA, -7L))


来源: stackexchange

问:
How to add the items in subset in c & store them in some array or some datatype so I can access each sum for further comparison?
I have generated subset of a set I want to calculate the sum of that set like the output is:

```<code>Enter the elements of main set :3
1
2
There are 8 subsets
Subset 7 = 3 1 2
Subset 6 = 1 2
Subset 5 = 3 2
Subset 4 = 2
Subset 3 = 3 1
Subset 2 = 1
Subset 1 = 3
Subset 0 =
</code>```

Here from the output, I want to calculate sum  1+2+3,1+2,3+2,...same for all subset, but sum should be in that way I can access each of the sums for further comparison how should I do that?

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

void print_subset(int subset, int *set) {
    int pos=0;
    printf("Subset %d = ", subset);
    while (subset) {
        if (subset & 1) {
            printf("%d ", set[pos]);
        }
        subset >>= 1;
        pos++;
    }
    printf("\n");
}

int main() {
    int no_of_element=3;
    int no_of_subset,x,a[50];

    printf("Enter the elements of main set :");
    for(x=0;x<no_of_element;x++)
        scanf("%d",&a[x]);

    no_of_subset= (1 << no_of_element);
    printf("There are %d subsets\n", no_of_subset);

    for (; no_of_subset--;) {
        print_subset(no_of_subset, a);
    }
}
</code>```

答:
Here your code with sum:

```<code>void print_subset(int subset, int *set) {
    int pos=0;
    int sum=0;
    printf("Subset %d = ", subset);
    while (subset) {
        if (subset & 1) {
            printf("%d ", set[pos]);
            sum+=set[pos];
        }
        subset >>= 1;
        pos++;
    }
    printf("==> Sum = %d \n", sum);
}

int main() {
    int no_of_element=3;
    int no_of_subset,x,a[50];

    printf("Enter the elements of main set :");
    for(x=0;x<no_of_element;x++)
        scanf("%d",&a[x]);

    no_of_subset= (1 << no_of_element);
    printf("There are %d subsets\n", no_of_subset);

    for (; no_of_subset--;) {
        print_subset(no_of_subset, a);
    }
}
</code>```

Result:

ContentLicense: CC BY-SA 4.0

Body:
I have generated subset of a set I want to calculate the sum of that set like the output is:

Enter the elements of main set :3
1
2
There are 8 subsets
Subset 7 = 3 1 2
Subset 6 = 1 2
Subset 5 = 3 2
Subset 4 = 2
Subset 3 = 3 1
Subset 2 = 1
Subset 1 = 3
Subset 0 =

Here from the output, I want to calculate sum  1+2+3,1+2,3+2,...same for all subset, but sum should be in that way I can access each of the sums for further comparison how should I do that?

#include <stdio.h>

void print_subset(int subset, int *set) {
    int pos=0;
    printf("Subset %d = ", subset);
    while (subset) {
        if (subset & 1) {
            printf("%d ", set[pos]);
        }
        subset >>= 1;
        pos++;
    }
    printf("\n");
}

int main() {
    int no_of_element=3;
    int no_of_subset,x,a[50];

    printf("Enter the elements of main set :");
    for(x=0;x<no_of_element;x++)
        scanf("%d",&a[x]);

    no_of_subset= (1 << no_of_element);
    printf("There are %d subsets\n", no_of_subset);

    for (; no_of_subset--;) {
        print_subset(no_of_subset, a);
    }
}

Body:
Here your code with sum:

void print_subset(int subset, int *set) {
    int pos=0;
    int sum=0;
    printf("Subset %d = ", subset);
    while (subset) {
        if (subset & 1) {
            printf("%d ", set[pos]);
            sum+=set[pos];
        }
        subset >>= 1;
        pos++;
    }
    printf("==> Sum = %d \n", sum);
}

int main() {
    int no_of_element=3;
    int no_of_subset,x,a[50];

    printf("Enter the elements of main set :");
    for(x=0;x<no_of_element;x++)
        scanf("%d",&a[x]);

    no_of_subset= (1 << no_of_element);
    printf("There are %d subsets\n", no_of_subset);

    for (; no_of_subset--;) {
        print_subset(no_of_subset, a);
    }
}

Result:


问:
How to calculate average asymptotic running time in Big-O notation?
Trying to understand Asymptotic notations which I understand is used to describe performance of an algorithm. Am I correct in saying that there is worst, best and average case scenarios? So for example, for the following piece of code, what is the average asymptotic running time in Big-O notation?

```<code>for (int i = 0; i < size; i++)
{
    printf("%d\n", i);
}
for (int i = 0; i < size; i++)
{
    for (int j = 0; j < size; j++)
    {
        printf("%d\n", i + j);
    }
}
</code>```

Would it be O(n^2)?

答:
Am I correct in saying that there is worst, best and average case scenarios?

A case is just some subset of all possible inputs, possibly a subset that has one input of all possible input sizes. So for instances, a case for a sorting algorithm might be some subset of the set of all possible input arrays, and maybe just those subsets that have exactly one element of each input size. Using this definition, the worst case would be the subset of inputs such that they cause the algorithm to execute the most instructions for the given input size; the best case would be the set of inputs that require the least number of steps at each input size; and the average case would be like the expected value of running types over all possible instances at each size (by the simple definition above, the average "case" is not really a true case at all, more like a hypothetical case).

To every case we may associate an asymptotic bound - upper, lower, or both. Typically of interest are upper bounds on the worst-case, and sometimes lower-bounds on the best-case. But it's not incorrect to speak of an upper bound on the best case or a lower bound on the worst case.

The code you've posted always does an amount of work proportional to the square of size's value. In that sense it is O(size^2). It is also Omega and Theta of size^2. If the algorithm gets input whose size in bits is proportional to size, then this is the true complexity. If the algorithm gets the value of size as input (represented using log(size) bits) then the complexity is actually exponential - the complexity in terms of size might be called pseudopolynomial.

Body:
Trying to understand Asymptotic notations which I understand is used to describe performance of an algorithm. Am I correct in saying that there is worst, best and average case scenarios? So for example, for the following piece of code, what is the average asymptotic running time in Big-O notation?

for (int i = 0; i < size; i++)
{
    printf("%d\n", i);
}
for (int i = 0; i < size; i++)
{
    for (int j = 0; j < size; j++)
    {
        printf("%d\n", i + j);
    }
}

Would it be O(n^2)?


问:
How to open file from VSCode file explorer in same window
Using cmd+shift+e I can highlight the file explorer tab and then use vim keybindings to select a given file. However, I've only figured out how to open a selected file in a new editor pane (Ctrl+Enter).

Is there a shortcut to open it in the same pane? Can I change the behavior of the Ctrl+Enter shortcut? A pointer to the right docs would also be helpful.

答:
This closest action is filesExplorer.openFilePreserveFocus, which is bound by default to Space.

This will open the file currently selected in a new tab, but it won't move your cursor to it.

You can use the cmd+shift+e keybinding to get back to your editor, though!


问:
error: no matching function for call to 'getline'
```<code>#include<iostream>
#include<string>
using namespace std;
int main(){
    //initializing two string

     string s2,s1="hello";

     cout<<s2<<s1;

     cout<<endl;
     //transferring(copying) data from s1 to s2
       getline(s1,s2);

     cout<<s2<<s1;
}
</code>```

答:
You are using getline wrong, please take a look at: http://www.cplusplus.com/reference/string/string/getline/

The getline function takes 2 parameters (a Istream and a string, instead of two times a string), that is the reason why you get the error.

If you just want to copy a string, you can use the following code:

```<code>std::string s1 = "myString";
std::string s2 = s1;
</code>```

Body:
You are using getline wrong, please take a look at: http://www.cplusplus.com/reference/string/string/getline/

The getline function takes 2 parameters (a Istream and a string, instead of two times a string), that is the reason why you get the error.

If you just want to copy a string, you can use the following code:

std::string s1 = "myString";
std::string s2 = s1;


问:
Setting HTTP Proxy on AWS API Gateway via Cloudformation
Thanks for the help in advance.

Currently using cloudformation templates to deploy a simple API to AWS as part of a POC for moving from Azure to AWS API management.

I have got everything working except i have not been able to figure out the YAML AWS extension for setting the HTTP proxy checkbox for the HTTP request.

Sample YAML below. I know this will not set that checkbox (as i have tested it and it worked minus that problem), but on this page

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-integration.html

i cannot see a extension that sets this option? Has AWS not done this yet

```<code>AWSTemplateFormatVersion: '2010-09-09'
Resources:
  PlayersAPI:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: RAH API
      Description: A demo API for testing
      Body:
        swagger: '2.0'
        info:
          title: test api
          description: test api
          version: 1.0.1
          contact:
            name: SH
            email: test@mailinator.com
        paths:
          "/heartbeat":
            get:
              description: Checks the API is working
              produces:
              - application/json
              responses:
                '200':
                  description: API Response information
              x-amazon-apigateway-integration:
                type: http
                responses:
                  default:
                    statusCode: '200'
                httpMethod: GET
                uri: https://api.example.com
</code>```

答:
This works for me:</p>

```<code>resources:
  Resources:
    ProxyResource:
      Type: AWS::ApiGateway::Resource
      Properties:
        ParentId:
          Fn::GetAtt:
            - ApiGatewayRestApi # our default Rest API logical ID
            - RootResourceId
        PathPart: "{proxy+}" # the endpoint in your API that is set as proxy
        RestApiId:
          Ref: ApiGatewayRestApi
    ProxyMethod:
      Type: AWS::ApiGateway::Method
      Properties:
        ResourceId:
          Ref: ProxyResource
        RestApiId:
          Ref: ApiGatewayRestApi
        HttpMethod: GET # the method of your proxy. Is it GET or POST or ... ?
        MethodResponses:
          - StatusCode: 200
        Integration:
          IntegrationHttpMethod: GET
          Type: HTTP_PROXY
          Uri: http://bucket.mybucket.co.s3.eu-west-1.amazonaws.com/{proxy} # the URL you want to set a proxy to
          IntegrationResponses:
            - StatusCode: 200
        AuthorizationType: NONE
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Thanks for the help in advance.

Currently using cloudformation templates to deploy a simple API to AWS as part of a POC for moving from Azure to AWS API management.

I have got everything working except i have not been able to figure out the YAML AWS extension for setting the HTTP proxy checkbox for the HTTP request.

Sample YAML below. I know this will not set that checkbox (as i have tested it and it worked minus that problem), but on this page

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-integration.html

i cannot see a extension that sets this option? Has AWS not done this yet

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  PlayersAPI:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: RAH API
      Description: A demo API for testing
      Body:
        swagger: '2.0'
        info:
          title: test api
          description: test api
          version: 1.0.1
          contact:
            name: SH
            email: test@mailinator.com
        paths:
          "/heartbeat":
            get:
              description: Checks the API is working
              produces:
              - application/json
              responses:
                '200':
                  description: API Response information
              x-amazon-apigateway-integration:
                type: http
                responses:
                  default:
                    statusCode: '200'
                httpMethod: GET
                uri: https://api.example.com

Body:
This works for me:

resources:
  Resources:
    ProxyResource:
      Type: AWS::ApiGateway::Resource
      Properties:
        ParentId:
          Fn::GetAtt:
            - ApiGatewayRestApi # our default Rest API logical ID
            - RootResourceId
        PathPart: "{proxy+}" # the endpoint in your API that is set as proxy
        RestApiId:
          Ref: ApiGatewayRestApi
    ProxyMethod:
      Type: AWS::ApiGateway::Method
      Properties:
        ResourceId:
          Ref: ProxyResource
        RestApiId:
          Ref: ApiGatewayRestApi
        HttpMethod: GET # the method of your proxy. Is it GET or POST or ... ?
        MethodResponses:
          - StatusCode: 200
        Integration:
          IntegrationHttpMethod: GET
          Type: HTTP_PROXY
          Uri: http://bucket.mybucket.co.s3.eu-west-1.amazonaws.com/{proxy} # the URL you want to set a proxy to
          IntegrationResponses:
            - StatusCode: 200
        AuthorizationType: NONE


问:
How to insert API response array string into database
I am trying to integrate the Bank Payment Gateway where data submission and processes is working very well but the success response as below received is not being inserted into database as it is a string in the form of an array.

```<code>BRN=837740&STC=000&RMK=success&TRN=5230896525&TET=2020/02/08 11:54:18 PM&PMD=CD&RID=253357&VER=1.0&CID=3636&TYP=Test&CRN=802406&CNY=INR&AMT=10000.00
</code>```

Foe eg: in this code BRN is a parameter and 837740 is its returned value similarly STC is parameter and 000 is its returned value.

Now I want to set all these values in a php variables so to insert in the data, if no value is returned then null should be stored in db for eg;

```<code>BRN=837741&STC=111&RMK=failure&TRN=1172146589&TET=&PMD=AIB&RID=126036&VER=1.0&CID=3636&TYP=Test&CRN=740076&CNY=INR&AMT=10000.00
</code>```

I tried below code which worked if all parameter has returned values if not then it is not working as delimiter sequence disturbed.

```<code>$chunks = preg_split('/(=|&)/', $qStr,-1, PREG_SPLIT_NO_EMPTY);
    //print_r($chunks);

    echo '```';
    print_r($chunks);
    echo '```';
/*
    echo "<br>";
    echo "<br>";

    $nweString = $chunks[0];
    for($i=1; $i<count($chunks); $i++) {
   // $nweString .= ':'.$chunks[$i];
    }
    echo $nweString;
    */

    echo "<br>";
    echo "<br>";
    echo "BRN = " . $BRN = $chunks[1] . "<br>";
//  echo "BRN = " . $BRN = $chunks[2] . "<br>";
    echo "STC = " . $STC = $chunks[3] . "<br>";
//  echo "BRN = " . $BRN = $chunks[4] . "<br>";
    if ($chunks[5] == "success") {$txtclr1 = '09CB00';}
    echo "<font color='$txtclr1'>" ."RMK = " . $RMK = $chunks[5]."</font>". "<br>";

    //echo "RMK = " . $RMK = $chunks[5] . "<br>";
    //echo "BRN = " . $BRN = $chunks[6] . "<br>";
    echo "TRN = " . $TRN = $chunks[7] . "<br>";
    //echo "TET = " . $BRN = $chunks[8] . "<br>";
    echo "TET = " . $TET = $chunks[9] . "<br>";
    //echo "BRN = " . $BRN = $chunks[10] . "<br>";
    echo "PMD = " . $PMD = $chunks[11] . "<br>";
    //echo "BRN = " . $BRN = $chunks[12] . "<br>";
    echo "RID = " . $RID = $chunks[13] . "<br>";
    //echo "BRN = " . $BRN = $chunks[14] . "<br>";
    echo "VER = " . $VER = $chunks[15] . "<br>";
    //echo "BRN = " . $BRN = $chunks[16] . "<br>";
    echo "CID = " . $CID = $chunks[17] . "<br>";
    //echo "BRN = " . $BRN = $chunks[18] . "<br>";
    echo "TYP = " . $TYP = $chunks[19] . "<br>";
    //echo "BRN = " . $BRN = $chunks[20] . "<br>";
    echo "CRN = " . $CRN = $chunks[21] . "<br>";
    //echo "BRN = " . $BRN = $chunks[22] . "<br>";
    echo "CNY = " . $CNY = $chunks[23] . "<br>";
    //echo "BRN = " . $BRN = $chunks[24] . "<br>";
    echo "AMT = " . $AMT = $chunks[25] . "<br>";
</code>```

Please help....

答:
i got the answer after juggling with array and explode function..

thnaks

Body:
I am trying to integrate the Bank Payment Gateway where data submission and processes is working very well but the success response as below received is not being inserted into database as it is a string in the form of an array.

BRN=837740&STC=000&RMK=success&TRN=5230896525&TET=2020/02/08 11:54:18 PM&PMD=CD&RID=253357&VER=1.0&CID=3636&TYP=Test&CRN=802406&CNY=INR&AMT=10000.00

Foe eg: in this code BRN is a parameter and 837740 is its returned value similarly STC is parameter and 000 is its returned value.

Now I want to set all these values in a php variables so to insert in the data, if no value is returned then null should be stored in db for eg;

BRN=837741&STC=111&RMK=failure&TRN=1172146589&TET=&PMD=AIB&RID=126036&VER=1.0&CID=3636&TYP=Test&CRN=740076&CNY=INR&AMT=10000.00

I tried below code which worked if all parameter has returned values if not then it is not working as delimiter sequence disturbed.

$chunks = preg_split('/(=|&)/', $qStr,-1, PREG_SPLIT_NO_EMPTY);
    //print_r($chunks);

    echo '
';
    print_r($chunks);
    echo '
';
/*
    echo "
";
    echo "
";

    $nweString = $chunks[0];
    for($i=1; $i<count($chunks); $i++) {
   // $nweString .= ':'.$chunks[$i];
    }
    echo $nweString;
    */

    echo "
";
    echo "
";
    echo "BRN = " . $BRN = $chunks[1] . "
";
//  echo "BRN = " . $BRN = $chunks[2] . "
";
    echo "STC = " . $STC = $chunks[3] . "
";
//  echo "BRN = " . $BRN = $chunks[4] . "
";
    if ($chunks[5] == "success") {$txtclr1 = '09CB00';}
    echo "" ."RMK = " . $RMK = $chunks[5]."". "
";

    //echo "RMK = " . $RMK = $chunks[5] . "
";
    //echo "BRN = " . $BRN = $chunks[6] . "
";
    echo "TRN = " . $TRN = $chunks[7] . "
";
    //echo "TET = " . $BRN = $chunks[8] . "
";
    echo "TET = " . $TET = $chunks[9] . "
";
    //echo "BRN = " . $BRN = $chunks[10] . "
";
    echo "PMD = " . $PMD = $chunks[11] . "
";
    //echo "BRN = " . $BRN = $chunks[12] . "
";
    echo "RID = " . $RID = $chunks[13] . "
";
    //echo "BRN = " . $BRN = $chunks[14] . "
";
    echo "VER = " . $VER = $chunks[15] . "
";
    //echo "BRN = " . $BRN = $chunks[16] . "
";
    echo "CID = " . $CID = $chunks[17] . "
";
    //echo "BRN = " . $BRN = $chunks[18] . "
";
    echo "TYP = " . $TYP = $chunks[19] . "
";
    //echo "BRN = " . $BRN = $chunks[20] . "
";
    echo "CRN = " . $CRN = $chunks[21] . "
";
    //echo "BRN = " . $BRN = $chunks[22] . "
";
    echo "CNY = " . $CNY = $chunks[23] . "
";
    //echo "BRN = " . $BRN = $chunks[24] . "
";
    echo "AMT = " . $AMT = $chunks[25] . "
";

Please help....


问:
Change tab spacing in python lxml prettyprint
I have a small script that creates an xml document and using the prettyprint=true it makes a correctly formatted xml document.  However, the tab indents are 2 spaces, and I am wondering if there is a way to change this to 4 spaces (I think it looks better with 4 spaces).  Is there a simple way to implement this?

Code snippet:

```<code>doc = lxml.etree.SubElement(root, 'dependencies')
for depen in dependency_list:
    dependency = lxml.etree.SubElement(doc, 'dependency')
    lxml.etree.SubElement(dependency, 'groupId').text = depen.group_id
    lxml.etree.SubElement(dependency, 'artifactId').text = depen.artifact_id
    lxml.etree.SubElement(dependency, 'version').text = depen.version
    if depen.scope == 'provided' or depen.scope == 'test':
        lxml.etree.SubElement(dependency, 'scope').text = depen.scope
    exclusions = lxml.etree.SubElement(dependency, 'exclusions')
    exclusion = lxml.etree.SubElement(exclusions, 'exclusion')
    lxml.etree.SubElement(exclusion, 'groupId').text = '*'
    lxml.etree.SubElement(exclusion, 'artifactId').text = '*'
tree.write('explicit-pom.xml' , pretty_print=True)
</code>```

答:
If someone is still trying to achieve this, it can be done using etree.indent() method in lxml 4.5 -

```<code>>>> etree.indent(root, space="    ")
>>> print(etree.tostring(root))
<root>
    <a>
        <b/>
    </a>
</root>
</code>```

https://lxml.de/tutorial.html#serialisation

Body:
I have a small script that creates an xml document and using the prettyprint=true it makes a correctly formatted xml document.  However, the tab indents are 2 spaces, and I am wondering if there is a way to change this to 4 spaces (I think it looks better with 4 spaces).  Is there a simple way to implement this?

Code snippet:

doc = lxml.etree.SubElement(root, 'dependencies')
for depen in dependency_list:
    dependency = lxml.etree.SubElement(doc, 'dependency')
    lxml.etree.SubElement(dependency, 'groupId').text = depen.group_id
    lxml.etree.SubElement(dependency, 'artifactId').text = depen.artifact_id
    lxml.etree.SubElement(dependency, 'version').text = depen.version
    if depen.scope == 'provided' or depen.scope == 'test':
        lxml.etree.SubElement(dependency, 'scope').text = depen.scope
    exclusions = lxml.etree.SubElement(dependency, 'exclusions')
    exclusion = lxml.etree.SubElement(exclusions, 'exclusion')
    lxml.etree.SubElement(exclusion, 'groupId').text = '*'
    lxml.etree.SubElement(exclusion, 'artifactId').text = '*'
tree.write('explicit-pom.xml' , pretty_print=True)

Body:
If someone is still trying to achieve this, it can be done using etree.indent() method in lxml 4.5 -

>>> etree.indent(root, space="    ")
>>> print(etree.tostring(root))
<root>
    <a>
        <b/>
    </a>
</root>

https://lxml.de/tutorial.html#serialisation


问:
Converting String to Integers the safe way
I have a little method that amongst other things also converts a string into an integer. Since the string is a parameter of the method I want to make sure that that string is convertable. So I was just wondering what would be the safest and / or fastest way.

Version A: Just leave it as it is and take the risks (which I'm trying to avoid)

```<code>public static int stringToInt(String param) {
        return Integer.valueOf(param);
}
</code>```

(in terms of speed, what kind of difference would it make to version B and C?)

Version B: Catch the exception

```<code>public static int stringToInt(String param) {
        try {
                return Integer.valueOf(param);
        } catch(NumberFormatException e) {
                return -1;
        }
}
</code>```

Version C: Check each letter of the string to see, if it's a digit number or not

```<code>public static int stringToInt(String param) {
        for(char c : param.toCharArray()) {
                if(!Character.isDigit(c))
                        return -1;
        }
        return Integer.valueOf(param);
}
</code>```

Note that the parameter has to be a positive number and the -1 is supposed to be the "error value" in my little program, in other words, all three versions of methods would work perfectally fine in my program.

I'm very open to any other suggestion you can give me, so feel free to create your own version, if you think yours is better.

Thank you very much for your support in advance.

答:
```<code>public int stringToInt(String param) throws NumberFormatException {

    Optional.ofNullable(param.replaceAll("\\s+", ""))
         .map(Integer::valueOf).orElse(null);

/*
                      or

    Optional.ofNullable(param.replaceAll(" ", ""))
         .map(Integer::valueOf).orElse(null);

*/

}
</code>```

use the replaceAll to replace white spaces the plus is cpu friendly even though seems not needed.

Body:
I have a little method that amongst other things also converts a string into an integer. Since the string is a parameter of the method I want to make sure that that string is convertable. So I was just wondering what would be the safest and / or fastest way.

Version A: Just leave it as it is and take the risks (which I'm trying to avoid)

public static int stringToInt(String param) {
        return Integer.valueOf(param);
}

(in terms of speed, what kind of difference would it make to version B and C?)

Version B: Catch the exception

public static int stringToInt(String param) {
        try {
                return Integer.valueOf(param);
        } catch(NumberFormatException e) {
                return -1;
        }
}

Version C: Check each letter of the string to see, if it's a digit number or not

public static int stringToInt(String param) {
        for(char c : param.toCharArray()) {
                if(!Character.isDigit(c))
                        return -1;
        }
        return Integer.valueOf(param);
}

Note that the parameter has to be a positive number and the -1 is supposed to be the "error value" in my little program, in other words, all three versions of methods would work perfectally fine in my program.

I'm very open to any other suggestion you can give me, so feel free to create your own version, if you think yours is better.

Thank you very much for your support in advance.

Body:
public int stringToInt(String param) throws NumberFormatException {

    Optional.ofNullable(param.replaceAll("\\s+", ""))
         .map(Integer::valueOf).orElse(null);

/*
                      or

    Optional.ofNullable(param.replaceAll(" ", ""))
         .map(Integer::valueOf).orElse(null);

*/

}

use the replaceAll to replace white spaces the plus is cpu friendly even though seems not needed.


问:
How do I avoid ExUnit.start() error when running mix test
When I run mix test on my project, I get the following error and I don't understand why:

```<code>$ mix test
Compiling 2 files (.ex)

== Compilation error in file lib/myproject_web/controllers/email_controller_test.ex ==
** (RuntimeError) cannot use ExUnit.Case without starting the ExUnit application, please call ExUnit.start() or explicitly start the :ex_unit app
    expanding macro: ExUnit.Case.__using__/1
    lib/myproject_web/controllers/email_controller_test.ex:2: MyProjectWeb.EmailControllerTest (module)
    (elixir 1.10.1) expanding macro: Kernel.use/2
    lib/myproject_web/controllers/email_controller_test.ex:2: MyProjectWeb.EmailControllerTest (module)
</code>```

I already have a test_helper.exs file in lib/ which calls ExUnit.start(). My set up is unusual because I want the tests next to the modules rather than in a separate test folder.

答:
It turns out this error comes from the test file having a .ex extension rather than .exs. With .ex then mix tries to compile it with everything else before running the tests and then complains because ExUnit.start() hasn't been called at compile time.

With the .exs extension then the file isn't compiled but is run by mix test after the ExUnit.start() has been called from test_helpers.exs.

Body:
When I run mix test on my project, I get the following error and I don't understand why:

$ mix test
Compiling 2 files (.ex)

== Compilation error in file lib/myproject_web/controllers/email_controller_test.ex ==
** (RuntimeError) cannot use ExUnit.Case without starting the ExUnit application, please call ExUnit.start() or explicitly start the :ex_unit app
    expanding macro: ExUnit.Case.__using__/1
    lib/myproject_web/controllers/email_controller_test.ex:2: MyProjectWeb.EmailControllerTest (module)
    (elixir 1.10.1) expanding macro: Kernel.use/2
    lib/myproject_web/controllers/email_controller_test.ex:2: MyProjectWeb.EmailControllerTest (module)

I already have a test_helper.exs file in lib/ which calls ExUnit.start(). My set up is unusual because I want the tests next to the modules rather than in a separate test folder.


问:
How do I modify this script to take parameters?
I have a power shell script that combines power points. The issue is it only works on power points in the current directory (the directory the script is in) and saves the combined power point to documents. How do I change the script to work from any directory that is given as a parameter. I run the power shell script like this ./Merge-Presentation -Source $Presentations -Destination $save -Verbose -Open;. Where $Presentations is the path of the individual power point and $save is the path where the combined power point is saved. Here is the script.

```<code>#region function definitions
#Function for releasing a COM object
Function Remove-Ref
{
    param
    (
        [Object]
        $ref
    )

    $null = Remove-Variable -Name $ref -ErrorAction SilentlyContinue
    while ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
    {

    }
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
}

#Main function for merging PowerPoint presentations
Function Merge-PowerPointPresentation
{
    <#
            .SYNOPSIS
            Merge multiple PowerPoint presentation files to one file

            .DESCRIPTION
            Merge multiple PowerPoint presentation files to one file

            .PARAMETER Source
            The PowerPoint presentation files to merge specified by its full name

            .PARAMETER Destination
            The target PowerPoint presentation file specified by its full name

            .PARAMETER Open
            A switch to specify if we keep the PowerPoint application opened after the processing

            .EXAMPLE
            $Get-ChildItem -Path $CurrentDir -filter *.pptx | Sort-Object -Property Name | Merge-PowerPointPresentation -Verbose -Open
            Will merge all the PowerPoint files into the current directory into one single Powerpoint file by using a timestamped filename (ie. yyyyMMddTHHmmss.pptx like 20170126T091011.pptx)
            The output will be verbose
            The PowerPoint application won't be left after the processing

            .EXAMPLE
            $Presentations = "$CurrentDir\0.pptx","$CurrentDir\1.pptx","$CurrentDir\2.pptx","$CurrentDir\3.pptx","$CurrentDir\4.pptx","$CurrentDir\5.pptx","$CurrentDir\6.pptx","$CurrentDir\7.pptx","$CurrentDir\8.pptx","$CurrentDir\9.pptx"
            Merge-PowerPointPresentation -Source $Presentations -Destination C:\Temp\MergedPresentation.pptx
            Will merge all the specified PowerPoint files into into the C:\Temp\MergedPresentation.pptx Powerpoint file
    #>
    [CmdletBinding()]
    Param(
        #The collection of the powerpoint files to merge
        [Parameter(Mandatory = $True,ValueFromPipeline = $True,ValueFromPipelineByPropertyName = $True)]
        [ValidateScript({
                    (Test-Path -Path $_ -PathType Leaf) -and ($_ -match "\.ppt(x{0,1})$")
        })]
        [alias('FilePath', 'Path', 'FullName')]
        [string[]]$Source,

        #The path of the generated powerpoint file
        [Parameter(Mandatory = $False)]
        [ValidateNotNullOrEmpty()]
        [alias('OutputFile')]
        [string]$Destination = $(Join-Path -Path $([Environment]::GetFolderPath('MyDocuments')) -ChildPath $('{0:yyyyMMddTHHmmss}' -f (Get-Date))),

        #To keep open the generated Powerpoint presentation
        [parameter(Mandatory = $False)]
        [switch]$Open
    )
    begin
    {
        #Opening the PowerPoint application once
        Add-Type -AssemblyName Microsoft.Office.Interop.PowerPoint
        $Powerpoint = New-Object -ComObject Powerpoint.Application
        #Creating a new PowerPoint presentation
        $NewPresentation = $Powerpoint.Presentations.Add($True)
        # Adding an empty slide : mandatory
        $null = $NewPresentation.Slides.Add(1, [Microsoft.Office.Interop.PowerPoint.PpSlideLayout]::ppLayoutBlank)
        $SlidesNb = 0
    }
    process
    {
        #For all files passed as argument outside a pipeline context
        foreach ($CurrentSource in $Source)
        {
            #Getting the base name of the processed presentation
            $CurrentPresentationName = (Get-Item -Path $CurrentSource).BaseName

            #Inserting the slide of the current presentationt o the new one
            $InsertedSlidesNb = $NewPresentation.Slides.InsertFromfile($CurrentSource, $SlidesNb)

            #Applying the original template
            $NewPresentation.Slides.Range(($SlidesNb+1)..($SlidesNb+$InsertedSlidesNb)).ApplyTemplate($CurrentSource)

            #Adding a new section for the inserted context with the name of the processed presentation
            Write-Verbose -Message "Adding the section $CurrentPresentationName before Slide $($SlidesNb+1)..."
            $null = $NewPresentation.SectionProperties.AddBeforeSlide($SlidesNb+1, $CurrentPresentationName)

            Write-Verbose -Message "Processed file $CurrentSource by inserting $InsertedSlidesNb slides ($($SlidesNb+1) ==> $($SlidesNb+$InsertedSlidesNb)) ..."
            $SlidesNb += $InsertedSlidesNb
        }
    }
    end
    {
        #Deleting the useless empty slide (added at the beginning)
        $NewPresentation.Slides.Range($SlidesNb+1).Delete()
        #Saving the final file
        $NewPresentation.SaveAs($Destination)
        Write-Host -Object "The new presentation was saved in $($NewPresentation.FullName) ($SlidesNb slides)"
        #If the -Open switch is specified we keep the PowerPoint application opened
        if (!$Open)
        {
            $NewPresentation.Close()
            #$Powerpoint.Quit() | Out-Null
            Write-Verbose -Message 'Releasing PowerPoint ...'
            Remove-Ref -ref ($NewPresentation)
            Remove-Ref -ref ($Powerpoint)
        }
    }
}
#endregion

Clear-Host
#Getting the current directory (where this script file resides)
$CurrentDir = Split-Path -Path $MyInvocation.MyCommand.Path
#Loading the PowerPoint assembly

#Example 1 : Processing all the PowerPoint presentation in current directory in the alphabetical order
Get-ChildItem -Path $CurrentDir -Filter *.pptx |
Sort-Object -Property Name |
Merge-PowerPointPresentation -Verbose -Open

#Example 2 : Processing a list of some PowerPoint presentations specified by their absolute path
$Presentations = "$CurrentDir\0.pptx", "$CurrentDir\1.pptx", "$CurrentDir\2.pptx", "$CurrentDir\3.pptx", "$CurrentDir\4.pptx", "$CurrentDir\5.pptx", "$CurrentDir\6.pptx", "$CurrentDir\7.pptx", "$CurrentDir\8.pptx", "$CurrentDir\9.pptx"
Merge-PowerPointPresentation -Source $Presentations -Destination $CurrentDir\all.pptx -Verbose
</code>```

The expected result is to load the power points from the directory specified as parameter and save the combined power point in the directory specified as a parameter.

答:
You can just add a parameter declaration at the top, something like:

```<code>Param(
    [parameter(Mandatory = $false, Position = 1)]
    [ValidateScript( {Test-Path $_} )]
    [String]$SourcePath = ( Split-Path $MyInvocation.MyCommand.Path ),

    [parameter(Mandatory = $false, Position = 2)]
    [ValidateScript( {Test-Path $_} )]
    [String]$DestinationPath

) #End Parameter Block...
</code>```

I used Path as the parameter because it's quite common and $CurrentDirector wouldn't make sense here.  I defaulted the parameter to the same as you had it. In the script body you'll want to replace $CurrentPath with $Path.

```<code>Get-ChildItem -Path $SourcePath -Filter *.pptx |
Sort-Object -Property Name |
Merge-PowerPointPresentation -Verbose -Open -Destination $DestinationPath
</code>```

Note: The addition of -DestinationPath in the above call.  That should override the default value in the Merge-PowerPointPresentation function.

If you don't use the parameters the script should behave same as before.  If you do use it It will operate against whatever paths you gave it.

Obviously not tested, but let me know if that helps.  Thanks.

Body:
I have a power shell script that combines power points. The issue is it only works on power points in the current directory (the directory the script is in) and saves the combined power point to documents. How do I change the script to work from any directory that is given as a parameter. I run the power shell script like this ./Merge-Presentation -Source $Presentations -Destination $save -Verbose -Open;. Where $Presentations is the path of the individual power point and $save is the path where the combined power point is saved. Here is the script.

#region function definitions
#Function for releasing a COM object
Function Remove-Ref
{
    param
    (
        [Object]
        $ref
    )

    $null = Remove-Variable -Name $ref -ErrorAction SilentlyContinue
    while ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
    {

    }
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
}

#Main function for merging PowerPoint presentations
Function Merge-PowerPointPresentation
{
    <#
            .SYNOPSIS
            Merge multiple PowerPoint presentation files to one file

            .DESCRIPTION
            Merge multiple PowerPoint presentation files to one file

            .PARAMETER Source
            The PowerPoint presentation files to merge specified by its full name

            .PARAMETER Destination
            The target PowerPoint presentation file specified by its full name

            .PARAMETER Open
            A switch to specify if we keep the PowerPoint application opened after the processing

            .EXAMPLE
            $Get-ChildItem -Path $CurrentDir -filter *.pptx | Sort-Object -Property Name | Merge-PowerPointPresentation -Verbose -Open
            Will merge all the PowerPoint files into the current directory into one single Powerpoint file by using a timestamped filename (ie. yyyyMMddTHHmmss.pptx like 20170126T091011.pptx)
            The output will be verbose
            The PowerPoint application won't be left after the processing

            .EXAMPLE
            $Presentations = "$CurrentDir\0.pptx","$CurrentDir\1.pptx","$CurrentDir\2.pptx","$CurrentDir\3.pptx","$CurrentDir\4.pptx","$CurrentDir\5.pptx","$CurrentDir\6.pptx","$CurrentDir\7.pptx","$CurrentDir\8.pptx","$CurrentDir\9.pptx"
            Merge-PowerPointPresentation -Source $Presentations -Destination C:\Temp\MergedPresentation.pptx
            Will merge all the specified PowerPoint files into into the C:\Temp\MergedPresentation.pptx Powerpoint file
    #>
    [CmdletBinding()]
    Param(
        #The collection of the powerpoint files to merge
        [Parameter(Mandatory = $True,ValueFromPipeline = $True,ValueFromPipelineByPropertyName = $True)]
        [ValidateScript({
                    (Test-Path -Path $_ -PathType Leaf) -and ($_ -match "\.ppt(x{0,1})$")
        })]
        [alias('FilePath', 'Path', 'FullName')]
        [string[]]$Source,

        #The path of the generated powerpoint file
        [Parameter(Mandatory = $False)]
        [ValidateNotNullOrEmpty()]
        [alias('OutputFile')]
        [string]$Destination = $(Join-Path -Path $([Environment]::GetFolderPath('MyDocuments')) -ChildPath $('{0:yyyyMMddTHHmmss}' -f (Get-Date))),

        #To keep open the generated Powerpoint presentation
        [parameter(Mandatory = $False)]
        [switch]$Open
    )
    begin
    {
        #Opening the PowerPoint application once
        Add-Type -AssemblyName Microsoft.Office.Interop.PowerPoint
        $Powerpoint = New-Object -ComObject Powerpoint.Application
        #Creating a new PowerPoint presentation
        $NewPresentation = $Powerpoint.Presentations.Add($True)
        # Adding an empty slide : mandatory
        $null = $NewPresentation.Slides.Add(1, [Microsoft.Office.Interop.PowerPoint.PpSlideLayout]::ppLayoutBlank)
        $SlidesNb = 0
    }
    process
    {
        #For all files passed as argument outside a pipeline context
        foreach ($CurrentSource in $Source)
        {
            #Getting the base name of the processed presentation
            $CurrentPresentationName = (Get-Item -Path $CurrentSource).BaseName

            #Inserting the slide of the current presentationt o the new one
            $InsertedSlidesNb = $NewPresentation.Slides.InsertFromfile($CurrentSource, $SlidesNb)

            #Applying the original template
            $NewPresentation.Slides.Range(($SlidesNb+1)..($SlidesNb+$InsertedSlidesNb)).ApplyTemplate($CurrentSource)

            #Adding a new section for the inserted context with the name of the processed presentation
            Write-Verbose -Message "Adding the section $CurrentPresentationName before Slide $($SlidesNb+1)..."
            $null = $NewPresentation.SectionProperties.AddBeforeSlide($SlidesNb+1, $CurrentPresentationName)

            Write-Verbose -Message "Processed file $CurrentSource by inserting $InsertedSlidesNb slides ($($SlidesNb+1) ==> $($SlidesNb+$InsertedSlidesNb)) ..."
            $SlidesNb += $InsertedSlidesNb
        }
    }
    end
    {
        #Deleting the useless empty slide (added at the beginning)
        $NewPresentation.Slides.Range($SlidesNb+1).Delete()
        #Saving the final file
        $NewPresentation.SaveAs($Destination)
        Write-Host -Object "The new presentation was saved in $($NewPresentation.FullName) ($SlidesNb slides)"
        #If the -Open switch is specified we keep the PowerPoint application opened
        if (!$Open)
        {
            $NewPresentation.Close()
            #$Powerpoint.Quit() | Out-Null
            Write-Verbose -Message 'Releasing PowerPoint ...'
            Remove-Ref -ref ($NewPresentation)
            Remove-Ref -ref ($Powerpoint)
        }
    }
}
#endregion

Clear-Host
#Getting the current directory (where this script file resides)
$CurrentDir = Split-Path -Path $MyInvocation.MyCommand.Path
#Loading the PowerPoint assembly

#Example 1 : Processing all the PowerPoint presentation in current directory in the alphabetical order
Get-ChildItem -Path $CurrentDir -Filter *.pptx |
Sort-Object -Property Name |
Merge-PowerPointPresentation -Verbose -Open

#Example 2 : Processing a list of some PowerPoint presentations specified by their absolute path
$Presentations = "$CurrentDir\0.pptx", "$CurrentDir\1.pptx", "$CurrentDir\2.pptx", "$CurrentDir\3.pptx", "$CurrentDir\4.pptx", "$CurrentDir\5.pptx", "$CurrentDir\6.pptx", "$CurrentDir\7.pptx", "$CurrentDir\8.pptx", "$CurrentDir\9.pptx"
Merge-PowerPointPresentation -Source $Presentations -Destination $CurrentDir\all.pptx -Verbose

The expected result is to load the power points from the directory specified as parameter and save the combined power point in the directory specified as a parameter.

Body:
You can just add a parameter declaration at the top, something like:

Param(
    [parameter(Mandatory = $false, Position = 1)]
    [ValidateScript( {Test-Path $_} )]
    [String]$SourcePath = ( Split-Path $MyInvocation.MyCommand.Path ),

    [parameter(Mandatory = $false, Position = 2)]
    [ValidateScript( {Test-Path $_} )]
    [String]$DestinationPath

) #End Parameter Block...

I used Path as the parameter because it's quite common and $CurrentDirector wouldn't make sense here.  I defaulted the parameter to the same as you had it. In the script body you'll want to replace $CurrentPath with $Path.

Get-ChildItem -Path $SourcePath -Filter *.pptx |
Sort-Object -Property Name |
Merge-PowerPointPresentation -Verbose -Open -Destination $DestinationPath

Note: The addition of -DestinationPath in the above call.  That should override the default value in the Merge-PowerPointPresentation function.

If you don't use the parameters the script should behave same as before.  If you do use it It will operate against whatever paths you gave it.

Obviously not tested, but let me know if that helps.  Thanks.


问:
React Native project does not start on the android emulator and no error is shown
I'm working on a React Native project (no Expo) end I'm using react-native-vector-icons

Everything was fine until I updated the ttf file of my icons.  From that moment when I try to run my project on Android (with npx react-native run-android) build process is successful but application does not start on the emulator.

On iOS I have no problem.

Is there a way that allows me to understand what goes wrong?

答:
Try to "Wipe Data" in the emulator before initialize your App.
You can do this in Android Studio, just follow the image:

If it doesn't work, you can go in your android folder with cmd ("cd android"), make a "./gradlew clean" there, then "cd ..", delete your "node_modules" folder, run "yarn install" or "npm install" and rebuild your project again with "npx react-native run-android".
Hope it works.


问:
Explode a cell populated with multiple values into unique rows
I want to "explode" each cell that has multiple words in it into distinct rows while retaining it's rating and sysnet value when being conjoined. I attempted to import someone's pandas_explode library but VS code just does not want to recognize it. Is there any way for me in pandas documentation or some nifty for loop that'll extract and redistribute these words? Example csv is in the img link

```<code>import json
import pandas as pd # version 1.01

df = pd.read_json('result.json')
df.to_csv('jsonToCSV.csv', index=False)
df = pd.read_csv('jsonToCSV.csv')

df = df.explode('words')

print(df)

df = df.to_csv(r'C:\Users\alant\Desktop\test.csv', index = None, header=True)
</code>```

Output when running above:

```<code>   synset  rating                                              words
0     1034312     0.0             ['discourse', 'talk about', 'discuss']
1      146856     0.0          ['merging', 'meeting', 'coming together']
2      829378     0.0     ['care', 'charge', 'tutelage', 'guardianship']
3     8164585     0.0  ['administration', 'governance', 'governing bo...
4     1204318     0.0               ['nonhierarchical', 'nonhierarchic']
...       ...     ...                                                ...
8605  7324673     1.0               ['emergence', 'outgrowth', 'growth']
</code>```

csv file

答:
If you have columns that needs to be kept from exploding, I suggest setting them as index first and then explode.

For your example, try if this works for you.

```<code>df = df.set_index(['synset','rating']).apply(pd.Series.explode) # this would work for exploding multiple columns as well

# then reset the index

df = df.reset_index()
</code>```

Body:
I want to "explode" each cell that has multiple words in it into distinct rows while retaining it's rating and sysnet value when being conjoined. I attempted to import someone's pandas_explode library but VS code just does not want to recognize it. Is there any way for me in pandas documentation or some nifty for loop that'll extract and redistribute these words? Example csv is in the img link

import json
import pandas as pd # version 1.01

df = pd.read_json('result.json')
df.to_csv('jsonToCSV.csv', index=False)
df = pd.read_csv('jsonToCSV.csv')

df = df.explode('words')

print(df)

df = df.to_csv(r'C:\Users\alant\Desktop\test.csv', index = None, header=True)

Output when running above:

   synset  rating                                              words
0     1034312     0.0             ['discourse', 'talk about', 'discuss']
1      146856     0.0          ['merging', 'meeting', 'coming together']
2      829378     0.0     ['care', 'charge', 'tutelage', 'guardianship']
3     8164585     0.0  ['administration', 'governance', 'governing bo...
4     1204318     0.0               ['nonhierarchical', 'nonhierarchic']
...       ...     ...                                                ...
8605  7324673     1.0               ['emergence', 'outgrowth', 'growth']

csv file

Body:
If you have columns that needs to be kept from exploding, I suggest setting them as index first and then explode.

For your example, try if this works for you.

df = df.set_index(['synset','rating']).apply(pd.Series.explode) # this would work for exploding multiple columns as well

# then reset the index

df = df.reset_index()


问:
Generate a diff report on json in python
I have a regression test script in python which takes in a JSON from ground truth file and JSON from a rest api and if they don't match I want to generate diff. The script is in python. I can walk through JSON and compare line by line but challenge is  new element can be appended in the end or start or middle. Then line by line  can get complicated. Is there some library that can spit the diff out if two JSON strings are passed.</p>

答:
You can check the deepdiff package. Here is an example with it:

```<code>from deepdiff import DeepDiff

t1 = {'a': 10, 'b': 20}
t2 = {'a': 10, 'b': 22}
ddiff = DeepDiff(t1, t2, ignore_order=True)
print(ddiff)

</code>```

This prints:

```<code>{'values_changed': {"root['b']": {'new_value': 22, 'old_value': 20}}}
</code>```

Body:
You can check the deepdiff package. Here is an example with it:

from deepdiff import DeepDiff

t1 = {'a': 10, 'b': 20}
t2 = {'a': 10, 'b': 22}
ddiff = DeepDiff(t1, t2, ignore_order=True)
print(ddiff)

This prints:

{'values_changed': {"root['b']": {'new_value': 22, 'old_value': 20}}}


问:
Expression to remove URL links from Twitter tweet
I simply would like to find and replace all occurrences of a twitter url in a string (tweet):

Input:

This is a tweet with a url: http://t.co/0DlGChTBIx

Output:

This is a tweet with a url:

I've tried this:

```<code>p=re.compile(r'\<http.+?\>', re.DOTALL)
tweet_clean = re.sub(p, '', tweet)
</code>```

答:
```<code>text = re.sub(r"https:(\/\/t\.co\/([A-Za-z0-9]|[A-Za-z]){10})", "", text)
</code>```

This matches alphanumerics  too after t.co/

Body:
I simply would like to find and replace all occurrences of a twitter url in a string (tweet):

Input:

This is a tweet with a url: http://t.co/0DlGChTBIx

Output:

This is a tweet with a url:

I've tried this:

p=re.compile(r'\<http.+?\>', re.DOTALL)
tweet_clean = re.sub(p, '', tweet)

Body:
text = re.sub(r"https:(\/\/t\.co\/([A-Za-z0-9]|[A-Za-z]){10})", "", text)

This matches alphanumerics  too after t.co/


问:
Django Execute a def at a time value
I'm searching for a method to make a def to execute at a time value when I run the server... Example once per day. One solution is to use Celery but i don't want to use it only for a simple def... Any suggestion? I'm using windows. Thanks!

答:
There are certainly several possibilities, so this is just one of many solutions:

We use Unix cron jobs or Kubernetes cron jobs for this which call:

./manage.py <the command>

(or call docker exec .... manage.py <the command>)

You should make sure that your logs go whereever you need them to monitor the cron job.

Note: there was a similar question I've answered with more details: https://stackoverflow.com/a/52778625/621690

Title: Django Execute a def at a time value


问:
Select * from table with NodeJS // ERROR: { error: relation "mytable" does not exist
I get the following error during my SELECT query from PostgreSQL DB

```<code>ERROR: { error: relation "free_subnets" does not exist
    at Connection.parseE (/home/ec2-user/environment/node_modules/pg/lib/connection.js:604:11)
    at Connection.parseMessage (/home/ec2-user/environment/node_modules/pg/lib/connection.js:401:19)
    at Socket.<anonymous> (/home/ec2-user/environment/node_modules/pg/lib/connection.js:121:22)
    at Socket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  name: 'error',
  length: 103,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '15',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '874',
  routine: 'parserOpenTable' }
</code>```

If I use psql command and do a select there, it works.

\dt provides me the relation:

```<code>
   Schema    |     Name     | Type  |  Owner
-------------+--------------+-------+----------
 subnet_calc | free_subnets | table | postgres
</code>```

Search_path has been set to: subnet_calc, public

I've created the table with user postgres, so I am the owner of the schema subnet_calc and the table free_subnets.

My dummy nodejs code is the following:

const pg = require('pg');

const cs = 'postgres://postgres:password@anydb.rds.amazonaws.com:5432/subnet_calculator';

const client = new pg.Client(cs);
client.connect();

client.query('SELECT * FROM subnet_calc.free_subnets', function(result) {
  console.log(result);
});
```

What could be the issue?

Thanks for your help in advance!

答:
you need to set search path for it like this:

```<code>db.query("SET search_path TO 'subnet_calc';")
</code>```

and then do the query :

```<code>const query = `SELECT * FROM free_subnets`

db.query(query)
</code>```

Body:
I get the following error during my SELECT query from PostgreSQL DB

ERROR: { error: relation "free_subnets" does not exist
    at Connection.parseE (/home/ec2-user/environment/node_modules/pg/lib/connection.js:604:11)
    at Connection.parseMessage (/home/ec2-user/environment/node_modules/pg/lib/connection.js:401:19)
    at Socket.<anonymous> (/home/ec2-user/environment/node_modules/pg/lib/connection.js:121:22)
    at Socket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  name: 'error',
  length: 103,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '15',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '874',
  routine: 'parserOpenTable' }

If I use psql command and do a select there, it works.

\dt provides me the relation:

   Schema    |     Name     | Type  |  Owner
-------------+--------------+-------+----------
 subnet_calc | free_subnets | table | postgres

Search_path has been set to: subnet_calc, public

I've created the table with user postgres, so I am the owner of the schema subnet_calc and the table free_subnets.

My dummy nodejs code is the following:

const pg = require('pg');

const cs = 'postgres://postgres:password@anydb.rds.amazonaws.com:5432/subnet_calculator';

const client = new pg.Client(cs);
client.connect();

client.query('SELECT * FROM subnet_calc.free_subnets', function(result) {
  console.log(result);
});

What could be the issue?

Thanks for your help in advance!

Body:
you need to set search path for it like this:

db.query("SET search_path TO 'subnet_calc';")

and then do the query :

const query = `SELECT * FROM free_subnets`

db.query(query)


问:
How to identify using xmlslurper in groovy, whether a node exists in my xml?
I have this xml, I want to check the existence of price node if present then do set of actions else move on.

```<code><game>
 <genre>
  <action>...</action>
  <racing>...</racing>
 <price>
  ..
  ..
  </price>
</genre>
</game>
</code>```

How can I achieve this in groovy?

答:
Hey I got the answer, this works fine for me.

xml is the GPathResult object that has the xml in it.

```<code>xml.children().find {it.name()=="price"}
</code>```

//will return true if price exists

Body:
I have this xml, I want to check the existence of price node if present then do set of actions else move on.

<game>
 <genre>
  <action>...</action>
  <racing>...</racing>
 <price>
  ..
  ..
  </price>
</genre>
</game>

How can I achieve this in groovy?

Body:
Hey I got the answer, this works fine for me.

xml is the GPathResult object that has the xml in it.

xml.children().find {it.name()=="price"}

//will return true if price exists


问:
How do I open and modify OpenCascade files?
I need to open and modify a file (cnc program) that is in the OpenCascade format.
How do I do this? Any libraries available for Python?

I tried treating it as an .xml file but this did not work.

```<code><?xml version="1.0" encoding="UTF-8"?>
<document format="MPRxOcaf" xmlns="http://www.opencascade.org/OCAF/XML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opencascade.org/OCAF/XML">
 <info date="2019-09-13" schemav="0" DocVersion="7" objnb="583">
  <iitem>Copyright: Open Cascade, 2001-2002</iitem>
  <iitem>REFERENCE_COUNTER: 0</iitem>
</code>```

答:
Quoted fragment is not exactly "OpenCascade format". Open CASCADE Technology (OCCT) comes with Application Framework module defining OCAF document (stands for 'Open CASCADE Application Framework'), which is a low-level data API defining an arbitrary document. It also implements routines for reading/writing documents in binary (BinOcaf) and Xml (XmlOcaf) formats.

OCCT has also XCAF document relying on OCAF, which defines an assembly structure of shapes with attributes (colors, names, locations) and has binary (BinXCAF) and Xml (XmlXCAF) storage formats. XCAF documents are used for importing and exporting files in STEP / IGES formats. Binary files usually has .xbf file extension.

The document header in your question defines MPRxOcaf format based on OCAF. Such format does not exist in OCCT, so that it should be invented by specific application. The knowledge that it is based on OCAF will barely help here. Reading this document without documentation from application authors will require reverse-engineering to understand its structure. To read it back into OCCT-based application, it will be necessary defining necessary OCAF plugins and drivers decoding entities - could be pretty much of work for a complex document structure.

Body:
I need to open and modify a file (cnc program) that is in the OpenCascade format.
How do I do this? Any libraries available for Python?

I tried treating it as an .xml file but this did not work.

<?xml version="1.0" encoding="UTF-8"?>
<document format="MPRxOcaf" xmlns="http://www.opencascade.org/OCAF/XML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opencascade.org/OCAF/XML">
 <info date="2019-09-13" schemav="0" DocVersion="7" objnb="583">
  <iitem>Copyright: Open Cascade, 2001-2002</iitem>
  <iitem>REFERENCE_COUNTER: 0</iitem>


问:
how do you fix this while loop?
EDIT: i have another problem but it won't let me post again

the code is this:

```<code>print('''Which group of queens do you want to compete against?
1. Winners
2. Runner-ups
3. Lip sync assassins
4. Miss Congenialities
5. First Eliminated
6. Returning queens''')
choice = int(input())

while choice > 6:
  if choice == 1:
    contestants = ["BeBe Zahara Benet", "Tyra Sanchez", "Raja", "Sharon Needles", "Jinkx Monsoon", "Bianca Del Rio", "Violet Chachki", "Bob the Drag Queen", "Sasha Velour", "Aquaria", "Yvie Oddly", "Chad Michaels", "Alaska", "Trixie Mattel", "Trinity the Tuck", "Monét X Change"]
  elif choice == 2:
    contestants = ["Nina Flowers", "Raven", "Manila Luzon", "Chad Micheals", "Alaska", "Courtney Act", "Ginger Minj", "Kim Chi", "Peppermint", "Eureka", "Brooke Lynn Hytes", "Katya", "Kennedy Davenport", "Monique Heart"]
  elif choice == 3:
    contestants = ["Akashia", "Jujubee", "Alexis Mateo", "Latrice Royale", "Coco Montrese", "Trinity K. Bonet", "Kennedy Davenport", "Chi Chi DeVayne", "Peppermint", "Kameron Michaels", "Ra'Jah O'Hara", "Raven", "Alaska", "BenDeLaCreme", "Trinity the Tuck"]
  elif choice == 4:
    contestants = ["Nina Flowers", "Pandora Boxx", "Yara Sofia", "Latrice Royale", "Ivy Winters", "BenDeLaCreme", "Katya", "Cynthia Lee Fontaine", "Valentina", "Monét X Change", "Nina West"]
  elif choice == 5:
    contestants = ["Victoria Parker", "Shangela", "Venus D-Lite", "Alisa Summers", "Penny Tration", "Kelly Mantle", "Tempest DuJour", "Laila McQueen", "Jaymes Mansfield", "Vanessa Vanjie Mateo", "Soju", "Mimi Imfurst", "Coco Montrese", "Thorgy Thor", "Jasmine Masters"]
  elif choice == 6:
    contestants = ["Carmen Carrera", "Shangela", "Kenya Michaels", "Trixie Mattel", "Naysha Lopez", "Cynthia Lee Fontaine", "Eureka", "Vanessa Vanjie Mateo", "Alyssa Edwards", "Tatianna", "Morgan McMichaels", "Latrice Royale", "Manila Luzon"]
  else:
    while choice > 6 or choice < 1:
        print("Please choose one of the 6 groups")
        choice = int(input())
</code>```

the section that doesn't work is this:

```<code>else:
    while choice > 6 or choice < 1:
        print("Please choose one of the 6 groups")
        choice = int(input())
</code>```

the loop keeps going on and on no mater what i enter (unless i enter anything other than an integer where it'll show an error message). how do i stop this when i enter an integer between 1 and 6?

答:
you may never get out from your while loop if choice < 6 so your program will never hit your for loop

to fix you can make a dict to hold all your options, read one time the  input and base on the input create contestants

```<code>options = {
    1: ["BeBe Zahara Benet", "Tyra Sanchez", "Raja", "Sharon Needles", "Jinkx Monsoon", "Bianca Del Rio", "Violet Chachki", "Bob the Drag Queen", "Sasha Velour", "Aquaria", "Yvie Oddly", "Chad Michaels", "Alaska", "Trixie Mattel", "Trinity the Tuck", "Monét X Change"],
    2: ["Nina Flowers", "Raven", "Manila Luzon", "Chad Micheals", "Alaska", "Courtney Act", "Ginger Minj", "Kim Chi", "Peppermint", "Eureka", "Brooke Lynn Hytes", "Katya", "Kennedy Davenport", "Monique Heart"],
    3: ["Akashia", "Jujubee", "Alexis Mateo", "Latrice Royale", "Coco Montrese", "Trinity K. Bonet", "Kennedy Davenport", "Chi Chi DeVayne", "Peppermint", "Kameron Michaels", "Ra'Jah O'Hara", "Raven", "Alaska", "BenDeLaCreme", "Trinity the Tuck"],
    4: ["Nina Flowers", "Pandora Boxx", "Yara Sofia", "Latrice Royale", "Ivy Winters", "BenDeLaCreme", "Katya", "Cynthia Lee Fontaine", "Valentina", "Monét X Change", "Nina West"],
    5: ["Victoria Parker", "Shangela", "Venus D-Lite", "Alisa Summers", "Penny Tration", "Kelly Mantle", "Tempest DuJour", "Laila McQueen", "Jaymes Mansfield", "Vanessa Vanjie Mateo", "Soju", "Mimi Imfurst", "Coco Montrese", "Thorgy Thor", "Jasmine Masters"],
    6: ["Carmen Carrera", "Shangela", "Kenya Michaels", "Trixie Mattel", "Naysha Lopez", "Cynthia Lee Fontaine", "Eureka", "Vanessa Vanjie Mateo", "Alyssa Edwards", "Tatianna", "Morgan McMichaels", "Latrice Royale", "Manila Luzon"]
}

print('''Which group of queens do you want to compete against?
1. Winners
2. Runner-ups
3. Lip sync assassins
4. Miss Congenialities
5. First Eliminated
6. Returning queens''')

choice = int(input())
while choice > 6 or choice < 1:
    print("Please choose one of the 6 groups")
    choice = int(input())

contestants = options[choice]
</code>```

Title: how do you fix this while loop?

Body:
EDIT: i have another problem but it won't let me post again

the code is this:

print('''Which group of queens do you want to compete against?
1. Winners
2. Runner-ups
3. Lip sync assassins
4. Miss Congenialities
5. First Eliminated
6. Returning queens''')
choice = int(input())

while choice > 6:
  if choice == 1:
    contestants = ["BeBe Zahara Benet", "Tyra Sanchez", "Raja", "Sharon Needles", "Jinkx Monsoon", "Bianca Del Rio", "Violet Chachki", "Bob the Drag Queen", "Sasha Velour", "Aquaria", "Yvie Oddly", "Chad Michaels", "Alaska", "Trixie Mattel", "Trinity the Tuck", "Monét X Change"]
  elif choice == 2:
    contestants = ["Nina Flowers", "Raven", "Manila Luzon", "Chad Micheals", "Alaska", "Courtney Act", "Ginger Minj", "Kim Chi", "Peppermint", "Eureka", "Brooke Lynn Hytes", "Katya", "Kennedy Davenport", "Monique Heart"]
  elif choice == 3:
    contestants = ["Akashia", "Jujubee", "Alexis Mateo", "Latrice Royale", "Coco Montrese", "Trinity K. Bonet", "Kennedy Davenport", "Chi Chi DeVayne", "Peppermint", "Kameron Michaels", "Ra'Jah O'Hara", "Raven", "Alaska", "BenDeLaCreme", "Trinity the Tuck"]
  elif choice == 4:
    contestants = ["Nina Flowers", "Pandora Boxx", "Yara Sofia", "Latrice Royale", "Ivy Winters", "BenDeLaCreme", "Katya", "Cynthia Lee Fontaine", "Valentina", "Monét X Change", "Nina West"]
  elif choice == 5:
    contestants = ["Victoria Parker", "Shangela", "Venus D-Lite", "Alisa Summers", "Penny Tration", "Kelly Mantle", "Tempest DuJour", "Laila McQueen", "Jaymes Mansfield", "Vanessa Vanjie Mateo", "Soju", "Mimi Imfurst", "Coco Montrese", "Thorgy Thor", "Jasmine Masters"]
  elif choice == 6:
    contestants = ["Carmen Carrera", "Shangela", "Kenya Michaels", "Trixie Mattel", "Naysha Lopez", "Cynthia Lee Fontaine", "Eureka", "Vanessa Vanjie Mateo", "Alyssa Edwards", "Tatianna", "Morgan McMichaels", "Latrice Royale", "Manila Luzon"]
  else:
    while choice > 6 or choice < 1:
        print("Please choose one of the 6 groups")
        choice = int(input())

the section that doesn't work is this:

else:
    while choice > 6 or choice < 1:
        print("Please choose one of the 6 groups")
        choice = int(input())

the loop keeps going on and on no mater what i enter (unless i enter anything other than an integer where it'll show an error message). how do i stop this when i enter an integer between 1 and 6?

Body:
you may never get out from your while loop if choice < 6 so your program will never hit your for loop

to fix you can make a dict to hold all your options, read one time the  input and base on the input create contestants

options = {
    1: ["BeBe Zahara Benet", "Tyra Sanchez", "Raja", "Sharon Needles", "Jinkx Monsoon", "Bianca Del Rio", "Violet Chachki", "Bob the Drag Queen", "Sasha Velour", "Aquaria", "Yvie Oddly", "Chad Michaels", "Alaska", "Trixie Mattel", "Trinity the Tuck", "Monét X Change"],
    2: ["Nina Flowers", "Raven", "Manila Luzon", "Chad Micheals", "Alaska", "Courtney Act", "Ginger Minj", "Kim Chi", "Peppermint", "Eureka", "Brooke Lynn Hytes", "Katya", "Kennedy Davenport", "Monique Heart"],
    3: ["Akashia", "Jujubee", "Alexis Mateo", "Latrice Royale", "Coco Montrese", "Trinity K. Bonet", "Kennedy Davenport", "Chi Chi DeVayne", "Peppermint", "Kameron Michaels", "Ra'Jah O'Hara", "Raven", "Alaska", "BenDeLaCreme", "Trinity the Tuck"],
    4: ["Nina Flowers", "Pandora Boxx", "Yara Sofia", "Latrice Royale", "Ivy Winters", "BenDeLaCreme", "Katya", "Cynthia Lee Fontaine", "Valentina", "Monét X Change", "Nina West"],
    5: ["Victoria Parker", "Shangela", "Venus D-Lite", "Alisa Summers", "Penny Tration", "Kelly Mantle", "Tempest DuJour", "Laila McQueen", "Jaymes Mansfield", "Vanessa Vanjie Mateo", "Soju", "Mimi Imfurst", "Coco Montrese", "Thorgy Thor", "Jasmine Masters"],
    6: ["Carmen Carrera", "Shangela", "Kenya Michaels", "Trixie Mattel", "Naysha Lopez", "Cynthia Lee Fontaine", "Eureka", "Vanessa Vanjie Mateo", "Alyssa Edwards", "Tatianna", "Morgan McMichaels", "Latrice Royale", "Manila Luzon"]
}

print('''Which group of queens do you want to compete against?
1. Winners
2. Runner-ups
3. Lip sync assassins
4. Miss Congenialities
5. First Eliminated
6. Returning queens''')

choice = int(input())
while choice > 6 or choice < 1:
    print("Please choose one of the 6 groups")
    choice = int(input())

contestants = options[choice]


问:
Kotlin Inline function in SceneRenderer
If an inline function is used in a render loop, will there be any performance benefit?

```<code>class SceneRenderer(val f: () -> Unit): GLSurfaceView.Renderer {
  override fun onSurfaceCreated(glUnused: GL10, config: EGLConfig) { ... }

  override fun onSurfaceChanged(glUnused: GL10, width: Int, height: Int) { ... }

  override fun onDrawFrame(glUnused: GL10) {
    ...
    inlineFun(f)
    ...
  }

  private inline fun inlineFun(f: () -> Unit) {
    f.invoke()
  }
}
</code>```

Or is it enough to use a direct function call?

```<code>override fun onDrawFrame(glUnused: GL10) {
  ...
  f.invoke()
  ...
}
</code>```

Thanks in advance!

答:
TL;DR

Or is it enough to use a direct function call?

Yes, it is.

Inline

Kotlinlang:

Using higher-order functions imposes certain runtime penalties: each
  function is an object, and it captures a closure, i.e. those variables
  that are accessed in the body of the function. Memory allocations
  (both for function objects and classes) and virtual calls introduce
  runtime overhead.

Your function is not high-order, since it is inside the class SceneRenderer and there will be no reasonable impact making it inline.

Inlining may cause the generated code to grow; however, if we do it in
  a reasonable way (i.e. avoiding inlining large functions), it will pay
  off in performance, especially at "megamorphic" call-sites inside
  loops.

Title: Kotlin Inline function in SceneRenderer

Body:
If an inline function is used in a render loop, will there be any performance benefit?

class SceneRenderer(val f: () -> Unit): GLSurfaceView.Renderer {
  override fun onSurfaceCreated(glUnused: GL10, config: EGLConfig) { ... }

  override fun onSurfaceChanged(glUnused: GL10, width: Int, height: Int) { ... }

  override fun onDrawFrame(glUnused: GL10) {
    ...
    inlineFun(f)
    ...
  }

  private inline fun inlineFun(f: () -> Unit) {
    f.invoke()
  }
}

Or is it enough to use a direct function call?

override fun onDrawFrame(glUnused: GL10) {
  ...
  f.invoke()
  ...
}

Thanks in advance!


问:
Material icons not displayed - Quasar
I have a quasar project in which the material icons are being displayed as text instead of icons.
I did install the packages using npm. Even though, it is not working.

Below is my app.js file

```<code>require('./bootstrap');

window.Vue = require('vue');

require('quasar/dist/quasar.css');
require('quasar/dist/quasar.min.css');

import Quasar from 'quasar';
import 'vuetify/dist/vuetify.min.css';
import Vuetify from 'vuetify';
import Vue from 'vue';

import Plugin from '@quasar/quasar-ui-qiconpicker';
import '@quasar/quasar-ui-qiconpicker/dist/index.css';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/eva-icons.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/fontawesome-v5.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/ionicons-v4.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/material-icons-outlined.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/material-icons-round.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/material-icons-sharp.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/material-icons.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/mdi-v4.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/themify.umd.js';

Vue.use(Plugin)

Vue.use(Quasar);
Vue.use(Vuetify);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('example-component1', require('./components/Com.vue').default);
Vue.component('example-component2', require('./components/Comp.vue').default);

let app = new Vue({
        el: '#app',
        icons: {
        iconfont: 'mdi', // default - only for display purposes
        },
        });
</code>```

答:
Have you added material icons font to the document?
https://fonts.googleapis.com/icon?family=Material+Icons&yav=40bde127</p>

Title: Material icons not displayed - Quasar

Body:
I have a quasar project in which the material icons are being displayed as text instead of icons.
I did install the packages using npm. Even though, it is not working.

Below is my app.js file

require('./bootstrap');

window.Vue = require('vue');

require('quasar/dist/quasar.css');
require('quasar/dist/quasar.min.css');

import Quasar from 'quasar';
import 'vuetify/dist/vuetify.min.css';
import Vuetify from 'vuetify';
import Vue from 'vue';

import Plugin from '@quasar/quasar-ui-qiconpicker';
import '@quasar/quasar-ui-qiconpicker/dist/index.css';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/eva-icons.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/fontawesome-v5.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/ionicons-v4.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/material-icons-outlined.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/material-icons-round.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/material-icons-sharp.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/material-icons.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/mdi-v4.umd.js';
import '@quasar/quasar-ui-qiconpicker/dist/icon-set/themify.umd.js';

Vue.use(Plugin)

Vue.use(Quasar);
Vue.use(Vuetify);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('example-component1', require('./components/Com.vue').default);
Vue.component('example-component2', require('./components/Comp.vue').default);

let app = new Vue({
        el: '#app',
        icons: {
        iconfont: 'mdi', // default - only for display purposes
        },
        });


问:
How do I customize dialog signal/slot in pyQT?
I have a set of buttons, OK and Cancel

```<code>buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok|
                                    QtGui.QDialogButtonBox.Cancel)
</code>```

I want a dialogue prompt when we click on Cancel

```<code>self.connect(buttonBox, SIGNAL("rejected()"),
                            self, SLOT("reject()"))
    def reject(self):
        print 'hello'
        self.emit(SIGNAL("reject()"))
</code>```

I am not sure what to emit. I don't want to just close the thing. I know how to create a QMessageBox when I press X. I want to do the prompt and closing in reject.

I hope it makes sense. Thanks.

For your information, when I press X to close the entire application, I have an overriden method

```<code>def closeEvent(self, event):
    reply = QtGui.QMessageBox.question(self, 'Message', 'Are you sure to quit?', QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
    if reply == QtGui.QMessageBox.Yes:
        event.accept()
    else:
        event.ignore()
</code>```

This override self.close() method.

答:
Let's overwrite the accept() function.</p>

```<code>def accept(self):
    if validation_ok():
        super().accept()
</code>```

Body:
I have a set of buttons, OK and Cancel

buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok|
                                    QtGui.QDialogButtonBox.Cancel)

I want a dialogue prompt when we click on Cancel

self.connect(buttonBox, SIGNAL("rejected()"),
                            self, SLOT("reject()"))
    def reject(self):
        print 'hello'
        self.emit(SIGNAL("reject()"))

I am not sure what to emit. I don't want to just close the thing. I know how to create a QMessageBox when I press X. I want to do the prompt and closing in reject.

I hope it makes sense. Thanks.

For your information, when I press X to close the entire application, I have an overriden method

def closeEvent(self, event):
    reply = QtGui.QMessageBox.question(self, 'Message', 'Are you sure to quit?', QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
    if reply == QtGui.QMessageBox.Yes:
        event.accept()
    else:
        event.ignore()

This override self.close() method.

Body:
Let's overwrite the accept() function.

def accept(self):
    if validation_ok():
        super().accept()


问:
Why does Bottom Sheet Dialog not expand on tablet?
I have impelemented a BottomSheetDialog in my app but when I install it on a tablet and have the tablet laying down it does not expand fully on first click. It expands up to Collapsed state first and you have to drag it up to see everything. Why does it do this? Is it some setting you can change in your style?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
    app:behavior_peekHeight="0dp"
    >
   ...

</LinearLayout>
```

<pre class="lang-java prettyprint-override"><code>val view = layoutInflater.inflate(R.layout.home_bottom_sheet_dialog, null)
val bottomSheetDialog = BottomSheetDialog(activity!!)

bottomSheetDialog.setContentView(view)
bottomSheetDialog.show()
</code>```

I use API 22 AndroidX with kotlin.

答:
As Sinan Ceylan said this part of the layout is not needed.

app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
    app:behavior_peekHeight="0dp"

But to fix my problem I sat the peakHeight variable of BottomSheetBehavior to something large before it is shown.

```<code>bottomSheetDialog.setContentView(view)
bottomSheetDialog.behavior.peekHeight = 1000
bottomSheetDialog.show()
</code>```

Body:
I have impelemented a BottomSheetDialog in my app but when I install it on a tablet and have the tablet laying down it does not expand fully on first click. It expands up to Collapsed state first and you have to drag it up to see everything. Why does it do this? Is it some setting you can change in your style?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
    app:behavior_peekHeight="0dp"
    >
   ...

</LinearLayout>

val view = layoutInflater.inflate(R.layout.home_bottom_sheet_dialog, null)
val bottomSheetDialog = BottomSheetDialog(activity!!)

bottomSheetDialog.setContentView(view)
bottomSheetDialog.show()

I use API 22 AndroidX with kotlin.

Body:
As Sinan Ceylan said this part of the layout is not needed.

app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
    app:behavior_peekHeight="0dp"

But to fix my problem I sat the peakHeight variable of BottomSheetBehavior to something large before it is shown.

bottomSheetDialog.setContentView(view)
bottomSheetDialog.behavior.peekHeight = 1000
bottomSheetDialog.show()


问:
I'm making a "parallax" effect but it doesn't work
I'm kinda new to HTML and CSS and am building a website, but I don't seem to be abled to create a parallex effect on my image... The image is just not showing. Can you see what's wrong with my (simplyfied) code?

.parallax {
  background-image: url("images/start-background.jpg");
  height: 100%;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link href="./style.css" type="text/css" rel="stylesheet">
</head>

<body>
  <div class="parallax"></div>
  <h1 class="title-home">This is my title</h1>
  <h2 class="subtitle-home">This is my subtitle. Example, example, etc.</h2>
  <div class="parallax"></div>
</body>

</html></code>```

答:
You should set a min-height.I made 500px here but you can change.

.parallax {
  /* The image used */
  background-image: url("https://www.metoffice.gov.uk/binaries/content/gallery/metofficegovuk/hero-images/weather/cloud/cumulus-cloud.jpg");
  min-height: 500px;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link href="./style.css" type="text/css" rel="stylesheet">
</head>

<body>
  <div class="parallax"></div>
  <h1 class="title-home">This is my title</h1>
  <h2 class="subtitle-home">This is my subtitle. Example, example, etc.</h2>
  <div class="parallax"></div>
</body>

</html></code>```

Body:
I'm kinda new to HTML and CSS and am building a website, but I don't seem to be abled to create a parallex effect on my image... The image is just not showing. Can you see what's wrong with my (simplyfied) code?

.parallax {
  background-image: url("images/start-background.jpg");
  height: 100%;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

<!DOCTYPE html>

  <link href="./style.css" type="text/css" rel="stylesheet">

This is my title

This is my subtitle. Example, example, etc.

Body:
You should set a min-height.I made 500px here but you can change.

.parallax {
  /* The image used */
  background-image: url("https://www.metoffice.gov.uk/binaries/content/gallery/metofficegovuk/hero-images/weather/cloud/cumulus-cloud.jpg");
  min-height: 500px;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

<!DOCTYPE html>
<html>

<head>
  <link href="./style.css" type="text/css" rel="stylesheet">
</head>

<body>
  <div class="parallax"></div>
  <h1 class="title-home">This is my title</h1>
  <h2 class="subtitle-home">This is my subtitle. Example, example, etc.</h2>
  <div class="parallax"></div>
</body>

</html>


问:
Deleting records from the created form in c#
I m working with c#, in this i want to delete record from the form for that i have the following code..

```<code>     private void button3_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data  Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
        con.Open();
        string sql = "DELETE FROM tblCompany WHERE (CoCode = 1)";

    }
</code>```

but i m not getting the answer...

答:
You need to setup an OleDbCommand

The full code for your case,

```<code>private void button3_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data  Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
        string sql = "DELETE FROM tblCompany WHERE (CoCode = 1)";

        con.Open();
        OleDbCommand cmd = new OleDbCommand(sql, con);
        cmd.ExecuteNonQuery();
        con.Close();

    }
</code>```

For more information of the whole implementation, read here
http://www.java2s.com/Code/CSharp/Database-ADO.net/DeletedatabaserecordsthroughOleDbCommandandverifytheresults.htm

Body:
I m working with c#, in this i want to delete record from the form for that i have the following code..

     private void button3_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data  Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
        con.Open();
        string sql = "DELETE FROM tblCompany WHERE (CoCode = 1)";

    }

but i m not getting the answer...

Body:
You need to setup an OleDbCommand

The full code for your case,

private void button3_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data  Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
        string sql = "DELETE FROM tblCompany WHERE (CoCode = 1)";

        con.Open();
        OleDbCommand cmd = new OleDbCommand(sql, con);
        cmd.ExecuteNonQuery();
        con.Close();

    }

For more information of the whole implementation, read here
http://www.java2s.com/Code/CSharp/Database-ADO.net/DeletedatabaserecordsthroughOleDbCommandandverifytheresults.htm


问:
C++ : forward declaring const with internal linkage
I want to forward declare a const variable without giving it external linkage. It seems to me, however, that this is impossible because the extern keyword simultaneously means "this has external linkage" and "this is a variable declaration, not a definition", and I can't get one without the other:

```<code>//// main.cpp: ////

extern const char table[256];    // forward declaration. External linkage.
// const char table[256];        // Error: table requires an initializer
// static const char table[256]; // Same error

// foo uses table so I need it forward declared:
char foo()
{
    // uses table
}

const char table[256] = {...}; // Actual definition
</code>```

Is my understanding correct? Are there any workarounds?

答:
First of all, a forward declaration is defined only for types. You can type

```<code>class X;
</code>```

and then use X * for example.

What you are trying to achieve here, is declare symbol before actual usage.
The only way I know to do this is via extern keyword.

But if want to make symbol linkage internal, anonymous namespace can help

```<code>namespace {
extern const char table[256]; // symbol declaration. Internal linkage.
}

char foo() {
    // use table
}
namespace {
const char table[256] = {...}; // symbol definition. Internal linkage.
}
</code>```

Here is a test you can do

```<code>$ cat test.cc
extern const char moo[4];
char foo() { return moo[2]; }
const char moo[4] = {0};
$ g++  -c test.cc -o test.o -O3 && g++ test.o -shared -o test.so && nm -gD test.so | grep moo
00000000000005ad R moo
$
</code>```

```<code>$ cat test.cc
namespace {
    extern const char moo[4];
}
char foo() { return moo[2]; }
namespace {
    const char moo[4] = {0};
}
$ g++  -c test.cc -o test.o -O3 && g++ test.o -shared -o test.so && nm -gD test.so | grep moo
$
</code>```

Body:
I want to forward declare a const variable without giving it external linkage. It seems to me, however, that this is impossible because the extern keyword simultaneously means "this has external linkage" and "this is a variable declaration, not a definition", and I can't get one without the other:

//// main.cpp: ////

extern const char table[256];    // forward declaration. External linkage.
// const char table[256];        // Error: table requires an initializer
// static const char table[256]; // Same error

// foo uses table so I need it forward declared:
char foo()
{
    // uses table
}

const char table[256] = {...}; // Actual definition

Is my understanding correct? Are there any workarounds?

Body:
First of all, a forward declaration is defined only for types. You can type

class X;

and then use X * for example.

What you are trying to achieve here, is declare symbol before actual usage.
The only way I know to do this is via extern keyword.

But if want to make symbol linkage internal, anonymous namespace can help

namespace {
extern const char table[256]; // symbol declaration. Internal linkage.
}

char foo() {
    // use table
}
namespace {
const char table[256] = {...}; // symbol definition. Internal linkage.
}

Here is a test you can do

$ cat test.cc
extern const char moo[4];
char foo() { return moo[2]; }
const char moo[4] = {0};
$ g++  -c test.cc -o test.o -O3 && g++ test.o -shared -o test.so && nm -gD test.so | grep moo
00000000000005ad R moo
$

$ cat test.cc
namespace {
    extern const char moo[4];
}
char foo() { return moo[2]; }
namespace {
    const char moo[4] = {0};
}
$ g++  -c test.cc -o test.o -O3 && g++ test.o -shared -o test.so && nm -gD test.so | grep moo
$


问:
Google Script: Send email 7 days before date in cell
I've made a script where I need some help. This one is getting the 3rd line and sends an email which doesn't make sense for me.
There's an date cell. I want to have it that way it should send an email with that row where the day in this cell is in 7 days. Do you know how to handle it? So I think this what I did is totally wrong.

Sheet looks like this with few names:
Surname | Name | Date

And if date is in 7 days I want to get an email.

```<code>function sendEmail() {

 //setup function
 var ActiveSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet2');
 var StartRow = 3;
 var RowRange = ActiveSheet.getLastRow() - StartRow + 1;
 var WholeRange = ActiveSheet.getRange(StartRow,1,RowRange,11);
 var AllValues = WholeRange.getValues();

 var message = "";
 //iterate loop
 for (i in AllValues) {

 //set current row
 var CurrentRow = AllValues[0];

 //set HTML template for information
  message =
      "<p><b>Name: </b>" + CurrentRow[5] + ' ' + CurrentRow[4] + ' ' + "</p>" +
      "<p><b>Department: </b>" + CurrentRow[8] + "</p>" +
      "<p><b>Location: </b>" + CurrentRow[1] + "</p>" +
      "<p><b>Last working day on: </b>" + CurrentRow[6] + "</p>" +
      "<p><b>Exit date -contractual-: </b>" + CurrentRow[7] + "</p>" +
        "<p><b>Useful links: </b>"+' ' +  "</p><br><br>";

  //set the row to look at
  var setRow = parseInt(i) + StartRow;

  //mark row as "sent"
  ActiveSheet.getRange(setRow, 13).setValue("Mail sent");
}

 //define who to send grants to
 var SendTo = "person@domain.com";

 //set subject line
  var Subject = "Subject: " + CurrentRow[4] + ' ' + CurrentRow[5] + ' | Date: ' + CurrentRow[7];

  //send the actual email
  MailApp.sendEmail({
      to: SendTo,
      cc: "",
      subject: Subject,
      htmlBody: message,
});
}
</code>```

Thank you!

答:
I think this is what you want.  Perhaps an image of your sheet would make it clearer.

```<code>function sendEmail() {
  var ss=SpreadsheetApp.getActive();
  var ash=ss.getSheetByName('Sheet2');
  var sr=3;
  var vA=ash.getRange(sr,1,ash.getLastRow()-sr+1,12).getValues();
  //Header Row: none,Location,None,None,Name1,Name2,LastWorkingDay,ExitDate,Department,None,None,Email Sent
  var message="";
  var dt=new Date();
  var tdv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
  for (var i=0;i<vA.length;i++) {
    message =
      "<p><b>Name: </b>" + vA[i][5] + ' ' + vA[i][4] + ' ' + "</p>" +
        "<p><b>Department: </b>" + vA[i][8] + "</p>" +
          "<p><b>Location: </b>" + vA[i][1] + "</p>" +
            "<p><b>Last working day on: </b>" + vA[i][6] + "</p>" +
              "<p><b>Exit date -contractual-: </b>" + vA[i][7] + "</p>" +
                "<p><b>Useful links: </b>"+' ' +  "</p><br><br>";
    var SendTo="person@domain.com";
    var Subject="Subject: " + vA[i][4] + ' ' + vA[i][5] + ' | Date: ' + vA[i][7];
    var cd=new Date(vA[i][7]);//Im guessing this is the date for the 7 day threshold
    var cdv=new Date(cd.getFullYear(),cd.getMonth(),cd.getDate()-7).valueOf();
    if(tdv>=cdv && vA[i][11]!='Email Sent') {
      MailApp.sendEmail({to: SendTo,subject: Subject,htmlBody: message});
      ash.getRange(sr,12).setValue("Email Sent");
    }
  }
}
</code>```

This is what I think your header row might be.

Body:
I've made a script where I need some help. This one is getting the 3rd line and sends an email which doesn't make sense for me.
There's an date cell. I want to have it that way it should send an email with that row where the day in this cell is in 7 days. Do you know how to handle it? So I think this what I did is totally wrong.

Sheet looks like this with few names:
Surname | Name | Date

And if date is in 7 days I want to get an email.

function sendEmail() {

 //setup function
 var ActiveSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet2');
 var StartRow = 3;
 var RowRange = ActiveSheet.getLastRow() - StartRow + 1;
 var WholeRange = ActiveSheet.getRange(StartRow,1,RowRange,11);
 var AllValues = WholeRange.getValues();

 var message = "";
 //iterate loop
 for (i in AllValues) {

 //set current row
 var CurrentRow = AllValues[0];

 //set HTML template for information
  message =
      "
Name: " + CurrentRow[5] + ' ' + CurrentRow[4] + ' ' + "
" +
      "
Department: " + CurrentRow[8] + "
" +
      "
Location: " + CurrentRow[1] + "
" +
      "
Last working day on: " + CurrentRow[6] + "
" +
      "
Exit date -contractual-: " + CurrentRow[7] + "
" +
        "
Useful links: "+' ' +  "

";

  //set the row to look at
  var setRow = parseInt(i) + StartRow;

  //mark row as "sent"
  ActiveSheet.getRange(setRow, 13).setValue("Mail sent");
}

 //define who to send grants to
 var SendTo = "person@domain.com";

 //set subject line
  var Subject = "Subject: " + CurrentRow[4] + ' ' + CurrentRow[5] + ' | Date: ' + CurrentRow[7];

  //send the actual email
  MailApp.sendEmail({
      to: SendTo,
      cc: "",
      subject: Subject,
      htmlBody: message,
});
}

Thank you!

Body:
I think this is what you want.  Perhaps an image of your sheet would make it clearer.

function sendEmail() {
  var ss=SpreadsheetApp.getActive();
  var ash=ss.getSheetByName('Sheet2');
  var sr=3;
  var vA=ash.getRange(sr,1,ash.getLastRow()-sr+1,12).getValues();
  //Header Row: none,Location,None,None,Name1,Name2,LastWorkingDay,ExitDate,Department,None,None,Email Sent
  var message="";
  var dt=new Date();
  var tdv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
  for (var i=0;i<vA.length;i++) {
    message =
      "<p><b>Name: </b>" + vA[i][5] + ' ' + vA[i][4] + ' ' + "</p>" +
        "<p><b>Department: </b>" + vA[i][8] + "</p>" +
          "<p><b>Location: </b>" + vA[i][1] + "</p>" +
            "<p><b>Last working day on: </b>" + vA[i][6] + "</p>" +
              "<p><b>Exit date -contractual-: </b>" + vA[i][7] + "</p>" +
                "<p><b>Useful links: </b>"+' ' +  "</p><br><br>";
    var SendTo="person@domain.com";
    var Subject="Subject: " + vA[i][4] + ' ' + vA[i][5] + ' | Date: ' + vA[i][7];
    var cd=new Date(vA[i][7]);//Im guessing this is the date for the 7 day threshold
    var cdv=new Date(cd.getFullYear(),cd.getMonth(),cd.getDate()-7).valueOf();
    if(tdv>=cdv && vA[i][11]!='Email Sent') {
      MailApp.sendEmail({to: SendTo,subject: Subject,htmlBody: message});
      ash.getRange(sr,12).setValue("Email Sent");
    }
  }
}

This is what I think your header row might be.