问:
Wordpress: search users using 'first_name' and 'last_name'?
UPDATE: I mean to search user in the Admin User Dashboard at /wp-admin/users.php

Is there a way to search users using 'first_name' and 'last_name'?

I found this plugin but not working at all: https://wordpress.org/plugins/full-name-search-in-wp-admin/

I also found this function, but neither is working in my site. Do I need to call the function with a hook/action?:

```<code>function search_users($search_term){

    global $wpdb;
    $the_users = $wpdb->get_results("SELECT DISTINCT $wpdb->users.* FROM $wpdb->users INNER JOIN $wpdb->usermeta um1 ON um1.user_id = $wpdb->users.ID JOIN $wpdb->usermeta um2 ON um2.user_id = $wpdb->users.ID WHERE (um1.meta_key = 'uRPhICRS_capabilities' AND um1.meta_value LIKE '%agent%') AND ((um2.meta_key = 'first_name' OR um2.meta_key = 'last_name') AND um2.meta_value LIKE '%".$search_term."%');");

    if(!empty($the_users)){
        return $the_users;
    }
    else{
        return false;
    }

}
</code>```

答:
Two Ways as follow:

1) If You want to check from the string match in either firstname or lastname, following will be work:

```<code>$users_query = new WP_User_Query(
  array(
    'meta_query' => array(
    'relation' => 'OR',
      array(
        'key' => 'first_name',
        'value' => $str,
        'compare' => 'LIKE'
      ),
    array(
        'key' => 'last_name',
        'value' => $str,
        'compare' => 'LIKE'
      )
    )
  )
 );

$users = $users_query->get_results();
</code>```

2) If you want to check the user from username, user_nicename, user_email, firstname, or lastname use following code:

```<code>//search from the user table
$users_query_table = new WP_User_Query(
  array(
    'search' => "*{$str}*",
    'search_columns' => array(
    'user_login',
    'user_nicename',
    'user_email',
  ),
) );
$users_via_table = $users_query_table->get_results();

//search from the usermeta
$users_query_meta = new WP_User_Query(
  array(
    'meta_query' => array(
    'relation' => 'OR',
      array(
        'key' => 'first_name',
        'value' => $str,
        'compare' => 'LIKE'
      ),
    array(
        'key' => 'last_name',
        'value' => $str,
        'compare' => 'LIKE'
      )
    )
  )
 );

$users_via_meta = $users_query_meta->get_results();

// Merge both result..
$combined_users = array_merge( $users_via_table, $users_via_meta );

// Get unique user
$users = array_unique( $combined_users, SORT_REGULAR );
</code>```

Body:
UPDATE: I mean to search user in the Admin User Dashboard at /wp-admin/users.php

Is there a way to search users using 'first_name' and 'last_name'?

I found this plugin but not working at all: https://wordpress.org/plugins/full-name-search-in-wp-admin/

I also found this function, but neither is working in my site. Do I need to call the function with a hook/action?:

function search_users($search_term){

    global $wpdb;
    $the_users = $wpdb->get_results("SELECT DISTINCT $wpdb->users.* FROM $wpdb->users INNER JOIN $wpdb->usermeta um1 ON um1.user_id = $wpdb->users.ID JOIN $wpdb->usermeta um2 ON um2.user_id = $wpdb->users.ID WHERE (um1.meta_key = 'uRPhICRS_capabilities' AND um1.meta_value LIKE '%agent%') AND ((um2.meta_key = 'first_name' OR um2.meta_key = 'last_name') AND um2.meta_value LIKE '%".$search_term."%');");

    if(!empty($the_users)){
        return $the_users;
    }
    else{
        return false;
    }

}

Body:
Two Ways as follow:

1) If You want to check from the string match in either firstname or lastname, following will be work:

$users_query = new WP_User_Query(
  array(
    'meta_query' => array(
    'relation' => 'OR',
      array(
        'key' => 'first_name',
        'value' => $str,
        'compare' => 'LIKE'
      ),
    array(
        'key' => 'last_name',
        'value' => $str,
        'compare' => 'LIKE'
      )
    )
  )
 );

$users = $users_query->get_results();

2) If you want to check the user from username, user_nicename, user_email, firstname, or lastname use following code:

//search from the user table
$users_query_table = new WP_User_Query(
  array(
    'search' => "*{$str}*",
    'search_columns' => array(
    'user_login',
    'user_nicename',
    'user_email',
  ),
) );
$users_via_table = $users_query_table->get_results();

//search from the usermeta
$users_query_meta = new WP_User_Query(
  array(
    'meta_query' => array(
    'relation' => 'OR',
      array(
        'key' => 'first_name',
        'value' => $str,
        'compare' => 'LIKE'
      ),
    array(
        'key' => 'last_name',
        'value' => $str,
        'compare' => 'LIKE'
      )
    )
  )
 );

$users_via_meta = $users_query_meta->get_results();

// Merge both result..
$combined_users = array_merge( $users_via_table, $users_via_meta );

// Get unique user
$users = array_unique( $combined_users, SORT_REGULAR );


来源: stackexchange

问:
Modifying a String (char array)
I am trying to modify a string in C language

```<code>    char signal_cat[8];

        if (k == 1) {
            strcpy_s(signal_cat, "HPHA",6);             //why cant I change char array (string) values???
        }
        else if (k == 2) {
            strcpy_s(signal_cat, "Normal",6);
        }

        printf("Original signal category: %s \n", signal_cat);

</code>```

When I run this it shows an exception "Unhandled exception at 0x7BEBF71D (ucrtbased.dll) in Lab3Parti.exe: 0xC0000005: Access violation reading location 0x00000006"

I have tried

```<code>signal_cat = "HPHA";
</code>```

too, but an error shows "expression must be a modifiable lvalue"

Does anyone know how I can go about doing this?

答:
What is strcpy_s?   Do you have a prototype for it in your code (ie. have you included the correct files for declarations?)  What are its arguments, and why are you using it?

You are obviously learning C; it is not in your best interest to start with some vendors proprietary (and often bizarre) extensions?   Learn the language, learn its established (standard) interfaces, then, if absolutely necessary, endure some vendors twisted extensions is a good process to follow:

```<code>#include <string.h>
#include <stdio.h>
int main(void) {
  char signal_cat[8];
  strncpy(signal_cat, "HPHA", sizeof signal_cat);
  printf("%s\n", signal_cat);
  strncpy(signal_cat, "Normal", sizeof signal_cat);
  printf("%s\n", signal_cat);
  return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Modifying a String (char array)

Body:
I am trying to modify a string in C language

    char signal_cat[8];

        if (k == 1) {
            strcpy_s(signal_cat, "HPHA",6);             //why cant I change char array (string) values???
        }
        else if (k == 2) {
            strcpy_s(signal_cat, "Normal",6);
        }

        printf("Original signal category: %s \n", signal_cat);

When I run this it shows an exception "Unhandled exception at 0x7BEBF71D (ucrtbased.dll) in Lab3Parti.exe: 0xC0000005: Access violation reading location 0x00000006"

I have tried

signal_cat = "HPHA";

too, but an error shows "expression must be a modifiable lvalue"

Does anyone know how I can go about doing this?

Body:
What is strcpy_s?   Do you have a prototype for it in your code (ie. have you included the correct files for declarations?)  What are its arguments, and why are you using it?

You are obviously learning C; it is not in your best interest to start with some vendors proprietary (and often bizarre) extensions?   Learn the language, learn its established (standard) interfaces, then, if absolutely necessary, endure some vendors twisted extensions is a good process to follow:

#include <string.h>
#include <stdio.h>
int main(void) {
  char signal_cat[8];
  strncpy(signal_cat, "HPHA", sizeof signal_cat);
  printf("%s\n", signal_cat);
  strncpy(signal_cat, "Normal", sizeof signal_cat);
  printf("%s\n", signal_cat);
  return 0;
}


问:
Visual Studio - Renaming Files From Uppercase to Lowercase

Short Version

I found myself losing alot of time renaming + including files in my Xamarin.Forms Projects because any change from Upercase to Lowercase (or vice versa) only in the files, will result in no change what so ever in the Project file, so i have a few questions:

Is there an option in Visual Studio that makes it take into account file renaming from Upercase to Lowercase? (See Edit Below)

What's the best way of changing alot of files from Upercase to Lowercase without delete/re-adding them?

Is renaming the file includes in the .csproj directly a Good Practice? if not, what is the best for this kind of scenarios?

Longer Version + Adicional Info

I had to include over 2000 images (Android + iOS and their respective sizes). So i started copying the files into the correct directory and include them in the Mobile Projects, the problem came when i already included the files in the project and some of the files had Uppercase letters that i haven't noticed before, so i made changes by hand to all the files, when i noticed that those changes weren't reflected in the Solution Explorer/Project File, i tried manually and got this error:

Edit: It seems this issue was apparently resolved in VS2019 arround v.16.1, but only if the file wasn't renamed externally. Since i did that i got this warning. This anwsers my first question.

And one solution that i found was renaming like: Foo.png > fooo.png > foo.png

But that would be exponentialy time-consuming by the number of files i had to edit, so i made this piece of code:

```<code>string filepath = @"C:\Users\(...)";
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.png", SearchOption.AllDirectories))
{
    if (file.Name.Any(char.IsUpper))
    {
        File.Move(file.FullName, file.FullName.Replace(file.Name, file.Name.ToLower()));
    }
}
</code>```

What it does is basically create a new file but with Lowercase, that means i still have to Remove the old References and Include the new Files. This doesn't seem right since a simple rename would do.

What's my go to option here?

答:
Windows as operating system is ascendant of the operating system where there was no difference in lower and uppercase. As such at today's state Windows treats the files with same letters as the same though technically it can remember and display lower and upper cases in file names.

Overall it means your request is not natural in Windows. Maybe someone can provide you with some hack, but if you want to resolve this problem quickly move your project to the Mac where this works differently at the operating system level, perform your operation in Visual Studio for Mac and then you can continue to use Windows if you prefer.

EDIT: Actually I can tell you one hack for Windows. First rename file to whatever you want (like add 1 at the end) and then rename it to the desired file name. It will work properly.

Body:
Short Version

I found myself losing alot of time renaming + including files in my Xamarin.Forms Projects because any change from Upercase to Lowercase (or vice versa) only in the files, will result in no change what so ever in the Project file, so i have a few questions:

Is there an option in Visual Studio that makes it take into account file renaming from Upercase to Lowercase? (See Edit Below)

What's the best way of changing alot of files from Upercase to Lowercase without delete/re-adding them?

Is renaming the file includes in the .csproj directly a Good Practice? if not, what is the best for this kind of scenarios?

Longer Version + Adicional Info

I had to include over 2000 images (Android + iOS and their respective sizes). So i started copying the files into the correct directory and include them in the Mobile Projects, the problem came when i already included the files in the project and some of the files had Uppercase letters that i haven't noticed before, so i made changes by hand to all the files, when i noticed that those changes weren't reflected in the Solution Explorer/Project File, i tried manually and got this error:

Edit: It seems this issue was apparently resolved in VS2019 arround v.16.1, but only if the file wasn't renamed externally. Since i did that i got this warning. This anwsers my first question.

And one solution that i found was renaming like: Foo.png > fooo.png > foo.png

But that would be exponentialy time-consuming by the number of files i had to edit, so i made this piece of code:

string filepath = @"C:\Users\(...)";
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.png", SearchOption.AllDirectories))
{
    if (file.Name.Any(char.IsUpper))
    {
        File.Move(file.FullName, file.FullName.Replace(file.Name, file.Name.ToLower()));
    }
}

What it does is basically create a new file but with Lowercase, that means i still have to Remove the old References and Include the new Files. This doesn't seem right since a simple rename would do.

What's my go to option here?


问:
Access an Array inside an Object with square brackets inside a ngFor
Basically, I've created a HTML that similar to the example :

```<code><div *ngFor="let formElements of formTemplate">
 <div *ngFor="let opt of staticEnumVals[formElements.testId]">
  <!-- do smth here -->
 </div>
</div>
</code>```

Basically formTemplate is an Array with Objects, each Object has a property called "testId".
staticEnumVals is an Object thats build like that

```<code> {
  "testId": [ {},{},{} ],
  "testId2" [ {},{},{} ],
 }
</code>```

The keys "testId" and "testId2" are actual keys that match the Keys from formTemplate[i].testId.
Basically I want to iterate through an array out of my staticEnumVals and the array is selected dynamically based on the id from the first *ngFor

Basically im looking for an elegant way to achieve my second iteration, square brackets doesnt work.
I think my problem is clear enough, im sorry for the weird title.
Thanks in advance

答:
After adding types to the staticEnumVals this worked for me.</p>

```<code>@Component({
  selector: 'test',
  template: `
      <div *ngFor="let formElements of formTemplate">
          <div *ngFor="let opt of staticEnumVals[formElements.testId]">
              {{opt.name}}
          </div>
      </div>
  `
})
export class TestComponent {
   private formTemplate: { testId: string }[] = [
    {testId: '3'}, {testId: '2'}, {testId: '3'}
  ];

  private staticEnumVals: { [id: string]: [any] } = {
    '1': [{name: 'id1'}],
    '2': [{name: 'id2'}],
    '3': [{name: 'id3'}],
  };

}
</code>```

Body:
Basically, I've created a HTML that similar to the example :

Basically formTemplate is an Array with Objects, each Object has a property called "testId".
staticEnumVals is an Object thats build like that

 {
  "testId": [ {},{},{} ],
  "testId2" [ {},{},{} ],
 }

The keys "testId" and "testId2" are actual keys that match the Keys from formTemplate[i].testId.
Basically I want to iterate through an array out of my staticEnumVals and the array is selected dynamically based on the id from the first *ngFor

Basically im looking for an elegant way to achieve my second iteration, square brackets doesnt work.
I think my problem is clear enough, im sorry for the weird title.
Thanks in advance

Body:
After adding types to the staticEnumVals this worked for me.

@Component({
  selector: 'test',
  template: `
      <div *ngFor="let formElements of formTemplate">
          <div *ngFor="let opt of staticEnumVals[formElements.testId]">
              {{opt.name}}
          </div>
      </div>
  `
})
export class TestComponent {
   private formTemplate: { testId: string }[] = [
    {testId: '3'}, {testId: '2'}, {testId: '3'}
  ];

  private staticEnumVals: { [id: string]: [any] } = {
    '1': [{name: 'id1'}],
    '2': [{name: 'id2'}],
    '3': [{name: 'id3'}],
  };

}


问:
Compare two dataframes Pyspark
I'm trying to compare two data frames with have same number of columns i.e. 4 columns with id as key column in both data frames

```<code>df1 = spark.read.csv("/path/to/data1.csv")
df2 = spark.read.csv("/path/to/data2.csv")
</code>```

Now I want to append new column to DF2 i.e. column_names which is the list of the columns with different values than df1

```<code>df2.withColumn("column_names",udf())
</code>```

DF1

```<code>+------+---------+--------+------+
|   id | |name  | sal  | Address |
+------+---------+--------+------+
|     1|  ABC   | 5000 | US      |
|     2|  DEF   | 4000 | UK      |
|     3|  GHI   | 3000 | JPN     |
|     4|  JKL   | 4500 | CHN     |
+------+---------+--------+------+
</code>```

DF2:

```<code>+------+---------+--------+------+
|   id | |name  | sal  | Address |
+------+---------+--------+------+
|     1|  ABC   | 5000 | US      |
|     2|  DEF   | 4000 | CAN     |
|     3|  GHI   | 3500 | JPN     |
|     4|  JKL_M | 4800 | CHN     |
+------+---------+--------+------+
</code>```

Now I want DF3

DF3:

```<code>+------+---------+--------+------+--------------+
|   id | |name  | sal  | Address | column_names |
+------+---------+--------+------+--------------+
|     1|  ABC   | 5000 | US      |  []          |
|     2|  DEF   | 4000 | CAN     |  [address]   |
|     3|  GHI   | 3500 | JPN     |  [sal]       |
|     4|  JKL_M | 4800 | CHN     |  [name,sal]  |
+------+---------+--------+------+--------------+
</code>```

I saw this SO question, How to compare two dataframe and print columns that are different in scala. Tried that, however the result is different.

I'm thinking of going with a UDF function by passing row from each dataframe to udf and compare column by column and return column list. However for that both the data frames should be in sorted order so that same id rows will be sent to udf. Sorting is costly operation here. Any solution?

答:
Here is your solution with UDF, I have changed first dataframe name dynamically so that it will be not ambiguous during check. Go through below code and let me know in case any concerns.

```<code>>>> from pyspark.sql.functions import *
>>> df.show()
+---+----+----+-------+
| id|name| sal|Address|
+---+----+----+-------+
|  1| ABC|5000|     US|
|  2| DEF|4000|     UK|
|  3| GHI|3000|    JPN|
|  4| JKL|4500|    CHN|
+---+----+----+-------+

>>> df1.show()
+---+----+----+-------+
| id|name| sal|Address|
+---+----+----+-------+
|  1| ABC|5000|     US|
|  2| DEF|4000|    CAN|
|  3| GHI|3500|    JPN|
|  4|JKLM|4800|    CHN|
+---+----+----+-------+

>>> df2 = df.select([col(c).alias("x_"+c) for c in df.columns])
>>> df3 = df1.join(df2, col("id") == col("x_id"), "left")

 //udf declaration

>>> def CheckMatch(Column,r):
...     check=''
...     ColList=Column.split(",")
...     for cc in ColList:
...             if(r[cc] != r["x_" + cc]):
...                     check=check + "," + cc
...     return check.replace(',','',1).split(",")

>>> CheckMatchUDF = udf(CheckMatch)

//final column that required to select
>>> finalCol = df1.columns
>>> finalCol.insert(len(finalCol), "column_names")

>>> df3.withColumn("column_names", CheckMatchUDF(lit(','.join(df1.columns)),struct([df3[x] for x in df3.columns])))
       .select(finalCol)
       .show()
+---+----+----+-------+------------+
| id|name| sal|Address|column_names|
+---+----+----+-------+------------+
|  1| ABC|5000|     US|          []|
|  2| DEF|4000|    CAN|   [Address]|
|  3| GHI|3500|    JPN|       [sal]|
|  4|JKLM|4800|    CHN| [name, sal]|
+---+----+----+-------+------------+
</code>```

Title: Compare two dataframes Pyspark

Body:
I'm trying to compare two data frames with have same number of columns i.e. 4 columns with id as key column in both data frames

df1 = spark.read.csv("/path/to/data1.csv")
df2 = spark.read.csv("/path/to/data2.csv")

Now I want to append new column to DF2 i.e. column_names which is the list of the columns with different values than df1

df2.withColumn("column_names",udf())

DF1

+------+---------+--------+------+
|   id | |name  | sal  | Address |
+------+---------+--------+------+
|     1|  ABC   | 5000 | US      |
|     2|  DEF   | 4000 | UK      |
|     3|  GHI   | 3000 | JPN     |
|     4|  JKL   | 4500 | CHN     |
+------+---------+--------+------+

DF2:

+------+---------+--------+------+
|   id | |name  | sal  | Address |
+------+---------+--------+------+
|     1|  ABC   | 5000 | US      |
|     2|  DEF   | 4000 | CAN     |
|     3|  GHI   | 3500 | JPN     |
|     4|  JKL_M | 4800 | CHN     |
+------+---------+--------+------+

Now I want DF3

DF3:

+------+---------+--------+------+--------------+
|   id | |name  | sal  | Address | column_names |
+------+---------+--------+------+--------------+
|     1|  ABC   | 5000 | US      |  []          |
|     2|  DEF   | 4000 | CAN     |  [address]   |
|     3|  GHI   | 3500 | JPN     |  [sal]       |
|     4|  JKL_M | 4800 | CHN     |  [name,sal]  |
+------+---------+--------+------+--------------+

I saw this SO question, How to compare two dataframe and print columns that are different in scala. Tried that, however the result is different.

I'm thinking of going with a UDF function by passing row from each dataframe to udf and compare column by column and return column list. However for that both the data frames should be in sorted order so that same id rows will be sent to udf. Sorting is costly operation here. Any solution?

Body:
Here is your solution with UDF, I have changed first dataframe name dynamically so that it will be not ambiguous during check. Go through below code and let me know in case any concerns.

>>> from pyspark.sql.functions import *
>>> df.show()
+---+----+----+-------+
| id|name| sal|Address|
+---+----+----+-------+
|  1| ABC|5000|     US|
|  2| DEF|4000|     UK|
|  3| GHI|3000|    JPN|
|  4| JKL|4500|    CHN|
+---+----+----+-------+

>>> df1.show()
+---+----+----+-------+
| id|name| sal|Address|
+---+----+----+-------+
|  1| ABC|5000|     US|
|  2| DEF|4000|    CAN|
|  3| GHI|3500|    JPN|
|  4|JKLM|4800|    CHN|
+---+----+----+-------+

>>> df2 = df.select([col(c).alias("x_"+c) for c in df.columns])
>>> df3 = df1.join(df2, col("id") == col("x_id"), "left")

 //udf declaration

>>> def CheckMatch(Column,r):
...     check=''
...     ColList=Column.split(",")
...     for cc in ColList:
...             if(r[cc] != r["x_" + cc]):
...                     check=check + "," + cc
...     return check.replace(',','',1).split(",")

>>> CheckMatchUDF = udf(CheckMatch)

//final column that required to select
>>> finalCol = df1.columns
>>> finalCol.insert(len(finalCol), "column_names")

>>> df3.withColumn("column_names", CheckMatchUDF(lit(','.join(df1.columns)),struct([df3[x] for x in df3.columns])))
       .select(finalCol)
       .show()
+---+----+----+-------+------------+
| id|name| sal|Address|column_names|
+---+----+----+-------+------------+
|  1| ABC|5000|     US|          []|
|  2| DEF|4000|    CAN|   [Address]|
|  3| GHI|3500|    JPN|       [sal]|
|  4|JKLM|4800|    CHN| [name, sal]|
+---+----+----+-------+------------+


问:
Cannot find control with name, first time opening mat dialog
I am getting this error

```<code>main.d6f3e40c71733c3e7aa5.js:1 ERROR Error: Cannot find control with name: 'email'
</code>```

Only on chrome. The form is inside an angular material dialog. I use an injected global service to initialize the form, so before I click the button that opens the modal, the form inside the service is already initialized and if I console.log it I can see the control there.

When I open the mat dialog it is using the service to get the fields as follows:

                    {{'login.validation.email-or-pass'|translate}}

                        <input [placeholder]="'login.email' | translate" autocomplete="off"
                               class="email-address form-input" formControlName="email"
                               id="email" required="required">

                                {{'login.validation.email.required' | translate}}

                                {{'login.validation.email.email' | translate}}

```

<p>The input</p>

<pre class="lang-html prettyprint-override"><code>    <input [placeholder]="'login.email' | translate" autocomplete="off"
                               class="email-address form-input" formControlName="email"
</code>```

is the one throwing the error.

If I close the dialog and reopen it, it does not throw the error again. It only happens the first time. And as I said it only happens in chrome. I tested in firefox and it works fine.
                               id="email" required="required">

答:
Seems to be related to chrome version 80.

Look here for fixes: https://github.com/angular/angular/issues/35190

Or follow Add FormControl accroding to the data returned from backend but got two different error in Angular app

Body:
I am getting this error

main.d6f3e40c71733c3e7aa5.js:1 ERROR Error: Cannot find control with name: 'email'

Only on chrome. The form is inside an angular material dialog. I use an injected global service to initialize the form, so before I click the button that opens the modal, the form inside the service is already initialized and if I console.log it I can see the control there.

When I open the mat dialog it is using the service to get the fields as follows:

                    {{'login.validation.email-or-pass'|translate}}

                        <input [placeholder]="'login.email' | translate" autocomplete="off"
                               class="email-address form-input" formControlName="email"
                               id="email" required="required">

                                {{'login.validation.email.required' | translate}}

                                {{'login.validation.email.email' | translate}}

The input

    <input [placeholder]="'login.email' | translate" autocomplete="off"
                               class="email-address form-input" formControlName="email"

is the one throwing the error.

If I close the dialog and reopen it, it does not throw the error again. It only happens the first time. And as I said it only happens in chrome. I tested in firefox and it works fine.
                               id="email" required="required">


问:
Why do you need to re-request Media Projection permission on Phone Restart
I am using the Media Projection API for a pet project and one thing I have noticed is that when the phone is restarted, the intent which is redelivered to my broadcast receiver (on boot completed) does not contain the permission to record the user's screen even though I accepted the permissions before I rebooted the device.

Does anyone know if this is standard and if this is documented anywhere or is their a way to maintain the permissions granted by the user across device reboots?

答:
Does anyone know if this is standard

Yes. That permission is on a per-process basis. This is in contrast to classic runtime permissions, which are persistent.

if this is documented anywhere

I doubt it.

is their a way to maintain the permissions granted by the user across device reboots?

Not without modifying the OS, or maybe with root privileges.


问:
check owner permissions from file (multiple paths results) in bash script
friends,
I have a problem with my script. I tried to find a full path of /bin/openssl and next save results to the file and read from the file paths and check permissions and owners.
But in the result file /tmp/lista.txt , I have multiple paths. How to make a script to read and check every path from file result.
Any ideas?</p>

```<code>#!/bin/sh

module_id="AV.1.8.2.1"
echo " === $module_id module === "

#MODULE BODY
find / -wholename "*bin/openssl" -print > /tmp/list.txt

file="/tmp/list.txt"
path=$(cat /tmp/list.txt)
os=$(uname)
permission_other_good=0

if [ -e $path ]
then
    if [ $os = "Linux" ]
    then
        gid_min=$(grep ^GID_MIN /etc/login.defs)
        gid_min_value=$(echo $gid_min | cut -d " " -f2)
        uid_min=$(grep ^UID_MIN /etc/login.defs)
        uid_min_value=$(echo $uid_min | cut -d " " -f2)
        sys_gid_max=$(grep ^SYS_GID_MAX /etc/login.defs)
        sys_gid_max_value=$(echo $sys_gid_max | cut -d " " -f2)
        sys_uid_max=$(grep ^SYS_UID_MAX /etc/login.defs)
        sys_uid_max_value=$(echo $sys_uid_max | cut -d " " -f2)
        user_uid=$(stat -c %u $path)
        user=$(stat -c %U $path)
        group_gid=$(stat -c %g $path)
        group=$(stat -c %G $path)
        permission_other=$(stat -c %A $path | cut -b 8-10)

        if [ -z $gid_min_value ]
        then
            gid_min_value=1000
        fi

        if [ -z $uid_min_value ]
        then
            uid_min_value=1000
        fi

        if [ -z $sys_gid_max_value ]
        then
            sys_gid_max_value=$((gid_min_value-1))
        fi

        if [ -z $sys_uid_max_value ]
        then
            sys_uid_max_value=$((uid_min_value-1))
        fi
    fi

    if [ $os = "AIX" ]
    then
        gid_min_value=$(cat /etc/security/.ids | cut -d " " -f4)
        sys_gid_max_value=$((gid_min_value-1))
        uid_min_value=$(cat /etc/security/.ids | cut -d " " -f2)
        sys_uid_max_value=$((uid_min_value-1))
        user_uid=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f1)
        user=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f2 | cut -d ")" -f1)
        group_gid=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f1)
        group=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f2 | cut -d ")" -f1)
        permission_other=$(istat $path | awk -F " " 'NR==2{print $2}' | cut -b 7-9)
    fi

    if [ $permission_other = "r-x" ] || [ $permission_other = "r--" ] || [ $permission_other = "--x" ] || [ $permission_other = "---" ]
    then
        permission_other_good=1
    fi

    if [ $user_uid -le $sys_uid_max_value ] && [ $group_gid -le $sys_gid_max_value ] && [ $permission_other_good -eq 1 ]
    then
        compliant="Yes"
        actual_value="user = $user group = $group permission = $permission_other"
    else
        compliant="No"
        actual_value="user = $user group = $group permission = $permission_other"
    fi
else
    compliant="N/A"
    actual_value="File $file does not exist"
fi

# SCRIPT RESULT

echo :::$module_id:::$compliant:::$actual_value:::
echo " === End of $module_id module === "
</code>```

答:
Since you are using bash, I would advise against using temporary files because it has a lot of caveats due to the filesystem (what happens if your disk is full? what happens if the file exists? what happens if you don’t have write permissions over the base directory? etc.) and due to the limitations of storing filenames in line-based text files (though this should not be an issue for finding openssl).

If you want to parse a list of files, here is a common and safe way to do that:

find / -wholename "*bin/openssl" -print0 | while IFS= read -r -d '' path
do
  # Write your code here using the 'path' variable
done
```

<p>But because you are storing variables <em>inside</em> the for loop, they would be limited to the scope of the loop because of the pipe operation between <code>find</code> and <code>while</code>. You can circumvent this problem by using process substitution instead:</p>

<pre class="lang-sh prettyprint-override"><code>while IFS= read -r -d '' path
do
  # Write your code here using the 'path' variable
done < <(find / -wholename "*bin/openssl" -print0)
</code>```

This behaves essentially the same as the previous code, except that the variable scope is not limited to the loop.

PS. You will have to deal with the assignment of your variables over several openssl paths. If you just copy/paste your code inside the for loop, the value of compliant and actual_value will retain information for the last path in the loop, which is probably not what you want.

Body:
friends,
I have a problem with my script. I tried to find a full path of /bin/openssl and next save results to the file and read from the file paths and check permissions and owners.
But in the result file /tmp/lista.txt , I have multiple paths. How to make a script to read and check every path from file result.
Any ideas?

#!/bin/sh

module_id="AV.1.8.2.1"
echo " === $module_id module === "

#MODULE BODY
find / -wholename "*bin/openssl" -print > /tmp/list.txt

file="/tmp/list.txt"
path=$(cat /tmp/list.txt)
os=$(uname)
permission_other_good=0

if [ -e $path ]
then
    if [ $os = "Linux" ]
    then
        gid_min=$(grep ^GID_MIN /etc/login.defs)
        gid_min_value=$(echo $gid_min | cut -d " " -f2)
        uid_min=$(grep ^UID_MIN /etc/login.defs)
        uid_min_value=$(echo $uid_min | cut -d " " -f2)
        sys_gid_max=$(grep ^SYS_GID_MAX /etc/login.defs)
        sys_gid_max_value=$(echo $sys_gid_max | cut -d " " -f2)
        sys_uid_max=$(grep ^SYS_UID_MAX /etc/login.defs)
        sys_uid_max_value=$(echo $sys_uid_max | cut -d " " -f2)
        user_uid=$(stat -c %u $path)
        user=$(stat -c %U $path)
        group_gid=$(stat -c %g $path)
        group=$(stat -c %G $path)
        permission_other=$(stat -c %A $path | cut -b 8-10)

        if [ -z $gid_min_value ]
        then
            gid_min_value=1000
        fi

        if [ -z $uid_min_value ]
        then
            uid_min_value=1000
        fi

        if [ -z $sys_gid_max_value ]
        then
            sys_gid_max_value=$((gid_min_value-1))
        fi

        if [ -z $sys_uid_max_value ]
        then
            sys_uid_max_value=$((uid_min_value-1))
        fi
    fi

    if [ $os = "AIX" ]
    then
        gid_min_value=$(cat /etc/security/.ids | cut -d " " -f4)
        sys_gid_max_value=$((gid_min_value-1))
        uid_min_value=$(cat /etc/security/.ids | cut -d " " -f2)
        sys_uid_max_value=$((uid_min_value-1))
        user_uid=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f1)
        user=$(istat $path | awk -F " " 'NR==3{print $2}' | cut -d "(" -f2 | cut -d ")" -f1)
        group_gid=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f1)
        group=$(istat $path | awk -F " " 'NR==3{print $4}' | cut -d "(" -f2 | cut -d ")" -f1)
        permission_other=$(istat $path | awk -F " " 'NR==2{print $2}' | cut -b 7-9)
    fi

    if [ $permission_other = "r-x" ] || [ $permission_other = "r--" ] || [ $permission_other = "--x" ] || [ $permission_other = "---" ]
    then
        permission_other_good=1
    fi

    if [ $user_uid -le $sys_uid_max_value ] && [ $group_gid -le $sys_gid_max_value ] && [ $permission_other_good -eq 1 ]
    then
        compliant="Yes"
        actual_value="user = $user group = $group permission = $permission_other"
    else
        compliant="No"
        actual_value="user = $user group = $group permission = $permission_other"
    fi
else
    compliant="N/A"
    actual_value="File $file does not exist"
fi

# SCRIPT RESULT

echo :::$module_id:::$compliant:::$actual_value:::
echo " === End of $module_id module === "

Body:
Since you are using bash, I would advise against using temporary files because it has a lot of caveats due to the filesystem (what happens if your disk is full? what happens if the file exists? what happens if you don’t have write permissions over the base directory? etc.) and due to the limitations of storing filenames in line-based text files (though this should not be an issue for finding openssl).

If you want to parse a list of files, here is a common and safe way to do that:

find / -wholename "*bin/openssl" -print0 | while IFS= read -r -d '' path
do
  # Write your code here using the 'path' variable
done

But because you are storing variables inside the for loop, they would be limited to the scope of the loop because of the pipe operation between find and while. You can circumvent this problem by using process substitution instead:

while IFS= read -r -d '' path
do
  # Write your code here using the 'path' variable
done < <(find / -wholename "*bin/openssl" -print0)

This behaves essentially the same as the previous code, except that the variable scope is not limited to the loop.

PS. You will have to deal with the assignment of your variables over several openssl paths. If you just copy/paste your code inside the for loop, the value of compliant and actual_value will retain information for the last path in the loop, which is probably not what you want.


问:
Is there a way to use a custom Angular Directive to apply a ngIf "effect"?
I have an application which has a Role based access. I'm using *ngIf's to allow/block users from access some components.

Is there a way to use a custom directive that will process the "existence" of the component based on the user role; instead of a complete *ngIf condition like this:

```<code><admin-menu *ngIf="user.role =='admin'"></admin-menu>

<admin-menu my-custom-directive ></admin-menu>

    my-custom-directive {

    //make the component where this directive is attached render or vanish based on the user.role
    ngAfterViewInit() {
        if(user.role == 'admin'){
            //render the component
        } else {
            //vanish the component
        }
    }
}
</code>```

答:
For the role base access to the user you can you the auth guard service.
This is the API link https://angular.io/api/router/CanActivate.

Body:
I have an application which has a Role based access. I'm using *ngIf's to allow/block users from access some components.

Is there a way to use a custom directive that will process the "existence" of the component based on the user role; instead of a complete *ngIf condition like this:

<admin-menu *ngIf="user.role =='admin'"></admin-menu>

<admin-menu my-custom-directive ></admin-menu>

    my-custom-directive {

    //make the component where this directive is attached render or vanish based on the user.role
    ngAfterViewInit() {
        if(user.role == 'admin'){
            //render the component
        } else {
            //vanish the component
        }
    }
}


问:
I want to create a Menu in shape of semi circle, with N number of menu-items
I want to create a menu like this,

.

But not getting perfect centre points for menu items(UIButton),
I'm using Stride(from:) in getCirclePoints() to get CGPoint for menu-items with equal spacing from starting and ending angle.

numberOfViews variable contains the number of menu-items that i want to place.

If numberOfViews = 5 then, the output will be

.

Anyone is having better idea to create such dynamic menu, or help me out in this piece of code.

Thank you.

```<code>class ViewController: UIViewController {

    @IBOutlet weak var btnMenu: UIButton!

    var numberOfViews: Int = 4
    var arrPoints: [CGPoint] = []
    var arrMenuItems = [UIButton]()

    var menuFrame: CGRect!
    var itemFrame: [CGRect] = []
    var isMenuOpen = false

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
}

extension ViewController {

    @IBAction func btnMenuTapped(_ sender: UIButton) {
        menu(open: isMenuOpen)
    }
}

extension ViewController {

    func prepareUI() {
        createMenuItems()
        storeFrame()
        btnMenu.makeRounded(0, isFullyRounded: true)
        menu(open: false, withDuration: 0.0001)
    }

    func createMenuItems() {
        arrPoints = getCirclePoints(centerPoint: btnMenu.center, radius: (self.view.bounds.width/CGFloat(numberOfViews) + 25), n: numberOfViews)
        for i in 0..<numberOfViews {
            drawMenuItem(for: i)
        }
    }

    func drawMenuItem(for index: Int) {
        var menuItem: UIButton
        let rect = CGRect(x: arrPoints[index].x, y: arrPoints[index].y, width: 50, height: 50)
        menuItem = UIButton(frame: rect)
        menuItem.makeRounded(0, isFullyRounded: true)
        menuItem.backgroundColor = UIColor.randomColor
        arrMenuItems.append(menuItem)
        view.addSubview(menuItem)
    }

    func getCirclePoints(centerPoint point: CGPoint, radius: CGFloat, n: Int)->[CGPoint] {
        let result: [CGPoint] = stride(from: -168, to: 12, by: Double(180 / n)).map {
            let bearing = CGFloat($0) * .pi / 180
            let x = point.x + radius * cos(bearing)
            let y = point.y + radius * sin(bearing)
            return CGPoint(x: x, y: y)
        }
        return result
    }

    func storeFrame() {
        menuFrame = btnMenu.frame
    }

    func menu(open isOpen: Bool, withDuration duration: Double = 0.5) {
        if isOpen {
            self.view.bringSubviewToFront(self.btnMenu)
            UIView.animate(withDuration: duration, animations: {
                for element in self.arrMenuItems {
                    element.frame = self.menuFrame
                }
            }) { (completed) in
                self.isMenuOpen = !self.isMenuOpen
            }
        }else {
            UIView.animate(withDuration: duration, animations: {
                for (index, element) in self.arrMenuItems.enumerated() {
                    element.frame = CGRect(x: self.arrPoints[index].x, y: self.arrPoints[index].y, width: element.frame.width, height: element.frame.height)
                }
                self.view.layoutIfNeeded()
            }) { (completed) in
                self.isMenuOpen = !self.isMenuOpen
            }
        }
    }
}

extension UIButton {

    func makeRounded(_ cornerRadius: CGFloat, isFullyRounded: Bool) {
        if isFullyRounded {
            self.layer.cornerRadius = self.frame.width / 2
        }else {
            self.layer.cornerRadius = cornerRadius
        }
    }
}

// MARK:- Color extension
extension UIColor {

    // To get random color
    static var randomColor: UIColor {
        return UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0)
    }
}
</code>```

答:
For a given position of the showMenu button which shows/collapse menu options on tap.

Assume we have an circle around the showMenu button, where we have to display menu options on the circumference of the circle.
Given position of showMenu button : (cx,xy) is known

get the position of the menu options using formula below:

```<code>x = cx + r * cos(a)
y = cy + r * sin(a)
</code>```

where r is the radius of circle, (cx,cy) the centre of showMenu, and the angle = (90)/numberofMenu

For a given set of points derived from formula for each menu buttons, add your Menu button options and animate accordingly.

Body:
I want to create a menu like this,

.

But not getting perfect centre points for menu items(UIButton),
I'm using Stride(from:) in getCirclePoints() to get CGPoint for menu-items with equal spacing from starting and ending angle.

numberOfViews variable contains the number of menu-items that i want to place.

If numberOfViews = 5 then, the output will be

.

Anyone is having better idea to create such dynamic menu, or help me out in this piece of code.

Thank you.

class ViewController: UIViewController {

    @IBOutlet weak var btnMenu: UIButton!

    var numberOfViews: Int = 4
    var arrPoints: [CGPoint] = []
    var arrMenuItems = [UIButton]()

    var menuFrame: CGRect!
    var itemFrame: [CGRect] = []
    var isMenuOpen = false

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
}

extension ViewController {

    @IBAction func btnMenuTapped(_ sender: UIButton) {
        menu(open: isMenuOpen)
    }
}

extension ViewController {

    func prepareUI() {
        createMenuItems()
        storeFrame()
        btnMenu.makeRounded(0, isFullyRounded: true)
        menu(open: false, withDuration: 0.0001)
    }

    func createMenuItems() {
        arrPoints = getCirclePoints(centerPoint: btnMenu.center, radius: (self.view.bounds.width/CGFloat(numberOfViews) + 25), n: numberOfViews)
        for i in 0..<numberOfViews {
            drawMenuItem(for: i)
        }
    }

    func drawMenuItem(for index: Int) {
        var menuItem: UIButton
        let rect = CGRect(x: arrPoints[index].x, y: arrPoints[index].y, width: 50, height: 50)
        menuItem = UIButton(frame: rect)
        menuItem.makeRounded(0, isFullyRounded: true)
        menuItem.backgroundColor = UIColor.randomColor
        arrMenuItems.append(menuItem)
        view.addSubview(menuItem)
    }

    func getCirclePoints(centerPoint point: CGPoint, radius: CGFloat, n: Int)->[CGPoint] {
        let result: [CGPoint] = stride(from: -168, to: 12, by: Double(180 / n)).map {
            let bearing = CGFloat($0) * .pi / 180
            let x = point.x + radius * cos(bearing)
            let y = point.y + radius * sin(bearing)
            return CGPoint(x: x, y: y)
        }
        return result
    }

    func storeFrame() {
        menuFrame = btnMenu.frame
    }

    func menu(open isOpen: Bool, withDuration duration: Double = 0.5) {
        if isOpen {
            self.view.bringSubviewToFront(self.btnMenu)
            UIView.animate(withDuration: duration, animations: {
                for element in self.arrMenuItems {
                    element.frame = self.menuFrame
                }
            }) { (completed) in
                self.isMenuOpen = !self.isMenuOpen
            }
        }else {
            UIView.animate(withDuration: duration, animations: {
                for (index, element) in self.arrMenuItems.enumerated() {
                    element.frame = CGRect(x: self.arrPoints[index].x, y: self.arrPoints[index].y, width: element.frame.width, height: element.frame.height)
                }
                self.view.layoutIfNeeded()
            }) { (completed) in
                self.isMenuOpen = !self.isMenuOpen
            }
        }
    }
}

extension UIButton {

    func makeRounded(_ cornerRadius: CGFloat, isFullyRounded: Bool) {
        if isFullyRounded {
            self.layer.cornerRadius = self.frame.width / 2
        }else {
            self.layer.cornerRadius = cornerRadius
        }
    }
}

// MARK:- Color extension
extension UIColor {

    // To get random color
    static var randomColor: UIColor {
        return UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0)
    }
}

Body:
For a given position of the showMenu button which shows/collapse menu options on tap.

Assume we have an circle around the showMenu button, where we have to display menu options on the circumference of the circle.
Given position of showMenu button : (cx,xy) is known

get the position of the menu options using formula below:

x = cx + r * cos(a)
y = cy + r * sin(a)

where r is the radius of circle, (cx,cy) the centre of showMenu, and the angle = (90)/numberofMenu

For a given set of points derived from formula for each menu buttons, add your Menu button options and animate accordingly.


问:
Can't run go tests from GoLand (Intellij Idea): compilation failed
I've made simple application in go and trying to run tests with GUI tools of GoLand.

In myfile_test.go file near test func I press green button that should start test. But I get error message: "Compilation failed" and message in console:

```<code># command-line-arguments [command-line-arguments.test]
./myfile_test.go:21:11: undefined: MyStruct
./myfile_test.go:22:12: undefined: MyFuncName
./myfile_test.go:33:12: undefined: AnotherStruct

Compilation finished with exit code 2
</code>```

Other variants (Run test with Coverage/CPU Profile) don't work either. GoLand 2020.1 EAP. The same problem occurred in older versions of GoLand.

But test from console starts normally:

```<code>go test -v

=== RUN   TestMyStruct_MyMethod
--- PASS: TestMyStruct_MyMethod (0.00s)
PASS
ok      _/home/username/projects/my_project_name     0.002s
</code>```

答:
I solved the problem with initializing new go module and enabling Go Modules Integration:

1) Run in Terminal go mod init my_module_name

2) Click "File -> Settings" or press Ctrl+Alt+S

3) Check "Enable Go Modules Integration" and Apply button

Now all test functionality in GoLand works well (including tests with coverage, etc.)

Body:
I've made simple application in go and trying to run tests with GUI tools of GoLand.

In myfile_test.go file near test func I press green button that should start test. But I get error message: "Compilation failed" and message in console:

# command-line-arguments [command-line-arguments.test]
./myfile_test.go:21:11: undefined: MyStruct
./myfile_test.go:22:12: undefined: MyFuncName
./myfile_test.go:33:12: undefined: AnotherStruct

Compilation finished with exit code 2

Other variants (Run test with Coverage/CPU Profile) don't work either. GoLand 2020.1 EAP. The same problem occurred in older versions of GoLand.

But test from console starts normally:

go test -v

=== RUN   TestMyStruct_MyMethod
--- PASS: TestMyStruct_MyMethod (0.00s)
PASS
ok      _/home/username/projects/my_project_name     0.002s


问:
Kubernetes Ingress difference of path/backend specification
What's the difference between these two specs in my ingress resource. Do they perform the same thing? When do I use which type?

```<code>spec:
  rules:
  - host: {{ .Values.Subdomain }}{{ .Values.Domain }}
    http:
      paths:
        - path: /api
          backend:
            serviceName: {{ .Values.ServiceName }}
            servicePort: 80
</code>```

And:

```<code>spec:
  rules:
  - host: {{ .Values.Subdomain }}{{ .Values.Domain }}
    http:
      paths:
      - backend:
          serviceName: {{ .Values.ServiceName }}
          servicePort: 80
        path: /api
</code>```

答: There is no difference. The paths field is a list of maps(dictionary), where each map consists of path and backend field. Within a map, the order of fields doesn't matter which is the case in your two templates.

Body:
What's the difference between these two specs in my ingress resource. Do they perform the same thing? When do I use which type?

spec:
  rules:
  - host: {{ .Values.Subdomain }}{{ .Values.Domain }}
    http:
      paths:
        - path: /api
          backend:
            serviceName: {{ .Values.ServiceName }}
            servicePort: 80

And:

spec:
  rules:
  - host: {{ .Values.Subdomain }}{{ .Values.Domain }}
    http:
      paths:
      - backend:
          serviceName: {{ .Values.ServiceName }}
          servicePort: 80
        path: /api


问:
Deploying Django on Heroku?
I am trying to host a Python\Django app on Heroku. I followed the guide on heroku website but when I execute the line "heroku ps:scale web:1" it comes back the following message:

No process types on ⬢ salty-brushlands-45215.

   ▸    Upload a Procfile to add process types.

   ▸    https://devcenter.heroku.com/articles/procfile

I already tryed to commit a Procfile into my project (searching for a solution) but I don't know if requires any configuration inside it. Help please!

答:
1.Create .txt file.

2.add this raw to your file:

```<code>worker: python main.py
</code>```

3.save file and delete file extension (.txt)

4.add Procfile to master folder

5.deploy

Title: Deploying Django on Heroku?

Body:
1.Create .txt file.

2.add this raw to your file:

worker: python main.py

3.save file and delete file extension (.txt)

4.add Procfile to master folder

5.deploy


问:
How to use multiple connections one by module in Laravel
I'm creating an application in Laravel where each one will have its database, is it possible for each module to receive its connection file instead of leaving everything inside the config/database?</p>

答:
Yes its possible follow the following step and let me if any query

Step 1 : Add the second db code in config->database.php bottom of mysql=>[....]

```<code>'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST2', '100.10.0.100'),  // note add your hostname
            'port' => env('DB_PORT2', '3306'),
            'database' => env('DB_DATABASE2', 'forge'),
            'username' => env('DB_USERNAME2', 'forge'),
            'password' => env('DB_PASSWORD2', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
</code>```

Step 2 : Add the code in .evn file

```<code>DB_CONNECTION2=mysql
DB_HOST2=100.10.0.100 // Add your hostname
DB_PORT2=3306
DB_DATABASE2=test // add your DB name
DB_USERNAME2=testuser // add your user name
DB_PASSWORD2=test123 // add your pass
</code>```

Step 3 : you can access in controller like (Note : use youe table name and fields)

```<code>$records= DB::connection('mysql2');
       $records1 = $records->table('contact');
       $records2 = $records1->where('mobile',$client_mob)
                   ->where('delete',0)
                   ->first(['id','converted']);
</code>```

All the best...

Body:
Yes its possible follow the following step and let me if any query

Step 1 : Add the second db code in config->database.php bottom of mysql=>[....]

'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST2', '100.10.0.100'),  // note add your hostname
            'port' => env('DB_PORT2', '3306'),
            'database' => env('DB_DATABASE2', 'forge'),
            'username' => env('DB_USERNAME2', 'forge'),
            'password' => env('DB_PASSWORD2', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

Step 2 : Add the code in .evn file

DB_CONNECTION2=mysql
DB_HOST2=100.10.0.100 // Add your hostname
DB_PORT2=3306
DB_DATABASE2=test // add your DB name
DB_USERNAME2=testuser // add your user name
DB_PASSWORD2=test123 // add your pass

Step 3 : you can access in controller like (Note : use youe table name and fields)

$records= DB::connection('mysql2');
       $records1 = $records->table('contact');
       $records2 = $records1->where('mobile',$client_mob)
                   ->where('delete',0)
                   ->first(['id','converted']);

All the best...


问:
How skip NullReferenceException in Get API
Here create an API to get the records, in my entity relation table there are twice start date and end date. Here my compulsion is one of them need to keep Null able type.

Here is ER that is SchoolCourses:

```<code> public class SchoolCourses
{
    public Guid ID { get; set; }

    public DateTime StartCourseDate { get; set; }
    public DateTime EndCourseDate { get; set; }

    public DateTime? StartSemDate { get; set; }  // Null able type
    public DateTime? EndSemDate { get; set; }  // Null able type

}
</code>```

I creates a repository for getting the value:

```<code>public async Task<ICollection<SchoolCourses>> GetcourseBySchoolId(Guid SchoolId)
    {
        List<SchoolCourses> schoolCourses = null;

            schoolCourses = await _GpsContext.SchoolCourses.AsNoTracking()
            .Where(x => x.SchoolsID == SchoolId)
            .ToListAsync();
        return schoolCourses;
    }
</code>```

And the Controller are like this:

```<code>    public async Task<IActionResult> GetforSchoolCourse(string SchoolId)
    {
        var result = await _schoolCoursesRepository.GetcourseBySchoolId(Guid.Parse(SchoolId));
        List<GetSchoolCourseBySchoolIdVm> getSchoolCourseBySchoolIdVms = new List<GetSchoolCourseBySchoolIdVm>();

        foreach (SchoolCourses schoolCourse in result)
        {
            getSchoolCourseBySchoolIdVms.Add(new GetSchoolCourseBySchoolIdVm
            {
                id = schoolCourse.ID.ToString(),
                StarCoursetDate = schoolCourse.StartCourseDate.ToString(),
                EndCourseDate = schoolCourse.EndCourseDate.ToString(),
                StartSemDate = schoolCourse.StartSemDate.ToString(),
                EndSemDate = schoolCourse.EndSemDate.ToString(),

            });

        }
        return Ok(getSchoolCourseBySchoolIdVms);
    }
</code>```

Here is View Model for reference:

```<code>public class GetSchoolCourseBySchoolIdVm
{
    public string id { get; set; }

    public string StarCoursetDate { get; set; }
    public string EndCourseDate { get; set; }

    public string StartSemDate { get; set; }
    public string EndSemDate { get; set; }

}
</code>```

After doing all the above staff it is getting exception error in swagger is following:

```<code>System.NullReferenceException: Object reference not set to an instance of an object.;
</code>```

答:
In your SchoolCourses model StartSemDate and EndSemDate are nullable types, so it must be possible that values of those fields are null. That should have been checked before using it, unlike you have used

```<code>StartSemDate = schoolCourse.StartSemDate.ToString(),
EndSemDate = schoolCourse.EndSemDate.ToString(),
</code>```

here if any of the date is null then calling .ToString() method on it will throw NullReferenceException. Use safe navigation operator to check

```<code>schoolCourse.StartSemDate?.ToString()
</code>```

or

```<code>schoolCourse.StartSemDate != null ? schoolCourse.StartSemDate.ToString() : string.Empty
</code>```

Body:
Here create an API to get the records, in my entity relation table there are twice start date and end date. Here my compulsion is one of them need to keep Null able type.

Here is ER that is SchoolCourses:

 public class SchoolCourses
{
    public Guid ID { get; set; }

    public DateTime StartCourseDate { get; set; }
    public DateTime EndCourseDate { get; set; }

    public DateTime? StartSemDate { get; set; }  // Null able type
    public DateTime? EndSemDate { get; set; }  // Null able type

}

I creates a repository for getting the value:

public async Task<ICollection<SchoolCourses>> GetcourseBySchoolId(Guid SchoolId)
    {
        List<SchoolCourses> schoolCourses = null;

            schoolCourses = await _GpsContext.SchoolCourses.AsNoTracking()
            .Where(x => x.SchoolsID == SchoolId)
            .ToListAsync();
        return schoolCourses;
    }

And the Controller are like this:

    public async Task<IActionResult> GetforSchoolCourse(string SchoolId)
    {
        var result = await _schoolCoursesRepository.GetcourseBySchoolId(Guid.Parse(SchoolId));
        List<GetSchoolCourseBySchoolIdVm> getSchoolCourseBySchoolIdVms = new List<GetSchoolCourseBySchoolIdVm>();

        foreach (SchoolCourses schoolCourse in result)
        {
            getSchoolCourseBySchoolIdVms.Add(new GetSchoolCourseBySchoolIdVm
            {
                id = schoolCourse.ID.ToString(),
                StarCoursetDate = schoolCourse.StartCourseDate.ToString(),
                EndCourseDate = schoolCourse.EndCourseDate.ToString(),
                StartSemDate = schoolCourse.StartSemDate.ToString(),
                EndSemDate = schoolCourse.EndSemDate.ToString(),

            });

        }
        return Ok(getSchoolCourseBySchoolIdVms);
    }

Here is View Model for reference:

public class GetSchoolCourseBySchoolIdVm
{
    public string id { get; set; }

    public string StarCoursetDate { get; set; }
    public string EndCourseDate { get; set; }

    public string StartSemDate { get; set; }
    public string EndSemDate { get; set; }

}

After doing all the above staff it is getting exception error in swagger is following:

System.NullReferenceException: Object reference not set to an instance of an object.;

Body:
In your SchoolCourses model StartSemDate and EndSemDate are nullable types, so it must be possible that values of those fields are null. That should have been checked before using it, unlike you have used

StartSemDate = schoolCourse.StartSemDate.ToString(),
EndSemDate = schoolCourse.EndSemDate.ToString(),

here if any of the date is null then calling .ToString() method on it will throw NullReferenceException. Use safe navigation operator to check

schoolCourse.StartSemDate?.ToString()

or

schoolCourse.StartSemDate != null ? schoolCourse.StartSemDate.ToString() : string.Empty


问:
Apache Spark: Get number of records per partition
I want to check how can we get information about each partition such as total no. of records in each partition on driver side when Spark job is submitted with deploy mode as a yarn cluster in order to log or print on the console.</p>

答:
For future PySpark users:</p>

```<code>from pyspark.sql.functions  import spark_partition_id
rawDf.withColumn("partitionId", spark_partition_id()).groupBy("partitionId").count().show()
</code>```

Body:
For future PySpark users:

from pyspark.sql.functions  import spark_partition_id
rawDf.withColumn("partitionId", spark_partition_id()).groupBy("partitionId").count().show()


问:
Deleting old version of GAE application is failed
I want to delete old version of GAE application, but deleting operation always fails since 5 months ago.

The error message is 'There is an operation pending for this application. Please wait and try again'.

I think it's inappropriate that we are charged to unnecessary instances and we couldn't delete these instances.

Technical details

GCP Console(GUI)

screenshot: https://gyazo.com/edcb1968944867c2a6a029efa7bf5bb5

Deleting the version from this page is failed.

The error message is 'There is an operation pending for this application. Please wait and try again'.

Stoping the version from this page is also failed.

The error message is 'This flexible version cannot be modified, it can only be deleted. Please re-deploy the version.'

CLI

Result when deleting version from CLI. (Occured internal error)

# https://cloud.google.com/sdk/gcloud/reference/app/versions/delete
$ gcloud app versions delete 20191028t001234
Deleting the following versions:
 - my-project/default/20191028t001234
Do you want to continue (Y/n)?  Y

Deleting [default/20191028t001234]...failed.
ERROR: (gcloud.app.versions.delete) Issue deleting version: [default/20191028t001234]

[default/20191028t001234]: Error Response: [13] Flex operation projects/my-project/regions/asia-northeast1/operations/aab27279-89bf-4deb-aecd-d25352977d11 error [INTERNAL]: An internal error occurred while processing task /appengine-flex-v1/delete_flex_deployment/flex_delete_resources>2020-01-06T11:26:23.364Z38645.oj.0: Deployment Manager operation my-project/operation-1578309983602-59b76edeb0758-e471c6e1-71f4fbeb errors: [code: "RESOURCE_ERROR"
location: "/deployments/aef-default-20191028t001234/resources/aef-default-20191028t001234-hcs"
message: "{\"ResourceType\":\"compute.v1.httpsHealthCheck\",\"ResourceErrorCode\":\"400\",\"ResourceErrorMessage\":{\"code\":400,\"errors\":[{\"domain\":\"global\",\"message\":\"The https_health_check resource \'projects/my-project/global/httpsHealthChecks/aef-default-20191028t001234-hcs\' is already being used by \'projects/my-project/global/backendServices/aef-default-20191028t001234-bs\'\",\"reason\":\"resourceInUseByAnotherResource\"}],\"message\":\"The https_health_check resource \'projects/my-project/global/httpsHealthChecks/aef-default-20191028t001234-hcs\' is already being used by \'projects/my-project/global/backendServices/aef-default-20191028t001234-bs\'\",\"statusMessage\":\"Bad Request\",\"requestPath\":\"https://compute.googleapis.com/compute/v1/projects/my-project/global/httpsHealthChecks/aef-default-20191028t001234-hcs\",\"httpMethod\":\"DELETE\"}}"
, code: "RESOURCE_ERROR"
location: "/deployments/aef-default-20191028t001234/resources/aef-default-20191028t001234-00"
message: "{\"ResourceType\":\"compute.beta.regionInstanceGroupManager\",\"ResourceErrorCode\":\"400\",\"ResourceErrorMessage\":{\"code\":400,\"errors\":[{\"domain\":\"global\",\"message\":\"The instance_group_manager resource \'projects/my-project/regions/asia-northeast1/instanceGroupManagers/aef-default-20191028t001234-00\' is already being used by \'projects/my-project/global/backendServices/aef-default-20191028t001234-bs\'\",\"reason\":\"resourceInUseByAnotherResource\"}],\"message\":\"The instance_group_manager resource \'projects/my-project/regions/asia-northeast1/instanceGroupManagers/aef-default-20191028t001234-00\' is already being used by \'projects/my-project/global/backendServices/aef-default-20191028t001234-bs\'\",\"statusMessage\":\"Bad Request\",\"requestPath\":\"https://compute.googleapis.com/compute/beta/projects/my-project/regions/asia-northeast1/instanceGroupManagers/aef-default-20191028t001234-00\",\"httpMethod\":\"DELETE\"}}"
]
```

答:
In cases like this, it's recommended for you to reach out directly to Google Cloud Platform Suppor Team directly - you can contact them here. As per other cases, like this one, they will be able to better assist you regarding payment - since you are unable to delete a version that you are not using and it's being billed for it - and should be able to help you fix the issue and delete it.

Let me know if the information helped you!


问:
There are possible way of dividing two float numbers which was casted from unsigned int make negative float result?
```<code>unsigned int deltaTime = now() - last();
unsigned int freq = getFreq();
float timeOfGap = float(deltaTime) / float(freq);

ASSERT(0.0f <= timeOfGap, "WHAT?");
</code>```

I got a really weired result from my program. I didn't catch a scene which is happened. But I have a log which said that really raised at least multiple times.

There are possible way of dividing between two float numbers which was casted from unsigned int make negative float result?

OK, thank you guys. I'm glad to see your attentions.
Let me try to add some descriptions about it. It'll be helpful for you.

I'm working for an online game, and this situation was raised rarely but frequently while hundreds of million times game was serving. I can't debug or catch the exact shot, but it is logged on the db error messages.

The timeOfGap should be NaN as you noticed, but the log didn't alert the value exactly. The timeOfGap is accumulated like below;

```<code>mTotalFrameRateTimeAsASecond += timeOfGap;
</code>```

And this program logs mTotalFrameRateTimeAsASecond, that was a negative value. But except this sign of value was a negative, it is correct value. Meaning, it point time as look as good if I divide the final value with a framerate. A hypothetical play time was 500 sec, it is -30000(with 60 framerate per sec).

答: Maybe it is not negative, but a NAN. 0.0f <= NAN is false. It may happen if both operands are zero.

ContentLicense: CC BY-SA 3.0

Body:
unsigned int deltaTime = now() - last();
unsigned int freq = getFreq();
float timeOfGap = float(deltaTime) / float(freq);

ASSERT(0.0f <= timeOfGap, "WHAT?");

I got a really weired result from my program. I didn't catch a scene which is happened. But I have a log which said that really raised at least multiple times.

There are possible way of dividing between two float numbers which was casted from unsigned int make negative float result?

OK, thank you guys. I'm glad to see your attentions.
Let me try to add some descriptions about it. It'll be helpful for you.

I'm working for an online game, and this situation was raised rarely but frequently while hundreds of million times game was serving. I can't debug or catch the exact shot, but it is logged on the db error messages.

The timeOfGap should be NaN as you noticed, but the log didn't alert the value exactly. The timeOfGap is accumulated like below;

mTotalFrameRateTimeAsASecond += timeOfGap;

And this program logs mTotalFrameRateTimeAsASecond, that was a negative value. But except this sign of value was a negative, it is correct value. Meaning, it point time as look as good if I divide the final value with a framerate. A hypothetical play time was 500 sec, it is -30000(with 60 framerate per sec).


问:
Cannot start memcached
I cannot get memcached to run on my server.

This is what I tried so far:

```<code>% sudo systemctl start memcached # no output
% sudo systemctl status memcached.service
● memcached.service - memcached daemon
   Loaded: loaded (/lib/systemd/system/memcached.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sun 2020-02-16 17:45:09 CET; 4s ago
  Process: 22725 ExecStart=/usr/share/memcached/scripts/systemd-memcached-wrapper /etc/memcached.conf (code=exited, status=71)
 Main PID: 22725 (code=exited, status=71)

systemd[1]: Started memcached daemon.
systemd-memcached-wrapper[22725]: bind(): Cannot assign requested address
systemd-memcached-wrapper[22725]: failed to listen on TCP port 11211: Cannot assign requested address
systemd[1]: memcached.service: Main process exited, code=exited, status=71/n/a
systemd[1]: memcached.service: Unit entered failed state.
systemd[1]: memcached.service: Failed with result 'exit-code'.
</code>```

I am running Ubuntu 16.04.6 LTS

How can I start my memcached service?

答:
Have a look into /etc/memcached.conf there might be written sth. like
-l xxx.xx.xx.xx
If you are trying to connect via localhost: just comment the line.
If you are trying to connect from somewhere else check the IP for correctness.</p>

Title: Cannot start memcached

Body:
I cannot get memcached to run on my server.

This is what I tried so far:

% sudo systemctl start memcached # no output
% sudo systemctl status memcached.service
● memcached.service - memcached daemon
   Loaded: loaded (/lib/systemd/system/memcached.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sun 2020-02-16 17:45:09 CET; 4s ago
  Process: 22725 ExecStart=/usr/share/memcached/scripts/systemd-memcached-wrapper /etc/memcached.conf (code=exited, status=71)
 Main PID: 22725 (code=exited, status=71)

systemd[1]: Started memcached daemon.
systemd-memcached-wrapper[22725]: bind(): Cannot assign requested address
systemd-memcached-wrapper[22725]: failed to listen on TCP port 11211: Cannot assign requested address
systemd[1]: memcached.service: Main process exited, code=exited, status=71/n/a
systemd[1]: memcached.service: Unit entered failed state.
systemd[1]: memcached.service: Failed with result 'exit-code'.

I am running Ubuntu 16.04.6 LTS

How can I start my memcached service?


问:
Curl / php Empty response from PayPal IPN url
In the past couple of days, our PayPal IPN has stopped working and receiving a empty response from PayPal.  Nothing has changed on the server or in our code.

Attempting to cUrl to the PayPal IPN url simply returns an empty response.

```<code>$url = "https://www.paypal.com/cgi-bin/webscr?cmd=_notify-validate";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

$data = curl_exec($ch);
curl_close($ch);

print $data;
</code>```

The above should return "INVALID" and works as expected on my localhost and from other servers.
Changing the url to any other domain other then PayPal also works without issues.

So it seems it only received the empty response from paypal.com

I wonder if any one has run into the issue or could give pointers where to look in the hope to- resolve it?

Kind Regards
Musaffar

答:
It looks like Paypal made some security changes at the weekend. Some oscommerce users have been getting similar symptoms since Sunday with the curl error turning out to be:

SSL certificate problem: unable to get local issuer certificate

In their cases it was due to the local certificate copy only having the Paypal certificate and not the root or intermediate certificates, with the solution to update it.

The working certificate can be found in:
OSCOM Phoenix github

Body:
In the past couple of days, our PayPal IPN has stopped working and receiving a empty response from PayPal.  Nothing has changed on the server or in our code.

Attempting to cUrl to the PayPal IPN url simply returns an empty response.

$url = "https://www.paypal.com/cgi-bin/webscr?cmd=_notify-validate";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

$data = curl_exec($ch);
curl_close($ch);

print $data;

The above should return "INVALID" and works as expected on my localhost and from other servers.
Changing the url to any other domain other then PayPal also works without issues.

So it seems it only received the empty response from paypal.com

I wonder if any one has run into the issue or could give pointers where to look in the hope to- resolve it?

Kind Regards
Musaffar


问:
Canvas: Dividing Rectange in several sub-rectangles
This is a conceptual question, here it starts:

I am supposed to create, edit, save and resuse a CustomView which should be made of one parent Rectange and 12 inner-Rectanges/Polygons. I should be able to refer to each of them from code.

The easiest solution would be simple to draw 12 Rectangles, one next to each other, but it might be too heavy. What I was thinking about is to draw a huge Rectangle and divide it into parts (like for example polygons in GIS), but I did not find a single trace of such thing.

If anybody can suggest some light-weight concept I would be more than happy.

答: Back to the question -> at the end I have created every single erectangle separately, by extending RectF and modifyied a it a bit to get what I need. Since it is static and not having the performance issues I kept it.</p>


问:
How to restore deleted services to an aws ECS cluster?
I have accidentally deleted an AWS ECS cluster, because of which all the running services in side it are been terminated. Is there any way to restore them all?</p>

答: There is no way to restore deleted cluster. But you are still having all the task-definitions so you can recreate services using them.</p>


问:
Using case when clause in insert values
So I have this insert statement, and I need to check another table before setting the number1 & number2 columns. I've used the case when statement in the values part of the insert statement. Is there a better way of doing this without duplicating code when setting both of these columns.

```<code>INSERT INTO history (
    user_id
    ,number1
    ,number2
    )
VALUES (
    'user1'
    ,CASE
        WHEN (
                SELECT user_id
                FROM old_history
                WHERE user_id = 'user1'
                ) IS NOT NULL
            THEN 12.3
        ELSE NULL
        END
    ,CASE
        WHEN (
                SELECT user_id
                FROM old_history
                WHERE user_id = 'user1'
                ) IS NOT NULL
            THEN 15
        ELSE NULL
        END
    );
</code>```

Thanks.

答:
Aggregation functions conveniently return NULL when there is no match.  So, I think this is the simplest method:

```<code>INSERT INTO history (user_id, number1, number2)
    SELECT 'user1', MAX(12.3), MAX(15)
    FROM old_history
    WHERE user_id = 'user1';
</code>```

The use of aggregation functions MAX() makes this an aggregation query, which is guaranteed to return 1 row.  The second and third columns are NULL when there are no matching rows.

Title: Using case when clause in insert values

Body:
So I have this insert statement, and I need to check another table before setting the number1 & number2 columns. I've used the case when statement in the values part of the insert statement. Is there a better way of doing this without duplicating code when setting both of these columns.

INSERT INTO history (
    user_id
    ,number1
    ,number2
    )
VALUES (
    'user1'
    ,CASE
        WHEN (
                SELECT user_id
                FROM old_history
                WHERE user_id = 'user1'
                ) IS NOT NULL
            THEN 12.3
        ELSE NULL
        END
    ,CASE
        WHEN (
                SELECT user_id
                FROM old_history
                WHERE user_id = 'user1'
                ) IS NOT NULL
            THEN 15
        ELSE NULL
        END
    );

Thanks.

Body:
Aggregation functions conveniently return NULL when there is no match.  So, I think this is the simplest method:

INSERT INTO history (user_id, number1, number2)
    SELECT 'user1', MAX(12.3), MAX(15)
    FROM old_history
    WHERE user_id = 'user1';

The use of aggregation functions MAX() makes this an aggregation query, which is guaranteed to return 1 row.  The second and third columns are NULL when there are no matching rows.


问:
Why can't you store an extremely large single value in a dynamically allocated block of memory?
Why can't I store a large integer in this allocated block of memory?

```<code>int *dyn = malloc(16);
*dyn = 9999999999;

printf("%lli\n", *dyn);

free(dyn);
</code>```

At compile-time, GCC warns me that an integer overflow will occur. And sure enough, when printed out, it has overflowed.

Why can't I use the entire block of memory to store a single value?

答:
9999999999 or better illustrated as 9,999,999,999 is not in the range of an int, to which dyn is pointing to, don´t matter how much memory malloc has allocated:

```<code>int *dyn = malloc(16);   // `dyn` points to an `int` object, don´t matter
                         // if malloc allocates 16 bytes.
*dyn = 9999999999;       // Attempt to assign an out-of-range value to an `int` object.
</code>```

An object of type int shall be allocated by 4 Bytes in memory by the most modern systems.

4 Bytes can hold a maximum of 2^(8*4) = 2^32 = 4,294,967,296 values.

Now you have the type of int which is equivalent to the type of signed int.

signed int can store positive and negative numbers, but since it can store positive and negative numbers it has quite a different range.

signed int has the range of -2,147,483,648 to 2,147,483,647 and so is the range of int.

So you can not hold 9,999,999,999 in an int object because the maximum value an int object can store is the value of 2,147,483,647.

If you want to store the value of 9,999,999,999 or 9999999999 in an object, use f.e. long long int, but not long int since long int can hold the same range of an int and an unsigned int:

```<code>long long int *dyn = malloc(16);   // `dyn` points to an `long long int` object.
*dyn = 9999999999;  // Fine, because 9999999999 is in the range of an `long long int` object.
</code>```

Body:
Why can't I store a large integer in this allocated block of memory?

int *dyn = malloc(16);
*dyn = 9999999999;

printf("%lli\n", *dyn);

free(dyn);

At compile-time, GCC warns me that an integer overflow will occur. And sure enough, when printed out, it has overflowed.

Why can't I use the entire block of memory to store a single value?

Body:
9999999999 or better illustrated as 9,999,999,999 is not in the range of an int, to which dyn is pointing to, don´t matter how much memory malloc has allocated:

int *dyn = malloc(16);   // `dyn` points to an `int` object, don´t matter
                         // if malloc allocates 16 bytes.
*dyn = 9999999999;       // Attempt to assign an out-of-range value to an `int` object.

An object of type int shall be allocated by 4 Bytes in memory by the most modern systems.

4 Bytes can hold a maximum of 2^(8*4) = 2^32 = 4,294,967,296 values.

Now you have the type of int which is equivalent to the type of signed int.

signed int can store positive and negative numbers, but since it can store positive and negative numbers it has quite a different range.

signed int has the range of -2,147,483,648 to 2,147,483,647 and so is the range of int.

So you can not hold 9,999,999,999 in an int object because the maximum value an int object can store is the value of 2,147,483,647.

If you want to store the value of 9,999,999,999 or 9999999999 in an object, use f.e. long long int, but not long int since long int can hold the same range of an int and an unsigned int:

long long int *dyn = malloc(16);   // `dyn` points to an `long long int` object.
*dyn = 9999999999;  // Fine, because 9999999999 is in the range of an `long long int` object.


问:
VBA Excel row height to the last row
This is the query strongly related to this one:

Setting RowHeight Excel VBA

but when I modify it a bit (as I want the row height = 15 only).

```<code> Dim ws As Worksheet
 Set ws = ActiveSheet

 Dim Rng As Range
 Dim cel As Range
 Set Rng = Range(ActiveCell, Cells(Rows.Count, ActiveCell.Column).End(xlUp)) '& lastRow

 For Each cel In Rng
 cel.Rows.AutoFit
 cel.Rows.RowHeight = 15
Next cel
</code>```

I am getting the result in the place, where the cell has been clicked (active cell).

I tried to put the & lastRow straight after the .End(xlUp), but it didn't work, unfortunately.

The situation looks as follows:

Only the first 5 rows have been adjusted (where the cell was initially activated), but I need all of them down to the end. The value it's going to be flexible in the future.

How can I do that?

答:
Row height applies to the whole row so the column selected is irrelevant.

Also there's no need to loop.

```<code>Sub x()

Dim Rng As Range

Set Rng = Range("S1", Cells(Rows.Count, "S").End(xlUp))

rng.EntireRow.AutoFit
rng.EntireRow.RowHeight = 15

End Sub
</code>```

Title: VBA Excel row height to the last row

Body:
This is the query strongly related to this one:

Setting RowHeight Excel VBA

but when I modify it a bit (as I want the row height = 15 only).

 Dim ws As Worksheet
 Set ws = ActiveSheet

 Dim Rng As Range
 Dim cel As Range
 Set Rng = Range(ActiveCell, Cells(Rows.Count, ActiveCell.Column).End(xlUp)) '& lastRow

 For Each cel In Rng
 cel.Rows.AutoFit
 cel.Rows.RowHeight = 15
Next cel

I am getting the result in the place, where the cell has been clicked (active cell).

I tried to put the & lastRow straight after the .End(xlUp), but it didn't work, unfortunately.

The situation looks as follows:

Only the first 5 rows have been adjusted (where the cell was initially activated), but I need all of them down to the end. The value it's going to be flexible in the future.

How can I do that?

Body:
Row height applies to the whole row so the column selected is irrelevant.

Also there's no need to loop.

Sub x()

Dim Rng As Range

Set Rng = Range("S1", Cells(Rows.Count, "S").End(xlUp))

rng.EntireRow.AutoFit
rng.EntireRow.RowHeight = 15

End Sub


问:
Installing fresh react app with dockerfile
I'm trying to run a fresh installation of React using a Dockerfile.

```<code>FROM node:12.14-alpine

RUN mkdir /app
WORKDIR /app

RUN npm install -g nodemon \
    npx create-react-app .

COPY package.json package.json
RUN npm install --silent

COPY . .

CMD [ "node", "start" ]
</code>```

My root folder is empty so no package.json file exists etc. When I run docker-compose up --build I get the following error which indicates that's failing on npx create-react-app .

```<code>Step 5/9 : RUN npm install -g nodemon     npx create-react-app .
 ---> Running in c4878af5f94d
npm ERR! code ENOLOCAL
npm ERR! Could not install from "" as it does not contain a package.json file.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-02-18T12_55_14_899Z-debug.log
ERROR: Service 'react' failed to build: The command '/bin/sh -c npm install -g nodemon     npx create-react-app .' returned a non-zero code: 1
</code>```

Any ideas what I'm doing wrong? I'm not having node or npm installed natively so all needs t run through docker

答:
You need to delete the . at the end of the RUN :</p>

```<code>RUN npm install -g nodemon \
    npx \
    create-react-app
</code>```

Body:
I'm trying to run a fresh installation of React using a Dockerfile.

FROM node:12.14-alpine

RUN mkdir /app
WORKDIR /app

RUN npm install -g nodemon \
    npx create-react-app .

COPY package.json package.json
RUN npm install --silent

COPY . .

CMD [ "node", "start" ]

My root folder is empty so no package.json file exists etc. When I run docker-compose up --build I get the following error which indicates that's failing on npx create-react-app .

Step 5/9 : RUN npm install -g nodemon     npx create-react-app .
 ---> Running in c4878af5f94d
npm ERR! code ENOLOCAL
npm ERR! Could not install from "" as it does not contain a package.json file.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-02-18T12_55_14_899Z-debug.log
ERROR: Service 'react' failed to build: The command '/bin/sh -c npm install -g nodemon     npx create-react-app .' returned a non-zero code: 1

Any ideas what I'm doing wrong? I'm not having node or npm installed natively so all needs t run through docker

Body:
You need to delete the . at the end of the RUN :

RUN npm install -g nodemon \
    npx \
    create-react-app


问:
Teradata Database TeraJDBC 16.20.00.04 Error 3610 SQLState HY000 Internal error: Please do not resubmit the last request
Im requesting a report in the form of excel in my application. The application generates a report by running several(31) sql tasks, everytime i submit a request. But for a particular request the execution of 28th task doesnt complete and throws the below error.

[Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request.  SubCode, CrashCode:   0,  2693

```<code>01/28/2020 10:35:28,586 ERROR com.xxxx.yyyy.zz.Runner:generateBasicReport:174 - java.sql.SQLException: [Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request.  SubCode, CrashCode:   0,  2693

com.xxxx.yyyy.zz.exception.ReportGenerationException: java.sql.SQLException: [Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request.  SubCode, CrashCode:   0,  2693
    at com.xxxx.yyyy.zz.generator.task.CancellableSqlTask.execute(CancellableSqlTask.java:79)
    at com.xxxx.yyyy.zz.generator.task.TaskExecutor.executeNext(TaskExecutor.java:56)
    at com.xxxx.yyyy.zz.generator.ReportGenerator.executeTasks(ReportGenerator.java:119)
    at com.xxxx.yyyy.zz.generator.ReportGenerator.execute(ReportGenerator.java:83)
    at com.xxxx.yyyy.zz.generator.task.CompositeCancellableTask.execute(CompositeCancellableTask.java:32)
    at com.xxxx.yyyy.zz.Runner.executeGeneration(Runner.java:209)
    at com.xxxx.yyyy.zz.Runner.generateBasicReport(Runner.java:171)
    at com.xxxx.yyyy.zz.Runner.generateReports(Runner.java:137)
    at com.xxxx.yyyy.zz.Runner.startReportGenerator(Runner.java:92)
    at com.xxxx.yyyy.zz.Runner.main(Runner.java:69)
Caused by: java.sql.SQLException: [Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request.  SubCode, CrashCode:   0,  2693
    at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDatabaseSQLException(ErrorFactory.java:309)
    at com.teradata.jdbc.jdbc_4.statemachine.ReceiveInitSubState.action(ReceiveInitSubState.java:103)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.subStateMachine(StatementReceiveState.java:311)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.action(StatementReceiveState.java:200)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementController.runBody(StatementController.java:137)
    at com.teradata.jdbc.jdbc_4.statemachine.PreparedStatementController.run(PreparedStatementController.java:46)
    at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:389)
    at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:331)
    at com.teradata.jdbc.jdbc_4.TDPreparedStatement.doPrepExecuteUpdate(TDPreparedStatement.java:225)
    at com.teradata.jdbc.jdbc_4.TDPreparedStatement.executeUpdate(TDPreparedStatement.java:2769)
    at com.xxxx.yyyy.zz.generator.task.CancellableUpdate.perform(CancellableUpdate.java:36)
    at com.xxxx.yyyy.zz.generator.task.CancellableSqlTask.execute(CancellableSqlTask.java:74)
    ... 9 more
</code>```

答:
That means that the request caused some exception that Teradata couldn't handle, and like the message says, "don't re-submit".  You could try digging into the logs, but I don't know how fruitful that will be.  I think they are somewhere in /var/opt/teradata/.  Otherwise, you'd have to check with customer support to debug.

From the documentation:

```<code>2693 The fieldids in field 5 are not contiguous.

Explanation: The field descriptors in field 5 should be contiguous, they are not.
Generated By: FldLocat.
For Whom: Site support representative.
Notes: This is caused by an incorrect field 5 header.
Remedy: Contact your Support Representative.
</code>```

Body:
Im requesting a report in the form of excel in my application. The application generates a report by running several(31) sql tasks, everytime i submit a request. But for a particular request the execution of 28th task doesnt complete and throws the below error.

[Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request.  SubCode, CrashCode:   0,  2693

01/28/2020 10:35:28,586 ERROR com.xxxx.yyyy.zz.Runner:generateBasicReport:174 - java.sql.SQLException: [Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request.  SubCode, CrashCode:   0,  2693

com.xxxx.yyyy.zz.exception.ReportGenerationException: java.sql.SQLException: [Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request.  SubCode, CrashCode:   0,  2693
    at com.xxxx.yyyy.zz.generator.task.CancellableSqlTask.execute(CancellableSqlTask.java:79)
    at com.xxxx.yyyy.zz.generator.task.TaskExecutor.executeNext(TaskExecutor.java:56)
    at com.xxxx.yyyy.zz.generator.ReportGenerator.executeTasks(ReportGenerator.java:119)
    at com.xxxx.yyyy.zz.generator.ReportGenerator.execute(ReportGenerator.java:83)
    at com.xxxx.yyyy.zz.generator.task.CompositeCancellableTask.execute(CompositeCancellableTask.java:32)
    at com.xxxx.yyyy.zz.Runner.executeGeneration(Runner.java:209)
    at com.xxxx.yyyy.zz.Runner.generateBasicReport(Runner.java:171)
    at com.xxxx.yyyy.zz.Runner.generateReports(Runner.java:137)
    at com.xxxx.yyyy.zz.Runner.startReportGenerator(Runner.java:92)
    at com.xxxx.yyyy.zz.Runner.main(Runner.java:69)
Caused by: java.sql.SQLException: [Teradata Database] [TeraJDBC 16.20.00.04] [Error 3610] [SQLState HY000] Internal error: Please do not resubmit the last request.  SubCode, CrashCode:   0,  2693
    at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDatabaseSQLException(ErrorFactory.java:309)
    at com.teradata.jdbc.jdbc_4.statemachine.ReceiveInitSubState.action(ReceiveInitSubState.java:103)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.subStateMachine(StatementReceiveState.java:311)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.action(StatementReceiveState.java:200)
    at com.teradata.jdbc.jdbc_4.statemachine.StatementController.runBody(StatementController.java:137)
    at com.teradata.jdbc.jdbc_4.statemachine.PreparedStatementController.run(PreparedStatementController.java:46)
    at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:389)
    at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:331)
    at com.teradata.jdbc.jdbc_4.TDPreparedStatement.doPrepExecuteUpdate(TDPreparedStatement.java:225)
    at com.teradata.jdbc.jdbc_4.TDPreparedStatement.executeUpdate(TDPreparedStatement.java:2769)
    at com.xxxx.yyyy.zz.generator.task.CancellableUpdate.perform(CancellableUpdate.java:36)
    at com.xxxx.yyyy.zz.generator.task.CancellableSqlTask.execute(CancellableSqlTask.java:74)
    ... 9 more

Body:
That means that the request caused some exception that Teradata couldn't handle, and like the message says, "don't re-submit".  You could try digging into the logs, but I don't know how fruitful that will be.  I think they are somewhere in /var/opt/teradata/.  Otherwise, you'd have to check with customer support to debug.

From the documentation:

2693 The fieldids in field 5 are not contiguous.

Explanation: The field descriptors in field 5 should be contiguous, they are not.
Generated By: FldLocat.
For Whom: Site support representative.
Notes: This is caused by an incorrect field 5 header.
Remedy: Contact your Support Representative.


问:
grails BIRT plugin deployment problem in linux
I integrate the BIRT plugin in my application. in the development environment (windows) it works fine. but my deployment is on a Linux server. i getting the application startup error about the engine initialization -  i trying to configure the path in a config properties file but it is still not working - do you have the experience in this deployment i'll be happy for you help.

Meni

答:
Try to put the file birt-runtime-2_5_0.zip in /home/your_User/.grails/1.3.7/download
and run:

```<code>install-plugin birt_plugin
</code>```

It's very important to run all these steps with root privileges......

ContentLicense: CC BY-SA 2.5

Body:
Try to put the file birt-runtime-2_5_0.zip in /home/your_User/.grails/1.3.7/download
and run:

install-plugin birt_plugin

It's very important to run all these steps with root privileges......


问:
Messed up fields when passing csv files to elastic+kibana
I'm trying to pass csv files to elastic using the logstash plugin via HTTP.
When I look at what I have in the database I see that the fields have been messed up, the csv file is correct.
Also another thing I see is that along with the data for each entry I also get http headers, I'd prefer not to have them but anyway I could live with them. Could they be the cause of the problem?

I copy the first line of the csv file and what I get in elastic.

```<code>Job, BuildId, Start time, Stop time, Execution time, Queue time, Executor, Result, Parent, User
DpiTools_Admin_CleaningEselnlx_v0.1.0, 32449, 2020-02-18T01:12:010100, 2020-02-18T01:12:020100, 1.144, 0.096, eselnlx2475-Admin., SUCCESS., DpiTools_Admin_CleaningEselnlx_v0.1.0, None
</code>```

Then What I get in elastiv as seen in kibana is:

```<code>Result: None Executor: DpiTools_Admin_CleaningEselnlx_v0.1.0 Stop_time: 0.236 @version:1 @timestamp:February 18th 2020, 11:17:53.455 BuildId: 32449 Execution_time: eselnlx2578-Admin. Stop_date: 0.100 Start_time: 2020-02-18T01:12:010100 Start_date: 2020-02-18T01:12:010100 headers.http_host:127.0.0.1:5044 headers.request_path:/ headers.http_version:HTTP/1.1 headers.connection:Keep-Alive headers.request_method:PUT headers.http_user_agent:Mozilla/5.0 (Windows NT; Windows NT 10.0; es-ES) WindowsPowerShell/5.1.17763.771 headers.content_length:3166 headers.http_accept: - Job:label=eselnlx2578-Admin message:label=eselnlx2578-Admin, 32449, 2020-02-18T01:12:010100, 2020-02-18T01:12:010100, 0.100, 0.236, eselnlx2578-Admin., SUCCESS., DpiTools_Admin_CleaningEselnlx_v0.1.0, None Queue_time: SUCCESS. host:172.19.0.1 _id:z0bNV3ABGO94josV3Kjr _type:doc _index:job-executions _score:1
</code>```

答: Solved, I forgot I had the csv headers in the configuration, from a previoues version u had date and time in two fields and now they are in the same one, that's why all got messed up.</p>

Body:
I'm trying to pass csv files to elastic using the logstash plugin via HTTP.
When I look at what I have in the database I see that the fields have been messed up, the csv file is correct.
Also another thing I see is that along with the data for each entry I also get http headers, I'd prefer not to have them but anyway I could live with them. Could they be the cause of the problem?

I copy the first line of the csv file and what I get in elastic.

Job, BuildId, Start time, Stop time, Execution time, Queue time, Executor, Result, Parent, User
DpiTools_Admin_CleaningEselnlx_v0.1.0, 32449, 2020-02-18T01:12:010100, 2020-02-18T01:12:020100, 1.144, 0.096, eselnlx2475-Admin., SUCCESS., DpiTools_Admin_CleaningEselnlx_v0.1.0, None

Then What I get in elastiv as seen in kibana is:

Result: None Executor: DpiTools_Admin_CleaningEselnlx_v0.1.0 Stop_time: 0.236 @version:1 @timestamp:February 18th 2020, 11:17:53.455 BuildId: 32449 Execution_time: eselnlx2578-Admin. Stop_date: 0.100 Start_time: 2020-02-18T01:12:010100 Start_date: 2020-02-18T01:12:010100 headers.http_host:127.0.0.1:5044 headers.request_path:/ headers.http_version:HTTP/1.1 headers.connection:Keep-Alive headers.request_method:PUT headers.http_user_agent:Mozilla/5.0 (Windows NT; Windows NT 10.0; es-ES) WindowsPowerShell/5.1.17763.771 headers.content_length:3166 headers.http_accept: - Job:label=eselnlx2578-Admin message:label=eselnlx2578-Admin, 32449, 2020-02-18T01:12:010100, 2020-02-18T01:12:010100, 0.100, 0.236, eselnlx2578-Admin., SUCCESS., DpiTools_Admin_CleaningEselnlx_v0.1.0, None Queue_time: SUCCESS. host:172.19.0.1 _id:z0bNV3ABGO94josV3Kjr _type:doc _index:job-executions _score:1