问:
How do I tie this program that validates passwords together? I keep getting error messages and when I fix those errors, more pop up
All I need is for this program to check both inputs and print either, "The passwords do not match", "The password is not valid", or "The password is valid"

/**
This program asks for a password, then asks again to confirm it.

If the passwords don't match or the rules are not fulfilled, prompt again.

-The password must be at least 8 characters long.

-The password must have at least one uppercase and one lower letter.

-The password must have at least one digit.

*/

```<code>import java.util.Scanner;
public class PasswordCheck {

    public static void main(String[] args) {

        do {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a password:");
        String pass1 = in.nextLine();
        System.out.println("Confirm password:");
        String pass2 = in.nextLine();

        if(samePassword(pass1,pass2)) {
        }
        else {
            System.out.println("The passwords do not match");
        }

        if(validate(pass1)) {
            System.out.println("The password is valid");
        }
        else {
            System.out.println("The password is not valid");
        }
        while(validate == false);
    }
    /**
            Checks if both passwords are the same
            @param password and confirmation password
            @return true or false
        */
    public static boolean samePassword(String password, String confPassword) {

        boolean isSame = password.equals(confPassword);

        if(isSame == true) {
            return true;
        }
        else {
            return false;
        }
    }
    /**
            Checks if the password is valid.
            It uses isDigit(), isLowerCase(), and isUpperCase() helper methods.
            @param the password
            @return true or false
        */
    public static boolean validate(String password) {

        String thePassword = password;

        for(int i = 0; i < thePassword.length(); i++) {

            if(i >= 8) {
                if(isDigit(thePassword.charAt(i)) == true)
                    if(isLowerCase(thePassword.charAt(i)) == true)
                        if(isUpperCase(thePassword.charAt(i)) == true)
                            return true;
            }
            else {
                return false;
            }
        }
    }
    /**
            Checks if the character is a digit (0 to 9).
            @param a character.
            @return true or false.
        */
    public static boolean isDigit(char ch) {

        char aCharacter = ch;
        if(aCharacter >= 0 && aCharacter <= 9) {
            return true;
        }
        else {
            return false;
        }
    }
    /**
            Checks if the character is lower case(a to z).
            @param a character.
            @return true or false.
        */
    public static boolean isLowerCase(char ch) {

        char aCharacter = ch;
        if(Character.isLowerCase(aCharacter)) {
            return true;
        }
        else {
            return false;
        }
    }
    /**
            Checks if the character is uppercase (A to Z).
            @param a character.
            @return true or false
        */
    public static boolean isUpperCase(char ch) {

        char aCharacter = ch;
        if(Character.isUpperCase(aCharacter)) {
            return true;
        }
        else {
            return false;
        }
    }
}
</code>```

答:
Formatted the code & fixed some typos and commented where ever needed. Please test it now.

```<code>import java.util.Scanner;

public class PasswordCheck {
    /**
     * Checks if both passwords are the same
     *
     * @param password and confirmation password
     * @return true or false
     */
    public static boolean samePassword(String password, String confPassword) {

        boolean isSame = password.equals(confPassword);

        if (isSame == true) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Checks if the password is valid.
     * It uses isDigit(), isLowerCase(), and isUpperCase() helper methods.
     *
     * @param password
     * @return true or false
     */
    public static boolean validate(final String password) {

        boolean hasDigit = false, hasUppercase = false, hasLowercase = false;
        /*for (int i = 0; i < thePassword.length(); i++) {

            if (i >= 8) {
                if (isDigit(thePassword.charAt(i)) == true)
                    if (isLowerCase(thePassword.charAt(i)) == true)
                        if (isUpperCase(thePassword.charAt(i)) == true)
                            return true;
            } else {
                return false;
            }

        }*/
        for (Character ch : password.toCharArray())
            if (isDigit(ch))
                hasDigit = true;
            else if (isLowerCase(ch))
                hasLowercase = true;
            else if (isUpperCase(ch))
                hasUppercase = true;
        return hasDigit && hasLowercase && hasUppercase;
    }

    /**
     * Checks if the character is a digit (0 to 9).
     *
     * @param ch character.
     * @return true or false.
     */
    public static boolean isDigit(char ch) {

//        char aCharacter = ch;
//        if (aCharacter >= 0 && aCharacter <= 9) {
//            return true;
//        } else {
//            return false;
//        }
        return Character.isDigit(ch);
    }

    /**
     * Checks if the character is lower case(a to z).
     *
     * @param ch character.
     * @return true or false.
     */
    public static boolean isLowerCase(char ch) {

//        char aCharacter = ch;
//        if (Character.isLowerCase(aCharacter)) {
//            return true;
//        } else {
//            return false;
//        }
        return Character.isLowerCase(ch);
    }

    /**
     * Checks if the character is uppercase (A to Z).
     *
     * @param ch character.
     * @return true or false
     */
    public static boolean isUpperCase(char ch) {

//        char aCharacter = ch;
//        if (Character.isUpperCase(aCharacter)) {
//            return true;
//        } else {
//            return false;
//        }
        return Character.isUpperCase(ch);
    }

    ////////////Main////////////
    public static void main(String[] args) {
        var out = System.out;
        boolean validPassword = false;
        do {
            Scanner in = new Scanner(System.in);
            out.println("Enter a password:");
            String pass1 = in.nextLine();
            out.println("Confirm password:");
            String pass2 = in.nextLine();
            out.println(pass1 + " " + pass2);

            if (samePassword(pass1, pass2)) {
            } else {
                System.out.println("The passwords do not match");
            }

            if (validate(pass1)) {
                System.out.println("The password is valid");
            } else {
                System.out.println("The password is not valid");
            }
            //validating password
            validPassword = validate(pass1) && samePassword(pass1, pass2);
        } while (!validPassword);//while password is invlaid keep

    }
}
</code>```

Output:

```<code>Enter a password:
blabla@123
Confirm password:
blabla@123
blabla@123 blabla@123
The password is not valid
Enter a password:
Blabla@123
Confirm password:
Blabla@123
Blabla@123 Blabla@123
The password is valid
</code>```

Body:
All I need is for this program to check both inputs and print either, "The passwords do not match", "The password is not valid", or "The password is valid"

/**
This program asks for a password, then asks again to confirm it.

If the passwords don't match or the rules are not fulfilled, prompt again.

-The password must be at least 8 characters long.

-The password must have at least one uppercase and one lower letter.

-The password must have at least one digit.

*/

import java.util.Scanner;
public class PasswordCheck {

    public static void main(String[] args) {

        do {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a password:");
        String pass1 = in.nextLine();
        System.out.println("Confirm password:");
        String pass2 = in.nextLine();

        if(samePassword(pass1,pass2)) {
        }
        else {
            System.out.println("The passwords do not match");
        }

        if(validate(pass1)) {
            System.out.println("The password is valid");
        }
        else {
            System.out.println("The password is not valid");
        }
        while(validate == false);
    }
    /**
            Checks if both passwords are the same
            @param password and confirmation password
            @return true or false
        */
    public static boolean samePassword(String password, String confPassword) {

        boolean isSame = password.equals(confPassword);

        if(isSame == true) {
            return true;
        }
        else {
            return false;
        }
    }
    /**
            Checks if the password is valid.
            It uses isDigit(), isLowerCase(), and isUpperCase() helper methods.
            @param the password
            @return true or false
        */
    public static boolean validate(String password) {

        String thePassword = password;

        for(int i = 0; i < thePassword.length(); i++) {

            if(i >= 8) {
                if(isDigit(thePassword.charAt(i)) == true)
                    if(isLowerCase(thePassword.charAt(i)) == true)
                        if(isUpperCase(thePassword.charAt(i)) == true)
                            return true;
            }
            else {
                return false;
            }
        }
    }
    /**
            Checks if the character is a digit (0 to 9).
            @param a character.
            @return true or false.
        */
    public static boolean isDigit(char ch) {

        char aCharacter = ch;
        if(aCharacter >= 0 && aCharacter <= 9) {
            return true;
        }
        else {
            return false;
        }
    }
    /**
            Checks if the character is lower case(a to z).
            @param a character.
            @return true or false.
        */
    public static boolean isLowerCase(char ch) {

        char aCharacter = ch;
        if(Character.isLowerCase(aCharacter)) {
            return true;
        }
        else {
            return false;
        }
    }
    /**
            Checks if the character is uppercase (A to Z).
            @param a character.
            @return true or false
        */
    public static boolean isUpperCase(char ch) {

        char aCharacter = ch;
        if(Character.isUpperCase(aCharacter)) {
            return true;
        }
        else {
            return false;
        }
    }
}

Body:
Formatted the code & fixed some typos and commented where ever needed. Please test it now.

import java.util.Scanner;

public class PasswordCheck {
    /**
     * Checks if both passwords are the same
     *
     * @param password and confirmation password
     * @return true or false
     */
    public static boolean samePassword(String password, String confPassword) {

        boolean isSame = password.equals(confPassword);

        if (isSame == true) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Checks if the password is valid.
     * It uses isDigit(), isLowerCase(), and isUpperCase() helper methods.
     *
     * @param password
     * @return true or false
     */
    public static boolean validate(final String password) {

        boolean hasDigit = false, hasUppercase = false, hasLowercase = false;
        /*for (int i = 0; i < thePassword.length(); i++) {

            if (i >= 8) {
                if (isDigit(thePassword.charAt(i)) == true)
                    if (isLowerCase(thePassword.charAt(i)) == true)
                        if (isUpperCase(thePassword.charAt(i)) == true)
                            return true;
            } else {
                return false;
            }

        }*/
        for (Character ch : password.toCharArray())
            if (isDigit(ch))
                hasDigit = true;
            else if (isLowerCase(ch))
                hasLowercase = true;
            else if (isUpperCase(ch))
                hasUppercase = true;
        return hasDigit && hasLowercase && hasUppercase;
    }

    /**
     * Checks if the character is a digit (0 to 9).
     *
     * @param ch character.
     * @return true or false.
     */
    public static boolean isDigit(char ch) {

//        char aCharacter = ch;
//        if (aCharacter >= 0 && aCharacter <= 9) {
//            return true;
//        } else {
//            return false;
//        }
        return Character.isDigit(ch);
    }

    /**
     * Checks if the character is lower case(a to z).
     *
     * @param ch character.
     * @return true or false.
     */
    public static boolean isLowerCase(char ch) {

//        char aCharacter = ch;
//        if (Character.isLowerCase(aCharacter)) {
//            return true;
//        } else {
//            return false;
//        }
        return Character.isLowerCase(ch);
    }

    /**
     * Checks if the character is uppercase (A to Z).
     *
     * @param ch character.
     * @return true or false
     */
    public static boolean isUpperCase(char ch) {

//        char aCharacter = ch;
//        if (Character.isUpperCase(aCharacter)) {
//            return true;
//        } else {
//            return false;
//        }
        return Character.isUpperCase(ch);
    }

    ////////////Main////////////
    public static void main(String[] args) {
        var out = System.out;
        boolean validPassword = false;
        do {
            Scanner in = new Scanner(System.in);
            out.println("Enter a password:");
            String pass1 = in.nextLine();
            out.println("Confirm password:");
            String pass2 = in.nextLine();
            out.println(pass1 + " " + pass2);

            if (samePassword(pass1, pass2)) {
            } else {
                System.out.println("The passwords do not match");
            }

            if (validate(pass1)) {
                System.out.println("The password is valid");
            } else {
                System.out.println("The password is not valid");
            }
            //validating password
            validPassword = validate(pass1) && samePassword(pass1, pass2);
        } while (!validPassword);//while password is invlaid keep

    }
}

Output:

Enter a password:
blabla@123
Confirm password:
blabla@123
blabla@123 blabla@123
The password is not valid
Enter a password:
Blabla@123
Confirm password:
Blabla@123
Blabla@123 Blabla@123
The password is valid


来源: stackexchange

问:
For TestCafe, is it possible to get a hook before the browser is launched?
Is it possible to get a hook on e.g. fixture before the browser is launched? The hooks on fixture (e.g. before) and test all happen after the browser is launched.

The only thing I can see to use is the --app switch but I'm not sure that's enough for me. Any help appreciated.

m

答:
Could you please describe why you need this usage scenario?
Currently, there is no way to run the fixture hooks before the browser is launched. As a workaround, you can use the `createTestCafe function to run TestCafe tests from script. In this script, you can run any JS code you want before the tests start.
Please refer to the following article for details:
https://testcafe.io/documentation/402662/reference/testcafe-api/global/createtestcafe</p>

ContentLicense: CC BY-SA 4.0


问:
FlatList calls `onEndReached` when it's rendered
Here is render() function for my simple category list page.

Recently I added pagination for my FlatList View so when the user scrolls to the bottom, onEndReached is called in a certain point(onEndReachedThreshold value length from the bottom), and it will fetch the next categories and concatenate the categories props.

But my problem is onEndReached is called when render() is called In other words, FlatList's onEndReached is triggered before it reach the bottom.

Am I putting wrong value for onEndReachedThreshold? Do you see any problem?

```<code>return (
  <View style={{ flex:1 }}>
    <FlatList
      data={this.props.categories}
      renderItem={this._renderItem}
      keyExtractor={this._keyExtractor}
      numColumns={2}
      style={{flex: 1, flexDirection: 'row'}}
      contentContainerStyle={{justifyContent: 'center'}}
      refreshControl={
        <RefreshControl
          refreshing = {this.state.refreshing}
          onRefresh = {()=>this._onRefresh()}
        />
      }
      // curent value for debug is 0.5
      onEndReachedThreshold={0.5} // Tried 0, 0.01, 0.1, 0.7, 50, 100, 700

      onEndReached = {({distanceFromEnd})=>{ // problem
        console.log(distanceFromEnd) // 607, 878
        console.log('reached'); // once, and if I scroll about 14% of the screen,
                             //it prints reached AGAIN.
        this._onEndReachedThreshold()
      }}
    />
  </View>
)
</code>```

UPDATE I fetch this.props.categories data here

```<code>  componentWillMount() {
    if(this.props.token) {
      this.props.loadCategoryAll(this.props.token);
    }
  }
</code>```

答:
From my experience, you can simply utilize onEndReachedThreshold props in your FlatList or SectionList and pass a very very small number like 0.001 to it.

```<code>onEndReachedThreshold={0.001}
</code>```

According to docs for FlatList, onEndReachedThreshold is units of length from the bottom in list items.

How far from the end (in units of visible length of the list) the
bottom edge of the list must be from the end of the content to trigger
the onEndReached callback. For example, a value of 0.5 will trigger
onEndReached when the end of the content is within half the visible
length of the list.

Thus, a very small value like 0.001 helps you to make sure that onEndReached is only gonna be called when the end of the content is within the very end of the visible length of the list.

Hope this helps :) Sorry for bad English.

Body:
Here is render() function for my simple category list page.

Recently I added pagination for my FlatList View so when the user scrolls to the bottom, onEndReached is called in a certain point(onEndReachedThreshold value length from the bottom), and it will fetch the next categories and concatenate the categories props.

But my problem is onEndReached is called when render() is called In other words, FlatList's onEndReached is triggered before it reach the bottom.

Am I putting wrong value for onEndReachedThreshold? Do you see any problem?

return (
  <View style={{ flex:1 }}>
    <FlatList
      data={this.props.categories}
      renderItem={this._renderItem}
      keyExtractor={this._keyExtractor}
      numColumns={2}
      style={{flex: 1, flexDirection: 'row'}}
      contentContainerStyle={{justifyContent: 'center'}}
      refreshControl={
        <RefreshControl
          refreshing = {this.state.refreshing}
          onRefresh = {()=>this._onRefresh()}
        />
      }
      // curent value for debug is 0.5
      onEndReachedThreshold={0.5} // Tried 0, 0.01, 0.1, 0.7, 50, 100, 700

      onEndReached = {({distanceFromEnd})=>{ // problem
        console.log(distanceFromEnd) // 607, 878
        console.log('reached'); // once, and if I scroll about 14% of the screen,
                             //it prints reached AGAIN.
        this._onEndReachedThreshold()
      }}
    />
  </View>
)

UPDATE I fetch this.props.categories data here

  componentWillMount() {
    if(this.props.token) {
      this.props.loadCategoryAll(this.props.token);
    }
  }

Body:
From my experience, you can simply utilize onEndReachedThreshold props in your FlatList or SectionList and pass a very very small number like 0.001 to it.

onEndReachedThreshold={0.001}

According to docs for FlatList, onEndReachedThreshold is units of length from the bottom in list items.

How far from the end (in units of visible length of the list) the
bottom edge of the list must be from the end of the content to trigger
the onEndReached callback. For example, a value of 0.5 will trigger
onEndReached when the end of the content is within half the visible
length of the list.

Thus, a very small value like 0.001 helps you to make sure that onEndReached is only gonna be called when the end of the content is within the very end of the visible length of the list.

Hope this helps :) Sorry for bad English.


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答: What you can do is sort each individual file. e.g. the UNIX sort or similar in Java.  You can read the sorted files one line at a time to perform a merge sort.

ContentLicense: CC BY-SA 3.0

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!


问:
Split log message on space for grok pattern
I am two days new to grok and ELK.
I am struggling with breaking up the log messages based on space and make them appear as different fields in the logstash.

My input pattern is:
2022-02-11 11:57:49 - app - INFO - function_name=add elapsed_time=0.0296 input_params=6_3

I would like to see different fields in the logstash/kibana for function_name, elapsed_time and input_params.

At the moment, I have a following .conf

```<code>input{
  file{
  path => "/path/to/log/file"
  start_position => "beginning"
  }
}
filter{
  grok{
  match => {"message" => "%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:log-level} %{(?<function_name>[^.]*)\.(?<elapsed_time>[^.]*)\.(?<input>[^.]*)}"}
  }
    date {
    match => ["timestamp", "ISO8601"]
    }
    function_name {
    match => ["function_name", "DATA"]
    }
    elapsed_time {
    match => ["elapsed_time", "BASE16FLOAT"]
    }
    input {
    match => ["input", "DATA"]
    }
}
output{
  elasticsearch{
  hosts => ["localhost:9200"]
  index => "math_apis"
  }
  stdout{codec => rubydebug}
}
</code>```

But this only produces a following message in logstash

```<code>{
          "host" => "hostname",
    "@timestamp" => 2022-02-11T06:27:49.404Z,
       "message" => "2022-02-11 11:57:49 - app - INFO - function_name=add elapsed_time=0.0296 input_params=6_3",
          "path" => "path/to/log/file",
      "@version" => "1",
          "tags" => [
        [0] "_grokparsefailure"
    ]
}
</code>```

答:
You can use the following pattern:

%{TIMESTAMP_ISO8601:timestamp} - \S+ - %{LOGLEVEL:log_level} - function_name=%{NOTSPACE:function_name} elapsed_time=%{NOTSPACE:elapsed_time} input_params=%{NOTSPACE:input}
```
<p><em>Details</em>:</p>
<ul>
<li><code>%{TIMESTAMP_ISO8601:timestamp}</code> - <code>timestamp</code> field</li>
<li><code>-</code> - a literal string</li>
<li><code>\S+</code> - any one or more non-whitespace chars</li>
<li><code>-</code> - a literal string</li>
<li><code>%{LOGLEVEL:log_level}</code> - <code>LOGLEVEL</code> pattern</li>
<li><code> - function_name=</code> - a literal string</li>
<li><code>%{NOTSPACE:function_name}</code> - <code>function_name</code> field of one or more non-whitespace chars</li>
<li><code> elapsed_time=</code> - space and <code>elapsed_time=</code> string</li>
<li><code>%{NOTSPACE:elapsed_time}</code> - <code>elapsed_time</code> field of one or more non-whitespace chars</li>
<li><code> input_params=</code> - literal string</li>
<li><code>%{NOTSPACE:input}</code> - <code>input</code> field of one or more non-whitespace chars.</li>
</ul>
<p>See more about Grok patterns here.</p>
<p>Test output:</p>
<pre class="lang-none prettyprint-override"><code>{
  "timestamp": [
    [
      "2022-02-11 11:57:49"
    ]
  ],
  "YEAR": [
    [
      "2022"
    ]
  ],
  "MONTHNUM": [
    [
      "02"
    ]
  ],
  "MONTHDAY": [
    [
      "11"
    ]
  ],
  "HOUR": [
    [
      "11",
      null
    ]
  ],
  "MINUTE": [
    [
      "57",
      null
    ]
  ],
  "SECOND": [
    [
      "49"
    ]
  ],
  "ISO8601_TIMEZONE": [
    [
      null
    ]
  ],
  "log_level": [
    [
      "INFO"
    ]
  ],
  "function_name": [
    [
      "add"
    ]
  ],
  "elapsed_time": [
    [
      "0.0296"
    ]
  ],
  "input": [
    [
      "6_3"
    ]
  ]
}
</code>```

Body:
I am two days new to grok and ELK.
I am struggling with breaking up the log messages based on space and make them appear as different fields in the logstash.

My input pattern is:
2022-02-11 11:57:49 - app - INFO - function_name=add elapsed_time=0.0296 input_params=6_3

I would like to see different fields in the logstash/kibana for function_name, elapsed_time and input_params.

At the moment, I have a following .conf

input{
  file{
  path => "/path/to/log/file"
  start_position => "beginning"
  }
}
filter{
  grok{
  match => {"message" => "%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:log-level} %{(?<function_name>[^.]*)\.(?<elapsed_time>[^.]*)\.(?<input>[^.]*)}"}
  }
    date {
    match => ["timestamp", "ISO8601"]
    }
    function_name {
    match => ["function_name", "DATA"]
    }
    elapsed_time {
    match => ["elapsed_time", "BASE16FLOAT"]
    }
    input {
    match => ["input", "DATA"]
    }
}
output{
  elasticsearch{
  hosts => ["localhost:9200"]
  index => "math_apis"
  }
  stdout{codec => rubydebug}
}

But this only produces a following message in logstash

{
          "host" => "hostname",
    "@timestamp" => 2022-02-11T06:27:49.404Z,
       "message" => "2022-02-11 11:57:49 - app - INFO - function_name=add elapsed_time=0.0296 input_params=6_3",
          "path" => "path/to/log/file",
      "@version" => "1",
          "tags" => [
        [0] "_grokparsefailure"
    ]
}

Body:
You can use the following pattern:

%{TIMESTAMP_ISO8601:timestamp} - \S+ - %{LOGLEVEL:log_level} - function_name=%{NOTSPACE:function_name} elapsed_time=%{NOTSPACE:elapsed_time} input_params=%{NOTSPACE:input}

Details:

%{TIMESTAMP_ISO8601:timestamp} - timestamp field

- - a literal string

\S+ - any one or more non-whitespace chars

- - a literal string

%{LOGLEVEL:log_level} - LOGLEVEL pattern

 - function_name= - a literal string

%{NOTSPACE:function_name} - function_name field of one or more non-whitespace chars

 elapsed_time= - space and elapsed_time= string

%{NOTSPACE:elapsed_time} - elapsed_time field of one or more non-whitespace chars

 input_params= - literal string

%{NOTSPACE:input} - input field of one or more non-whitespace chars.

See more about Grok patterns here.

Test output:

{
  "timestamp": [
    [
      "2022-02-11 11:57:49"
    ]
  ],
  "YEAR": [
    [
      "2022"
    ]
  ],
  "MONTHNUM": [
    [
      "02"
    ]
  ],
  "MONTHDAY": [
    [
      "11"
    ]
  ],
  "HOUR": [
    [
      "11",
      null
    ]
  ],
  "MINUTE": [
    [
      "57",
      null
    ]
  ],
  "SECOND": [
    [
      "49"
    ]
  ],
  "ISO8601_TIMEZONE": [
    [
      null
    ]
  ],
  "log_level": [
    [
      "INFO"
    ]
  ],
  "function_name": [
    [
      "add"
    ]
  ],
  "elapsed_time": [
    [
      "0.0296"
    ]
  ],
  "input": [
    [
      "6_3"
    ]
  ]
}


问:
C++ bit shift operators not working with pointer; showing 'statement has no effect'
```<code>*data << 1;
</code>```

I am trying to bit shift the value pointed to by the pointer (uint8_t type). But, when I build the project it is throwing the warning 'statement has no effect'.

How do I resolve this? Or can I ignore this?

(Also, my build process is failing, but I think it's probably due to something else.)

P.S. I am working on an embedded systems project.

答:
One usually gets "statement has no effect" warnings when writing null statements with no side effects. For example:

```<code>*data << 1;
</code>```

Perhaps you meant to do this?

```<code>*data <<= 1;
</code>```

Body:
*data << 1;

I am trying to bit shift the value pointed to by the pointer (uint8_t type). But, when I build the project it is throwing the warning 'statement has no effect'.

How do I resolve this? Or can I ignore this?

(Also, my build process is failing, but I think it's probably due to something else.)

P.S. I am working on an embedded systems project.

Body:
One usually gets "statement has no effect" warnings when writing null statements with no side effects. For example:

*data << 1;

Perhaps you meant to do this?

*data <<= 1;


问:
Trigger Github Action only on new tags?
Is there a possibility to tigger a github action only if a new version (which comes with a new tag) is pushed? I don't want run them on every push into master, but I also want to avoid creating a release branch.</p>

答:
The goal is to trigger a workflow when a tag is pushed, e.g. doing something like:

```<code>git tag v1.0.0
git push origin v1.0.0
</code>```

In the workflow file:
e.g. ci.yml

name: CI
on:
  push:
    tags:
      - 'v[0-9]+.[0-9]+.[0-9]+'
```

This will run if someone pushes a semantic versioned tag to the GitHub repo.

One mistake I made was when migrating from Travis CI to GitHub Actions is that I incorrectly used

'^v[0-9]+\.[0-9]+\.[0-9]+'

as the pattern, which is WRONG. So check your pattern syntax if the workflow is not being triggered.

Title: Trigger Github Action only on new tags?

Body:
The goal is to trigger a workflow when a tag is pushed, e.g. doing something like:

git tag v1.0.0
git push origin v1.0.0

In the workflow file:
e.g. ci.yml

name: CI
on:
  push:
    tags:
      - 'v[0-9]+.[0-9]+.[0-9]+'

This will run if someone pushes a semantic versioned tag to the GitHub repo.

One mistake I made was when migrating from Travis CI to GitHub Actions is that I incorrectly used

'^v[0-9]+\.[0-9]+\.[0-9]+'

as the pattern, which is WRONG. So check your pattern syntax if the workflow is not being triggered.


问:
Convet this sql query to php laravel?
SELECT project_name, (CHAR_LENGTH(company_id) - CHAR_LENGTH(REPLACE(company_id, ',', '')) + 1) as total FROM project_management;</p>

答:
try this</p>
```<code>$getData = DB::table('project_management')
->selectRaw('(CHAR_LENGTH(company_id) - CHAR_LENGTH(REPLACE(company_id, ',', ''))
+ 1) as total')
->addSelect('project_name')
->get();
</code>```

Title: Convet this sql query to php laravel?

Body:
try this

$getData = DB::table('project_management')
->selectRaw('(CHAR_LENGTH(company_id) - CHAR_LENGTH(REPLACE(company_id, ',', ''))
+ 1) as total')
->addSelect('project_name')
->get();


问:
Constraint is not enough?
I have a very simple Database consist of;

Person_id, City and is_manager columns. is_manager can have TRUE or FALSE bit (0,1).

There are some restrictions that I manage to complete, such as;

each city can have one or more than one person (unique
person_id+City)

each person can be either manager or not in a city. (unique person+city+is_manager)

each city can have only one manager
but can have more than one non-managers.

not every person has to have a city, some might not be assigned to a
city at all.

I managed to do first two constraints easily but I couldn't manage for the third condition. because each city can have one manager, but can have more than one non_manager positions.

I have some other methodology to solve it but it will be not 100% on server-side solution. I want to have 100% SQL Server side solution.

I think it can be done with trigger;

if so, how? (when is_manager TRUE comes, search whole database for that if city has any manager before, if not accept data, otherwise don't accept)

if not necessary, how with constraints?

答:
A sample DB

```<code>create table Person(
    id int primary key,
    cityId int,
    constraint UK1 unique(cityId, id)
);

create table City (
    id int primary key,
    managerId int,
    constraint FK1 foreign key(id, managerId) references Person(cityId, id)
);
</code>```

Business process is first assign a person to a City then make him/her a manager of the City.

db<>fiddle including test data

Title: Constraint is not enough?

Body:
A sample DB

create table Person(
    id int primary key,
    cityId int,
    constraint UK1 unique(cityId, id)
);

create table City (
    id int primary key,
    managerId int,
    constraint FK1 foreign key(id, managerId) references Person(cityId, id)
);

Business process is first assign a person to a City then make him/her a manager of the City.

db<>fiddle including test data


问:
Using variables in a function from another function
In function foo() there is a loop that iterates until it finds an optimum set of variables and determines that as the ideal set. The function only returns one variable, in order to pass a unit test.

In the next function bar(), I need to output all of the variables in function foo() as it iterates. First output the optimum set of variables, and then the rest of the possible variable sets seperately.

```<code>int foo(int a, int b) {
    int c, d;
    while ( etc. ) {
        c = arithmetic_for_c;
        d = arithmetic_for_d;
        e = c + d;
    }
    return e;
}

int bar(a, b) {
    cout << e;
    cout << c << d;
}
</code>```

This example is very simple, but you get the idea.

I have a feeling references (int&, string& etc) would help somehow, but I'm not sure how they would be used here.

I tried to put together a global array but that seemed to get a bit too complex for the scope of this assignment.

The loop is a necessity, but also seems to ruin any hope for variables or arrays in the global scope.

Unfortunately there are a number of things we haven't learned yet, so there is likely a solution I can't use yet.

Thoughts?

Thank you!

答:
Unless you want to go really fancy (probably not within your reach, yet), foo() has to help bar() a little.

Since you want to show the end result first, then the intermediate data later, you will have to find some way of storing the intermediate states. You could do so, using arrays or lists and push the intermediate values into them.

But another, probably shorter option is, to just store the intermediate output.

You know how to use std::cout by now, which prints output to the console.
It is of type std::ostream. And next to output to a console (or file etc.), the c++ standard library also allows to output to a string.
So, for your use case to work, you create such a string stream, then call bar and give it as output stream the string stream.
At the end of your calculations, you call bar with the regular output stream to print the end result, then, you output the string of the string stream to the regular output stream.

It sounds more convoluted, than it actually is, if you see it in code:

```<code>#include <iostream>
#include <sstream>

void bar(int a, int b, int c, int d, int e, std::ostream& os) {
  os
    << "a: " << a
    << " b: " << b
    << " c: " << c
    << " d: " << d
    << " e: " << e
    << std::endl;
}

int foo(int a, int b, std::ostream& os ) {
  std::ostringstream ossteps;
  int c=  0;
  int d=  1;
  int e= 42;
  while (c < 10) {
    bar(a,b,c,d,e,ossteps);
    c++;
    d += c*c;
    e = (a * b) - d;
  }
  bar(a,b,c,d,e,os);
  os << ossteps.str();
  return e;
}

int main (int argc, const char* argv[]) {
  int efinal = foo(1,2, std::cout);
  return 0;
}

</code>```

Body:
In function foo() there is a loop that iterates until it finds an optimum set of variables and determines that as the ideal set. The function only returns one variable, in order to pass a unit test.

In the next function bar(), I need to output all of the variables in function foo() as it iterates. First output the optimum set of variables, and then the rest of the possible variable sets seperately.

int foo(int a, int b) {
    int c, d;
    while ( etc. ) {
        c = arithmetic_for_c;
        d = arithmetic_for_d;
        e = c + d;
    }
    return e;
}

int bar(a, b) {
    cout << e;
    cout << c << d;
}

This example is very simple, but you get the idea.

I have a feeling references (int&, string& etc) would help somehow, but I'm not sure how they would be used here.

I tried to put together a global array but that seemed to get a bit too complex for the scope of this assignment.

The loop is a necessity, but also seems to ruin any hope for variables or arrays in the global scope.

Unfortunately there are a number of things we haven't learned yet, so there is likely a solution I can't use yet.

Thoughts?

Thank you!

Body:
Unless you want to go really fancy (probably not within your reach, yet), foo() has to help bar() a little.

Since you want to show the end result first, then the intermediate data later, you will have to find some way of storing the intermediate states. You could do so, using arrays or lists and push the intermediate values into them.

But another, probably shorter option is, to just store the intermediate output.

You know how to use std::cout by now, which prints output to the console.
It is of type std::ostream. And next to output to a console (or file etc.), the c++ standard library also allows to output to a string.
So, for your use case to work, you create such a string stream, then call bar and give it as output stream the string stream.
At the end of your calculations, you call bar with the regular output stream to print the end result, then, you output the string of the string stream to the regular output stream.

It sounds more convoluted, than it actually is, if you see it in code:

#include <iostream>
#include <sstream>

void bar(int a, int b, int c, int d, int e, std::ostream& os) {
  os
    << "a: " << a
    << " b: " << b
    << " c: " << c
    << " d: " << d
    << " e: " << e
    << std::endl;
}

int foo(int a, int b, std::ostream& os ) {
  std::ostringstream ossteps;
  int c=  0;
  int d=  1;
  int e= 42;
  while (c < 10) {
    bar(a,b,c,d,e,ossteps);
    c++;
    d += c*c;
    e = (a * b) - d;
  }
  bar(a,b,c,d,e,os);
  os << ossteps.str();
  return e;
}

int main (int argc, const char* argv[]) {
  int efinal = foo(1,2, std::cout);
  return 0;
}


问:
How to extract elements of an array in object type in c#?
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

```<code>int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (<b>of a priory unknown type and I cannot use type conversion in the code </b>
//How can extract elements of obj and use them, e.g. write them on the screen?`
</code>```

答:
You can cast it.</p>

```<code>var myTempArray = obj as IEnumerable;

foreach (object item in myTempArray)
   ...
</code>```

Body:
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (of a priory unknown type and I cannot use type conversion in the code
//How can extract elements of obj and use them, e.g. write them on the screen?`

Body:
You can cast it.

var myTempArray = obj as IEnumerable;

foreach (object item in myTempArray)
   ...


问:
FireDAC: possibility to make query faster - Delphi
I use bind variables in Delphi and on the other side there is Oracle database with Database link (@dblink). When I build a SELECT statement without bind variables, it has no problem with performance. Only if I query SELECT statement with bind variables it takes very long (sometimes 1-2 hour). Is it possible in FireDAC to make the query faster without changing SQL-query? I need to use bind variables to avoid SQL injection.

```<code>This SQL is very Fast in Delphi:
SELECT
 DLGH_START_D Datum,
 TRUNC((d.DLGH_ENDE_D - d.DLGH_START_D) * 24 * 60)||' Min '||
 TRUNC(MOD(((d.DLGH_ENDE_D - d.DLGH_START_D) * 24 * 3600), 60))||' Sek' Dauer
FROM
  dialoghistory d
WHERE
 d.DLGH_PARAMETER_C = 'Name of Parameter' AND  <--
 d.dlgh_funktion_c = 'SQLS' AND
 d.DLGH_START_D > '01.02.2020'  <--
order by 1

This SQL is very slow in Delphi:
SELECT
 DLGH_START_D Datum,
 TRUNC((d.DLGH_ENDE_D - d.DLGH_START_D) * 24 * 60)||' Min '||
 TRUNC(MOD(((d.DLGH_ENDE_D - d.DLGH_START_D) * 24 * 3600), 60))||' Sek' Dauer
FROM
  dialoghistory d
WHERE
 d.DLGH_PARAMETER_C = :B_Name AND  <--
 d.dlgh_funktion_c = 'SQLS' AND
 d.DLGH_START_D > :Datum    <--
order by 1

    ---------------------------
    //slow execution period ,  because of bind variables (1 h)
    qry := TFDQuery.CreateSQL(Application, sSqlText_.Text);
    with qry do begin
    ...
     Param.AsString := value; //set value of bind variable
    ...
    Open;
</code>```

Table dialoghistory looks like this

答:
My Solution:</p>
```<code>tmpQuery := TFDQuery.Create(self);  // Create Query
tmpQuery.Sql.Text := 'SELECT * FROM dlgHistory d where d.DLGH_PARAMETER = :par';

...
// Set Data Type, Param Type and Size yourself
 with tmpQuery.Params do begin
  Clear;
   with Add do begin
    Name := 'par';
    DataType := ftString;
    Size := 128;
    ParamType := ptInput;
   end;
  end;

tmpQuery.Params[0].AsString := 'Value';  //assign a value

tmpQuery.Prepare;
tmpQuery.Open; //And it works perfect!
</code>```

Body:
I use bind variables in Delphi and on the other side there is Oracle database with Database link (@dblink). When I build a SELECT statement without bind variables, it has no problem with performance. Only if I query SELECT statement with bind variables it takes very long (sometimes 1-2 hour). Is it possible in FireDAC to make the query faster without changing SQL-query? I need to use bind variables to avoid SQL injection.

This SQL is very Fast in Delphi:
SELECT
 DLGH_START_D Datum,
 TRUNC((d.DLGH_ENDE_D - d.DLGH_START_D) * 24 * 60)||' Min '||
 TRUNC(MOD(((d.DLGH_ENDE_D - d.DLGH_START_D) * 24 * 3600), 60))||' Sek' Dauer
FROM
  dialoghistory d
WHERE
 d.DLGH_PARAMETER_C = 'Name of Parameter' AND  <--
 d.dlgh_funktion_c = 'SQLS' AND
 d.DLGH_START_D > '01.02.2020'  <--
order by 1

This SQL is very slow in Delphi:
SELECT
 DLGH_START_D Datum,
 TRUNC((d.DLGH_ENDE_D - d.DLGH_START_D) * 24 * 60)||' Min '||
 TRUNC(MOD(((d.DLGH_ENDE_D - d.DLGH_START_D) * 24 * 3600), 60))||' Sek' Dauer
FROM
  dialoghistory d
WHERE
 d.DLGH_PARAMETER_C = :B_Name AND  <--
 d.dlgh_funktion_c = 'SQLS' AND
 d.DLGH_START_D > :Datum    <--
order by 1

    ---------------------------
    //slow execution period ,  because of bind variables (1 h)
    qry := TFDQuery.CreateSQL(Application, sSqlText_.Text);
    with qry do begin
    ...
     Param.AsString := value; //set value of bind variable
    ...
    Open;

Table dialoghistory looks like this

Body:
My Solution:

tmpQuery := TFDQuery.Create(self);  // Create Query
tmpQuery.Sql.Text := 'SELECT * FROM dlgHistory d where d.DLGH_PARAMETER = :par';

...
// Set Data Type, Param Type and Size yourself
 with tmpQuery.Params do begin
  Clear;
   with Add do begin
    Name := 'par';
    DataType := ftString;
    Size := 128;
    ParamType := ptInput;
   end;
  end;

tmpQuery.Params[0].AsString := 'Value';  //assign a value

tmpQuery.Prepare;
tmpQuery.Open; //And it works perfect!


问:
DEPRECATED: DI is instantiating a token "MockLocationStrategy" that inherits its @Injectable decorator but does not provide one itself
While testing my Angular application I am getting deprecation warnings

'DEPRECATED: DI is instantiating a token "MockLocationStrategy" that inherits its @Injectable decorator but does not provide one itself.
This will become an error in a future version of Angular. Please add @Injectable() to the "MockLocationStrategy" class.'

Below is a sample test throwing the warning

```<code>
describe('BookComponent', () => {
  let component: BookComponent;
  let fixture: ComponentFixture<BookIssueComponent>;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
      ],
      declarations: [BookComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BookComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

</code>```

I believe the warning is because I updated my packages

```<code>Package                                   Current     Wanted    Latest  Location
@angular-devkit/architect               0.1102.11  0.1102.13  0.1200.1  node_modules/@angular-devkit/architect
@angular-devkit/build-angular           0.1102.11  0.1102.13    12.0.1  node_modules/@angular-devkit/build-angular
@angular-eslint/builder                     4.2.0      4.3.0    12.0.0  node_modules/@angular-eslint/builder
@angular-eslint/eslint-plugin               4.2.0      4.3.0    12.0.0  node_modules/@angular-eslint/eslint-plugin
@angular-eslint/eslint-plugin-template      4.2.0      4.3.0    12.0.0  node_modules/@angular-eslint/eslint-plugin-template
@angular-eslint/schematics                  4.2.0      4.3.0    12.0.0  node_modules/@angular-eslint/schematics
@angular-eslint/template-parser             4.2.0      4.3.0    12.0.0  node_modules/@angular-eslint/template-parser
@angular/animations                       11.2.12    11.2.14    12.0.1  node_modules/@angular/animations
@angular/cdk                              11.2.11    11.2.13    12.0.1  node_modules/@angular/cdk
@angular/cli                              11.2.11    11.2.13    12.0.1  node_modules/@angular/cli
@angular/common                           11.2.12    11.2.14    12.0.1  node_modules/@angular/common
@angular/compiler                         11.2.12    11.2.14    12.0.1  node_modules/@angular/compiler
@angular/compiler-cli                     11.2.12    11.2.14    12.0.1  node_modules/@angular/compiler-cli
@angular/core                             11.2.12    11.2.14    12.0.1  node_modules/@angular/core
@angular/forms                            11.2.12    11.2.14    12.0.1  node_modules/@angular/forms
@angular/language-service                 11.2.12    11.2.14    12.0.1  node_modules/@angular/language-service
@angular/platform-browser                 11.2.12    11.2.14    12.0.1  node_modules/@angular/platform-browser
@angular/platform-browser-dynamic         11.2.12    11.2.14    12.0.1  node_modules/@angular/platform-browser-dynamic
@angular/pwa                            0.1102.11  0.1102.13    12.0.1  node_modules/@angular/pwa
@angular/router                           11.2.12    11.2.14    12.0.1  node_modules/@angular/router
@angular/service-worker                   11.2.12    11.2.14    12.0.1  node_modules/@angular/service-worker
@ngrx/component                            11.1.1     11.1.1    12.0.0  node_modules/@ngrx/component
@ngrx/effects                              11.1.1     11.1.1    12.0.0  node_modules/@ngrx/effects
@ngrx/entity                               11.1.1     11.1.1    12.0.0  node_modules/@ngrx/entity
@ngrx/schematics                           11.1.1     11.1.1    12.0.0  node_modules/@ngrx/schematics
@ngrx/store                                11.1.1     11.1.1    12.0.0  node_modules/@ngrx/store
@ngrx/store-devtools                       11.1.1     11.1.1    12.0.0  node_modules/@ngrx/store-devtools
@tinymce/tinymce-angular                    4.2.2      4.2.3     4.2.3  node_modules/@tinymce/tinymce-angular
@types/jasmine                             3.6.10      3.7.4     3.7.4  node_modules/@types/jasmine
@types/jasminewd2                           2.0.8      2.0.9     2.0.9  node_modules/@types/jasminewd2
@types/node                                15.0.1     15.6.0    15.6.0  node_modules/@types/node
@typescript-eslint/eslint-plugin           4.22.0     4.22.0    4.24.0  node_modules/@typescript-eslint/eslint-plugin
@typescript-eslint/parser                  4.22.0     4.22.0    4.24.0  node_modules/@typescript-eslint/parser
bootstrap                                   4.6.0      4.6.0     5.0.1  node_modules/bootstrap
eslint                                     7.25.0     7.26.0    7.26.0  node_modules/eslint
eslint-plugin-import                       2.22.1     2.22.1    2.23.2  node_modules/eslint-plugin-import
eslint-plugin-jsdoc                        33.0.0     33.0.0    34.8.2  node_modules/eslint-plugin-jsdoc
google-libphonenumber                      3.2.19     3.2.21    3.2.21  node_modules/google-libphonenumber
ng2-pdf-viewer                              6.4.1      6.4.1     7.0.1  node_modules/ng2-pdf-viewer
rxjs                                        6.6.7      6.6.7     7.1.0  node_modules/rxjs
snyk                                      1.580.0    1.605.0   1.605.0  node_modules/snyk
tinymce                                     5.7.1      5.8.1     5.8.1  node_modules/tinymce
typescript                                  4.1.5      4.1.5     4.2.4  node_modules/typescript
</code>```

I have tried to follow the discussion docs: RouterTestingModule should be added to Testing guide #34341 but I am not getting how to resolve this issue

But how do I provide my RouterTesting Module to solve this issue?

答: Using Angular ^12.2.14 this issue could be solved by completely nuking the node_modules directory followed by npm install.

Body:
While testing my Angular application I am getting deprecation warnings

'DEPRECATED: DI is instantiating a token "MockLocationStrategy" that inherits its @Injectable decorator but does not provide one itself.
This will become an error in a future version of Angular. Please add @Injectable() to the "MockLocationStrategy" class.'

Below is a sample test throwing the warning

describe('BookComponent', () => {
  let component: BookComponent;
  let fixture: ComponentFixture<BookIssueComponent>;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
      ],
      declarations: [BookComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BookComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

I believe the warning is because I updated my packages

Package                                   Current     Wanted    Latest  Location
@angular-devkit/architect               0.1102.11  0.1102.13  0.1200.1  node_modules/@angular-devkit/architect
@angular-devkit/build-angular           0.1102.11  0.1102.13    12.0.1  node_modules/@angular-devkit/build-angular
@angular-eslint/builder                     4.2.0      4.3.0    12.0.0  node_modules/@angular-eslint/builder
@angular-eslint/eslint-plugin               4.2.0      4.3.0    12.0.0  node_modules/@angular-eslint/eslint-plugin
@angular-eslint/eslint-plugin-template      4.2.0      4.3.0    12.0.0  node_modules/@angular-eslint/eslint-plugin-template
@angular-eslint/schematics                  4.2.0      4.3.0    12.0.0  node_modules/@angular-eslint/schematics
@angular-eslint/template-parser             4.2.0      4.3.0    12.0.0  node_modules/@angular-eslint/template-parser
@angular/animations                       11.2.12    11.2.14    12.0.1  node_modules/@angular/animations
@angular/cdk                              11.2.11    11.2.13    12.0.1  node_modules/@angular/cdk
@angular/cli                              11.2.11    11.2.13    12.0.1  node_modules/@angular/cli
@angular/common                           11.2.12    11.2.14    12.0.1  node_modules/@angular/common
@angular/compiler                         11.2.12    11.2.14    12.0.1  node_modules/@angular/compiler
@angular/compiler-cli                     11.2.12    11.2.14    12.0.1  node_modules/@angular/compiler-cli
@angular/core                             11.2.12    11.2.14    12.0.1  node_modules/@angular/core
@angular/forms                            11.2.12    11.2.14    12.0.1  node_modules/@angular/forms
@angular/language-service                 11.2.12    11.2.14    12.0.1  node_modules/@angular/language-service
@angular/platform-browser                 11.2.12    11.2.14    12.0.1  node_modules/@angular/platform-browser
@angular/platform-browser-dynamic         11.2.12    11.2.14    12.0.1  node_modules/@angular/platform-browser-dynamic
@angular/pwa                            0.1102.11  0.1102.13    12.0.1  node_modules/@angular/pwa
@angular/router                           11.2.12    11.2.14    12.0.1  node_modules/@angular/router
@angular/service-worker                   11.2.12    11.2.14    12.0.1  node_modules/@angular/service-worker
@ngrx/component                            11.1.1     11.1.1    12.0.0  node_modules/@ngrx/component
@ngrx/effects                              11.1.1     11.1.1    12.0.0  node_modules/@ngrx/effects
@ngrx/entity                               11.1.1     11.1.1    12.0.0  node_modules/@ngrx/entity
@ngrx/schematics                           11.1.1     11.1.1    12.0.0  node_modules/@ngrx/schematics
@ngrx/store                                11.1.1     11.1.1    12.0.0  node_modules/@ngrx/store
@ngrx/store-devtools                       11.1.1     11.1.1    12.0.0  node_modules/@ngrx/store-devtools
@tinymce/tinymce-angular                    4.2.2      4.2.3     4.2.3  node_modules/@tinymce/tinymce-angular
@types/jasmine                             3.6.10      3.7.4     3.7.4  node_modules/@types/jasmine
@types/jasminewd2                           2.0.8      2.0.9     2.0.9  node_modules/@types/jasminewd2
@types/node                                15.0.1     15.6.0    15.6.0  node_modules/@types/node
@typescript-eslint/eslint-plugin           4.22.0     4.22.0    4.24.0  node_modules/@typescript-eslint/eslint-plugin
@typescript-eslint/parser                  4.22.0     4.22.0    4.24.0  node_modules/@typescript-eslint/parser
bootstrap                                   4.6.0      4.6.0     5.0.1  node_modules/bootstrap
eslint                                     7.25.0     7.26.0    7.26.0  node_modules/eslint
eslint-plugin-import                       2.22.1     2.22.1    2.23.2  node_modules/eslint-plugin-import
eslint-plugin-jsdoc                        33.0.0     33.0.0    34.8.2  node_modules/eslint-plugin-jsdoc
google-libphonenumber                      3.2.19     3.2.21    3.2.21  node_modules/google-libphonenumber
ng2-pdf-viewer                              6.4.1      6.4.1     7.0.1  node_modules/ng2-pdf-viewer
rxjs                                        6.6.7      6.6.7     7.1.0  node_modules/rxjs
snyk                                      1.580.0    1.605.0   1.605.0  node_modules/snyk
tinymce                                     5.7.1      5.8.1     5.8.1  node_modules/tinymce
typescript                                  4.1.5      4.1.5     4.2.4  node_modules/typescript

I have tried to follow the discussion docs: RouterTestingModule should be added to Testing guide #34341 but I am not getting how to resolve this issue

But how do I provide my RouterTesting Module to solve this issue?


问:
MySQL is too smart about accented characters
I guess, normally people would be aiming to make their programme behave like this, but in my case this is completely opposite from what I want.

Somehow, my MySQL database is able to read different accented characters as identical. For instance, shī, shí, shǐ, shì and shi are all the same thing to it. When I search for one, I’ll get the others as well. Proofpic:

This is not what I want, since for me those values are very different. Basically, the query on the pic must return empty rows, because there is no a single entry in that table with shi (without an accent).

My tables type is InnoDB, collation is utf8_general_ci.

答:
Use utf8_bin collation. You don't have to change collation of entire column, you can just use it on per query basis

```<code>WHERE `pinyin` = 'shi' COLLATE utf8_bin
</code>```

You can also experiment with different collations which might work better for you (utf8_bin works on binery level, so even if two unicode characters with different byte codes are the same, it will see them as different).

Body:
Use utf8_bin collation. You don't have to change collation of entire column, you can just use it on per query basis

WHERE `pinyin` = 'shi' COLLATE utf8_bin

You can also experiment with different collations which might work better for you (utf8_bin works on binery level, so even if two unicode characters with different byte codes are the same, it will see them as different).


问:
Regex Extraction - Match before a space, or NOT before a space
Here are my potential inputs:

brian@muck.co, brian@gmail.com

brian@gmail.com, brian@muck.co

What I want to do is extract the @muck.co email address.

What I have tried is:
\s.*@muck.co

The problem is that this only grabs an email address if it is preceded by a space (so it would only match the second example input above). . . How would I write a Regex expression to match either inputs?

答:
You can use a negated character class to not cross the @ and use either a word boundary at the end to prevent a partial word match:

```<code>[^\s@]+@muck\.co\b
</code>```

Regex demo

Body:
You can use a negated character class to not cross the @ and use either a word boundary at the end to prevent a partial word match:

[^\s@]+@muck\.co\b

Regex demo


问:
unable to resolve dependency tree error when using npm install generic-ui
I was trying to install generic-ui in my angular project using the cmd:

```<code>npm i @generic-ui/ngx-grid @generic-ui/fabric @generic-ui/hermes
</code>```

but I got the following error :

```<code>$ npm i @generic-ui/ngx-grid @generic-ui/fabric @generic-ui/hermes
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: angular-app@0.0.0
npm ERR! Found: @angular/common@13.1.3
npm ERR! node_modules/@angular/common
npm ERR!   @angular/common@"~13.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"12.2.11" from @generic-ui/ngx-grid@0.16.4
npm ERR! node_modules/@generic-ui/ngx-grid
npm ERR!   @generic-ui/ngx-grid@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\PC\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\PC\AppData\Local\npm-cache\_logs\2022-02-10T20_30_51_751Z-debug-0.log
</code>```

I literally tried everything, I updated npm, installed Angular CLI again, downloaded and installed node again, npm audit, and a lot of other things but nothing happened.

答:
you are trying to install @angular/common@13.1.3 in your project but the module @generic-ui/ngx-grid@0.16.4 ask the package @angular/common@"12.2.11" is not yet compatible

in the github page of ngx-grid it says the module is not yet compatible with angular 13

Currently highest supported Angular version is 12.2. We are working on
bringing Gui libraries to Angular 13.

https://github.com/generic-ui/generic-ui

The better for your project it to stay to angular 12 while dependencies are not compatible with angular 13

Body:
I was trying to install generic-ui in my angular project using the cmd:

npm i @generic-ui/ngx-grid @generic-ui/fabric @generic-ui/hermes

but I got the following error :

$ npm i @generic-ui/ngx-grid @generic-ui/fabric @generic-ui/hermes
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: angular-app@0.0.0
npm ERR! Found: @angular/common@13.1.3
npm ERR! node_modules/@angular/common
npm ERR!   @angular/common@"~13.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"12.2.11" from @generic-ui/ngx-grid@0.16.4
npm ERR! node_modules/@generic-ui/ngx-grid
npm ERR!   @generic-ui/ngx-grid@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\PC\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\PC\AppData\Local\npm-cache\_logs\2022-02-10T20_30_51_751Z-debug-0.log

I literally tried everything, I updated npm, installed Angular CLI again, downloaded and installed node again, npm audit, and a lot of other things but nothing happened.


问:
How I can convert TypeScript type?
I have the code

```<code>interface IProps {
  name: string;
  age: number;
}
</code>```

I want to get

```<code>type Result = {
  key: 'name',
  value: string
} | {
  key: 'age',
  value: number
}
</code>```

Is there any good way?

答:
COnsider this example:

interface IProps {
    name: string;
    age: number;
}

type Distribute<Obj, Keys extends keyof Obj> = Keys extends any ? { key: Keys, value: Obj[Keys] } : never

type Builder<T> = Distribute<T, keyof T>

// type Result = {
//     key: "name";
//     value: string;
// } | {
//     key: "age";
//     value: number;
// }
type Result = Builder<IProps>
```
<p>Playground</p>
<p>Here you can find more information about distributivity</p>
<p>This line of code <code>{ key: Keys, value: Obj[Keys] }</code> is applied to each <code>IProps</code> key separately because of distributivity</p>
<p>P.S. There is also an alternative way:</p>
<pre class="lang-js prettyprint-override"><code>type AlternativeWay<T> = {
    [Prop in keyof T]: {
        key: Prop,
        value: T[Prop]
    }
}[keyof T]

type Result = AlternativeWay<IProps>
</code>```

Title: How I can convert TypeScript type?

Body:
I have the code

interface IProps {
  name: string;
  age: number;
}

I want to get

type Result = {
  key: 'name',
  value: string
} | {
  key: 'age',
  value: number
}

Is there any good way?

Body:
COnsider this example:

interface IProps {
    name: string;
    age: number;
}

type Distribute<Obj, Keys extends keyof Obj> = Keys extends any ? { key: Keys, value: Obj[Keys] } : never

type Builder<T> = Distribute<T, keyof T>

// type Result = {
//     key: "name";
//     value: string;
// } | {
//     key: "age";
//     value: number;
// }
type Result = Builder<IProps>

Playground

Here you can find more information about distributivity

This line of code { key: Keys, value: Obj[Keys] } is applied to each IProps key separately because of distributivity

P.S. There is also an alternative way:

type AlternativeWay<T> = {
    [Prop in keyof T]: {
        key: Prop,
        value: T[Prop]
    }
}[keyof T]

type Result = AlternativeWay<IProps>


问:
SSL Self-Signed certificate not trusted by ASP.Net app
I have an ASP.Net app that requires SSL certification in order to connect to a Dynamics NAV instance via SOAP.

I've created a self signed SSL certificate using the New-SelfSignedCertificateEx.ps1 script. The exact command used was:

New-SelfSignedCertificateEx -Subject "CN=<computerHostname>" -IsCA $true -Exportable -StoreLocation LocalMachine -NotAfter $([datetime]::now.AddYears(5))

Afterwards I copied the certificate to Trusted Root Certificates and added the thumbprint in the NAV instance settings, yet every time I try to connect my app to said NAV instance I receive an error stating:

System.ServiceModel.Security.SecurityNegotiationException: Could not establish trust relationship for the SSL/TLS secure channel with authority '<computerHostname>:<NavInstanceSOAPPort>'

答:
A self signed certificate is not a trusted certificate, you need to provide one from a trusted authority

Try Let's Encrypt, ZeroSSL, FreeSSL or any party you like, they will offer you free 90-day certificate good enough for your tests


问:
nginx proxy_pass download page from other host
I need to download pdf file from other host.

For example:

mydomain.com/bill/55d5e947-edc4-44e0-bee4-c5ffacaf81dd/download

must download pdf file from

domain.com/bill/55d5e947-edc4-44e0-bee4-c5ffacaf81dd/download

my location is below, may be i'm missing something?

```<code>         location "/bill/([0-9a-zA-Z]{8})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{12})/download" {
                proxy_pass http://10.130.0.31:8088;
                proxy_set_header content-type "application/pdf";
</code>```

答:
Regex Location matching always starts with ~, ~* ~^ like

location ~ /bill/([0-9a-zA-Z]{8})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{12})/download {
...
}
```
<p>Is your Regex correct? I mean technically it is BUT the ID in your location looks like a UUID? Could this be possible? As UUID are basically hex and as you are already spending the compute time to validate the UUID in the location you should use <code>[a-f0-9]</code> instead of <code>[0-9a-zA-Z]</code>. BUT JUST IF IT IS A UUID and not just like a Thing that looks like a UUID.</p>
<p>A working configuration will look like</p>
<pre class="lang-sh prettyprint-override"><code> location ~ "/bill/([a-f0-9]{8})-([a-f0-9]{4})-([a-f0-9]{4})-([a-f0-9]{4})-([a-f0-9]{12})/download" {
                proxy_pass http://127.0.0.1:8000;
                proxy_set_header content-type "application/pdf";
}

</code>```

Body:
I need to download pdf file from other host.

For example:

mydomain.com/bill/55d5e947-edc4-44e0-bee4-c5ffacaf81dd/download

must download pdf file from

domain.com/bill/55d5e947-edc4-44e0-bee4-c5ffacaf81dd/download

my location is below, may be i'm missing something?

         location "/bill/([0-9a-zA-Z]{8})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{12})/download" {
                proxy_pass http://10.130.0.31:8088;
                proxy_set_header content-type "application/pdf";

Body:
Regex Location matching always starts with ~, ~* ~^ like

location ~ /bill/([0-9a-zA-Z]{8})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{4})-([0-9a-zA-Z]{12})/download {
...
}

Is your Regex correct? I mean technically it is BUT the ID in your location looks like a UUID? Could this be possible? As UUID are basically hex and as you are already spending the compute time to validate the UUID in the location you should use [a-f0-9] instead of [0-9a-zA-Z]. BUT JUST IF IT IS A UUID and not just like a Thing that looks like a UUID.

A working configuration will look like

 location ~ "/bill/([a-f0-9]{8})-([a-f0-9]{4})-([a-f0-9]{4})-([a-f0-9]{4})-([a-f0-9]{12})/download" {
                proxy_pass http://127.0.0.1:8000;
                proxy_set_header content-type "application/pdf";
}


问:
For how long does Android save a killed activity's state?
I just did a little test: I started my app, went to a certain screen, pressed the home button and killed the process via Advanced Task Killer.

Now, if I go back to my app just a few moments later, I come back to that very screen. I also know that onRestoreInstanceState() is called in this case, as I have played around with this method quite a bit.

However, just out of curiosity, I did all the same, but let my phone lie around for some time (an hour or something). When I restarted my app, it went straight to the main activity.

So my question is: for how long does Android keep the saved state? or what determines if it throws it away or not? I already figured out it had nothing to do with lockscreen on/off.

Kind regards,
jellyfish

答: Android will dispose of the activity when it needs the resources that the activity is holding (usually memory) and the activity is not in the foreground.  There's more criteria involved, but that's the general case.  There's no predefined time limit or criteria other than "when it decides it needs to".  The app could die almost immediately or it could stay up indefinitely.  You should never assume your app will ever be killed and you should never assume your app will never be killed.</p>


问:
Find the largest Pair in an integer
I'm playing around with numbers, and I'm looking to write a small program that will return the largest double-digit of an integer that's passed in for example:

I pass in 2215487
it should return 87

I pass in 98765499
It should return 99

I've tried looking at Math.Max, but I don't believe that's what I'm looking for unless I have overlooked it

答:
You can divide by 10 each time and then compare the remainder of dividing the remaining number by 100. For example:

int v = 98765499;
int m = 0;
v = Math.Abs(v); // negate negative numbers so that we can process these too
while (v >= 10) // if you want to accept single digit initial values for V change this to v > 0
{
    m = Math.Max(m, v % 100);
    v /= 10;
}
Console.WriteLine(m);
```

We use v >= 10 because we don't want to consider single-digit numbers (e.g. an initial value of v = 5).

v % 100 uses the remainder operator to give us the value left over when we divide by 100.

v /= 10 divides v by 10 and stores the result in v.

I've used Math.Abs( ) to make this work with negative numbers too, though you can take this line out if you only care about positive numbers.

At the end, m will either hold 0 (for single digit numbers or zero) or the highest two-digit value.

Example execution flow:

Initial V
V % 100
New V

98765499
99
9876549

9876549
49
987654

987654
54
98765

98765
65
9876

9876
76
987

987
87
98

98
98
9

Highest v % 100 is 99.

Try it online

Title: Find the largest Pair in an integer

Body:
You can divide by 10 each time and then compare the remainder of dividing the remaining number by 100. For example:

int v = 98765499;
int m = 0;
v = Math.Abs(v); // negate negative numbers so that we can process these too
while (v >= 10) // if you want to accept single digit initial values for V change this to v > 0
{
    m = Math.Max(m, v % 100);
    v /= 10;
}
Console.WriteLine(m);

We use v >= 10 because we don't want to consider single-digit numbers (e.g. an initial value of v = 5).

v % 100 uses the remainder operator to give us the value left over when we divide by 100.

v /= 10 divides v by 10 and stores the result in v.

I've used Math.Abs( ) to make this work with negative numbers too, though you can take this line out if you only care about positive numbers.

At the end, m will either hold 0 (for single digit numbers or zero) or the highest two-digit value.

Example execution flow:

Initial V
V % 100
New V

98765499
99
9876549

9876549
49
987654

987654
54
98765

98765
65
9876

9876
76
987

987
87
98

98
98
9

Highest v % 100 is 99.

Try it online


问:
Equivalent of the Rstudio `browser()` function in Julia for debugging
I wondered if there is an equivalent to the browser() statement available in RStudio for debugging purposes for Julia (I am using the Juno IDE at the moment).

The R function browser() halts execution and invokes an environment browser when it is called. So, in principle, we can put browser() anywhere in our code to stop in this particular line and see what's stored in the environment at that moment, which is terrific for debugging purposes.

For instance, the code below will stop when i>3. Hence, that's exactly what we will see in the environment browser available in RStudio, where we will observe that i=4 at that moment in the code.

```<code>for (i in 1:5) {
  print(i)
  if (i>3) {
    browser()
  }
}
[1] 1
[1] 2
[1] 3
[1] 4
Called from: eval(ei, envir)
Browse[1]>
</code>```

答:
Have a look at Debugger.jl. Specifically the Place breakpoints in source code section:

It is sometimes more convenient to choose in the source code when to break. This is done for instance in Matlab/Octave with keyboard, and in R with browser(). You can use the @bp macro to do this

Your R example translated to Julia:

```<code>julia> using Debugger

julia> @run for i in 1:5
           println(i)
           if i > 3
               @bp
           end
       end
1
2
3
4
Hit breakpoint:
In ##thunk#257() at REPL[4]:1
  9  │         Base.println(i)
 10  │   %10 = i > 3
 11  └──       goto #4 if not %10
●12  3 ─       nothing
>13  4 ┄       @_2 = Base.iterate(%1, %8)
 14  │   %14 = @_2 === nothing
 15  │   %15 = ($(QuoteNode(Core.Intrinsics.not_int)))(%14)
 16  └──       goto #6 if not %15
 17  5 ─       goto #2

About to run: (iterate)(1:5, 4)
1|debug>
</code>```

This is a general solution for Julia, Juno IDE also has integrated debugging: Debugging, Juno manual.

Body:
I wondered if there is an equivalent to the browser() statement available in RStudio for debugging purposes for Julia (I am using the Juno IDE at the moment).

The R function browser() halts execution and invokes an environment browser when it is called. So, in principle, we can put browser() anywhere in our code to stop in this particular line and see what's stored in the environment at that moment, which is terrific for debugging purposes.

For instance, the code below will stop when i>3. Hence, that's exactly what we will see in the environment browser available in RStudio, where we will observe that i=4 at that moment in the code.

for (i in 1:5) {
  print(i)
  if (i>3) {
    browser()
  }
}
[1] 1
[1] 2
[1] 3
[1] 4
Called from: eval(ei, envir)
Browse[1]>

Body:
Have a look at Debugger.jl. Specifically the Place breakpoints in source code section:

It is sometimes more convenient to choose in the source code when to break. This is done for instance in Matlab/Octave with keyboard, and in R with browser(). You can use the @bp macro to do this

Your R example translated to Julia:

julia> using Debugger

julia> @run for i in 1:5
           println(i)
           if i > 3
               @bp
           end
       end
1
2
3
4
Hit breakpoint:
In ##thunk#257() at REPL[4]:1
  9  │         Base.println(i)
 10  │   %10 = i > 3
 11  └──       goto #4 if not %10
●12  3 ─       nothing
>13  4 ┄       @_2 = Base.iterate(%1, %8)
 14  │   %14 = @_2 === nothing
 15  │   %15 = ($(QuoteNode(Core.Intrinsics.not_int)))(%14)
 16  └──       goto #6 if not %15
 17  5 ─       goto #2

About to run: (iterate)(1:5, 4)
1|debug>

This is a general solution for Julia, Juno IDE also has integrated debugging: Debugging, Juno manual.


问:
Get-eventlog: How to get all Logs (Application, System, Security, etc) using powershell
I am trying to read All log files from EventLog using Get-eventlog commandlet

```<code>Get-EventLog -LogName Application, Security -after 09/15/2016 -Before 09/17/2016
</code>```

Instead of -LogName Application, I need all logs like Application, System, Security, etc.

Any help?

答:
Here is a working code based on @andrey-marchuk's answer. All the log are appended in a single file( ⚠ save the file with encoding UTF-8 with BOM because of the @)

```<code>$Begin = '10/02/2022 09:00:00'
$End = '10/02/2022 09:15:05'
$path= "C:\Users\user\Desktop\logevent\\"
If(!(test-path $path))
{
      New-Item -ItemType Directory -Force -Path $path
}
$datetimenow =  [DateTime]::Now.ToString("yyyy_MM_dd HH_mm_ss")
$allLog = (Get-WinEvent –ListLog * -ErrorAction SilentlyContinue).LogName
foreach ($lognameName in $allLog){
Get-WinEvent -FilterHashtable @{logname = $lognameName; StartTime = "$Begin"; EndTime = "$End" }  | Select-Object * | Out-File -Enc UTF8 -Append "$path $datetimenow winevent.txt"
}
</code>```

If you want to retrieve only specific info of the events, then replace Select-Object * by something like Select-Object TimeCreated, ID, LogName, Source, LevelDisplayName, Message

If you want separate files for each logname, you can do this, but be carefully, this will create > 400 files:

```<code>$Begin = '10/02/2022 09:00:00'
$End = '10/02/2022 09:15:05'
$path= "C:\Users\user\Desktop\logevent\\"
If(!(test-path $path))
{
      New-Item -ItemType Directory -Force -Path $path
}
$allLog = (Get-WinEvent –ListLog * -ErrorAction SilentlyContinue).LogName

foreach ($lognameName in $allLog){
$lognameFile = $lognameName.Replace("/", "-")
$datetimenow =  [DateTime]::Now.ToString("yyyy_MM_dd HH_mm_ss")
Get-WinEvent -FilterHashtable @{logname = $lognameName; StartTime = "$Begin"; EndTime = "$End" }  | Select-Object * | Out-File -Enc UTF8 -FilePath "$path $datetimenow winevent $lognameFile .txt"

}
</code>```

Body:
I am trying to read All log files from EventLog using Get-eventlog commandlet

Get-EventLog -LogName Application, Security -after 09/15/2016 -Before 09/17/2016

Instead of -LogName Application, I need all logs like Application, System, Security, etc.

Any help?

Body:
Here is a working code based on @andrey-marchuk's answer. All the log are appended in a single file( ⚠ save the file with encoding UTF-8 with BOM because of the @)

$Begin = '10/02/2022 09:00:00'
$End = '10/02/2022 09:15:05'
$path= "C:\Users\user\Desktop\logevent\\"
If(!(test-path $path))
{
      New-Item -ItemType Directory -Force -Path $path
}
$datetimenow =  [DateTime]::Now.ToString("yyyy_MM_dd HH_mm_ss")
$allLog = (Get-WinEvent –ListLog * -ErrorAction SilentlyContinue).LogName
foreach ($lognameName in $allLog){
Get-WinEvent -FilterHashtable @{logname = $lognameName; StartTime = "$Begin"; EndTime = "$End" }  | Select-Object * | Out-File -Enc UTF8 -Append "$path $datetimenow winevent.txt"
}

If you want to retrieve only specific info of the events, then replace Select-Object * by something like Select-Object TimeCreated, ID, LogName, Source, LevelDisplayName, Message

If you want separate files for each logname, you can do this, but be carefully, this will create > 400 files:

$Begin = '10/02/2022 09:00:00'
$End = '10/02/2022 09:15:05'
$path= "C:\Users\user\Desktop\logevent\\"
If(!(test-path $path))
{
      New-Item -ItemType Directory -Force -Path $path
}
$allLog = (Get-WinEvent –ListLog * -ErrorAction SilentlyContinue).LogName

foreach ($lognameName in $allLog){
$lognameFile = $lognameName.Replace("/", "-")
$datetimenow =  [DateTime]::Now.ToString("yyyy_MM_dd HH_mm_ss")
Get-WinEvent -FilterHashtable @{logname = $lognameName; StartTime = "$Begin"; EndTime = "$End" }  | Select-Object * | Out-File -Enc UTF8 -FilePath "$path $datetimenow winevent $lognameFile .txt"

}


问:
How to write a Azure Function and pass POST API?
I need some help in writing an Azure function with CosmosDB trigger, which will capture some values from cosmosdb like below and create a POST call and trigger an API. Is it possible in Azure function?
Cosmosdb:

The POST API which needs to be passed through Azure function is like this.

答:
Here is the example code to for passing POST in the Azure function

[FunctionName("TestPost")]
public static HttpResponseMessage POST([HttpTrigger(AuthorizationLevel.Function, "put", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
    try
    {
        //create redis connection and database
        var RedisConnection = RedisConnectionFactory.GetConnection();
        var serializer = new NewtonsoftSerializer();
        var cacheClient = new StackExchangeRedisCacheClient(RedisConnection, serializer);

        //read json object from request body
        var content = req.Content;
        string JsonContent = content.ReadAsStringAsync().Result;

        var expirytime = DateTime.Now.AddHours(Convert.ToInt16(ConfigurationSettings.AppSettings["ExpiresAt"]));

        SessionModel ObjModel = JsonConvert.DeserializeObject<SessionModel>(JsonContent);
        bool added = cacheClient.Add("RedisKey", ObjModel, expirytime); //store to cache

        return req.CreateResponse(HttpStatusCode.OK, "RedisKey");
    }
    catch (Exception ex)
    {
        return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "an error has occured");
    }
}
```

Here are the few examples for Post in Azure functions

Azure function POST

Post Async Function.

Body:
Here is the example code to for passing POST in the Azure function

[FunctionName("TestPost")]
public static HttpResponseMessage POST([HttpTrigger(AuthorizationLevel.Function, "put", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
    try
    {
        //create redis connection and database
        var RedisConnection = RedisConnectionFactory.GetConnection();
        var serializer = new NewtonsoftSerializer();
        var cacheClient = new StackExchangeRedisCacheClient(RedisConnection, serializer);

        //read json object from request body
        var content = req.Content;
        string JsonContent = content.ReadAsStringAsync().Result;

        var expirytime = DateTime.Now.AddHours(Convert.ToInt16(ConfigurationSettings.AppSettings["ExpiresAt"]));

        SessionModel ObjModel = JsonConvert.DeserializeObject<SessionModel>(JsonContent);
        bool added = cacheClient.Add("RedisKey", ObjModel, expirytime); //store to cache

        return req.CreateResponse(HttpStatusCode.OK, "RedisKey");
    }
    catch (Exception ex)
    {
        return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "an error has occured");
    }
}

Here are the few examples for Post in Azure functions

Azure function POST

Post Async Function.


问:
Store Private Key into Azure KeyVault, value got changed
I tried to store my private key to Azure Key Vault, but when I retrieve it out, my private key got changed.

If I put the private key into my web.config file, it works without any issue.

```<code>-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAohoZ+TCXMn17BPFXFCuIHvh7oONSBNCjuixl2CbwrGO8tIAO
XIQP1sZa3lhXkUj0f4HewmYsx6JR+39Do21H+QtCZxR4qCvOJxrrFHqMrk76aQji
....
ZVmUljOatig+g+q+jMEf7IA5zcAgBdAAuausXrPoNcip89Yuqag1
-----END RSA PRIVATE KEY-----
</code>```

Since my private key is just a text, I stored it as a Secrets. Am I doing the right thing?

I also tried to store the key as a Certificate, but the key is just a text with hidden CRLN, it is not PEM or PKCS#12. And in my case, I don't need to store the public key.

Below is my code to retrieve the key:

```<code>public static string GetDocuSignPrivateKey()
{
    var key = keyVaultClient.GetSecretAsync($"{vaultUrl}secrets/DocuSignPrivateKey/88e15b41234bf89619ddc9a2exxxx").Result;

    return key.Value;
}
</code>```

Sorry, I just start using Azure KeyVault.  Please help.  Thank you.

答:
This is how I deployed a private key from a .ppk file to the keyvault using powershell. The first one is in nonproduction where I used AAD MFA, the second one is in production where I used a service principal.

AAD Multifactor Log In

```<code>Connect-AzAccount -DeviceCode

$fileContentInBvtes = get-content C:\Users\filedirectory\file.ppk -Encoding Byte
$fileContentAsBase64 = [Svstem.Convert]::ToBase64String($fileContentInBytes)

Set-AzKeyVaultSecret -VaultName 'CHANGEVALUETOKEYVAULTNAME' -SecretName 'CHANGEVALUETOSECRETNAME' -SecretValue (ConvertTo-SecureString -String $fileContentAsBase64 -force -AsPlainText) -ErrorAction Stop
</code>```

Service Principal

```<code>$secPassword = ConvertTo-SecureString -AsPlainText -Force -String 'CHANGEVALUETOSERVICEPRINCIPALPASSWORD'
$Applicationld= 'CHANGEVALUETOSERVICEPRINCIPALID'

$Credential = New-Object -TypeName Svstem.Management.Automation.PSCredential -Argumentlist $Applicationld, $secPassword

Connect-AzAccount -ServicePrincipal -Tenantld 'CHANGEVALUETOTENANTID' -Credential $Credential

$fileContentInBvtes = get-content C:\Users\filedirectory\file.ppk -Encoding Byte

$fileContentAsBase64 = [Svstem.Convert]::ToBase64String($fileContentInBytes)

Set-AzKeyVaultSecret -VaultName 'CHANGEVALUETOKEYVAULTNAME' -SecretName 'CHANGEVALUETOSECRETNAME' -SecretValue (ConvertTo-SecureString -String $fileContentAsBase64 -force -AsPlainText) -ErrorAction Stop
</code>```

Body:
I tried to store my private key to Azure Key Vault, but when I retrieve it out, my private key got changed.

If I put the private key into my web.config file, it works without any issue.

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAohoZ+TCXMn17BPFXFCuIHvh7oONSBNCjuixl2CbwrGO8tIAO
XIQP1sZa3lhXkUj0f4HewmYsx6JR+39Do21H+QtCZxR4qCvOJxrrFHqMrk76aQji
....
ZVmUljOatig+g+q+jMEf7IA5zcAgBdAAuausXrPoNcip89Yuqag1
-----END RSA PRIVATE KEY-----

Since my private key is just a text, I stored it as a Secrets. Am I doing the right thing?

I also tried to store the key as a Certificate, but the key is just a text with hidden CRLN, it is not PEM or PKCS#12. And in my case, I don't need to store the public key.

Below is my code to retrieve the key:

public static string GetDocuSignPrivateKey()
{
    var key = keyVaultClient.GetSecretAsync($"{vaultUrl}secrets/DocuSignPrivateKey/88e15b41234bf89619ddc9a2exxxx").Result;

    return key.Value;
}

Sorry, I just start using Azure KeyVault.  Please help.  Thank you.

Body:
This is how I deployed a private key from a .ppk file to the keyvault using powershell. The first one is in nonproduction where I used AAD MFA, the second one is in production where I used a service principal.

AAD Multifactor Log In

Connect-AzAccount -DeviceCode

$fileContentInBvtes = get-content C:\Users\filedirectory\file.ppk -Encoding Byte
$fileContentAsBase64 = [Svstem.Convert]::ToBase64String($fileContentInBytes)

Set-AzKeyVaultSecret -VaultName 'CHANGEVALUETOKEYVAULTNAME' -SecretName 'CHANGEVALUETOSECRETNAME' -SecretValue (ConvertTo-SecureString -String $fileContentAsBase64 -force -AsPlainText) -ErrorAction Stop

Service Principal

$secPassword = ConvertTo-SecureString -AsPlainText -Force -String 'CHANGEVALUETOSERVICEPRINCIPALPASSWORD'
$Applicationld= 'CHANGEVALUETOSERVICEPRINCIPALID'

$Credential = New-Object -TypeName Svstem.Management.Automation.PSCredential -Argumentlist $Applicationld, $secPassword

Connect-AzAccount -ServicePrincipal -Tenantld 'CHANGEVALUETOTENANTID' -Credential $Credential

$fileContentInBvtes = get-content C:\Users\filedirectory\file.ppk -Encoding Byte

$fileContentAsBase64 = [Svstem.Convert]::ToBase64String($fileContentInBytes)

Set-AzKeyVaultSecret -VaultName 'CHANGEVALUETOKEYVAULTNAME' -SecretName 'CHANGEVALUETOSECRETNAME' -SecretValue (ConvertTo-SecureString -String $fileContentAsBase64 -force -AsPlainText) -ErrorAction Stop


问:
Skipping chunk of a big file with bash
Using bash, how to awk/grep from the middle of a given file and skip 1Gig for instance?  In other words, I don't want awk/grep to search through the first 1Gig of the file but want to start my search in the middle of the file.</p>

答:
You can use dd like this:

```<code># make a 10GB file of zeroes
dd if=/dev/zero bs=1G count=10 > file

# read it, skipping first 9GB and count what you get
dd if=file bs=1G skip=9 | wc -c
1+0 records in
1+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 1.84402 s, 582 MB/s
1073741824
</code>```

Note that I am just demonstrating a concept of how easily you can skip 9GB. In practice, you may prefer to use a 100MB memory buffer and skip 90 of them, rather than allocating a whole GB. So, in practice, you might prefer:

```<code>dd if=file bs=100M skip=90 | wc -c
</code>```

Note also that I am piping to wc rather than awk because my test data is not line oriented - it is just zeros.

Or, if your record size is 30kB and you want to skip a million records and discard diagnostic output:

```<code>dd if=file bs=30K skip=1000000 2> /dev/null | awk ...
</code>```

Note that:

your line numbers will be "wrong" in awk (because awk didn't "see" them), and

your first line may be incomplete (because dd isn't "line oriented")  but I guess that doesn't matter.

Note also, that it is generally very advantageous to use a large block size. So, if you want 8MB, you will do much better with bs=1m count=8 than with bs=8 count=1000000 which will cause a million writes of 8 bytes each.

Note also, that if you like processing very large files, you can get GNU Parallel to divide them up for processing in parallel by multiple subprocesses. So, for example, the following code takes the 10GB file we made at the start and starts 10 parallel jobs counting the bytes in each 1GB chunk:

```<code>parallel -a file --recend "" --pipepart --block 1G wc -c
</code>```

Title: Skipping chunk of a big file with bash

Body:
You can use dd like this:

# make a 10GB file of zeroes
dd if=/dev/zero bs=1G count=10 > file

# read it, skipping first 9GB and count what you get
dd if=file bs=1G skip=9 | wc -c
1+0 records in
1+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 1.84402 s, 582 MB/s
1073741824

Note that I am just demonstrating a concept of how easily you can skip 9GB. In practice, you may prefer to use a 100MB memory buffer and skip 90 of them, rather than allocating a whole GB. So, in practice, you might prefer:

dd if=file bs=100M skip=90 | wc -c

Note also that I am piping to wc rather than awk because my test data is not line oriented - it is just zeros.

Or, if your record size is 30kB and you want to skip a million records and discard diagnostic output:

dd if=file bs=30K skip=1000000 2> /dev/null | awk ...

Note that:

your line numbers will be "wrong" in awk (because awk didn't "see" them), and

your first line may be incomplete (because dd isn't "line oriented")  but I guess that doesn't matter.

Note also, that it is generally very advantageous to use a large block size. So, if you want 8MB, you will do much better with bs=1m count=8 than with bs=8 count=1000000 which will cause a million writes of 8 bytes each.

Note also, that if you like processing very large files, you can get GNU Parallel to divide them up for processing in parallel by multiple subprocesses. So, for example, the following code takes the 10GB file we made at the start and starts 10 parallel jobs counting the bytes in each 1GB chunk:

parallel -a file --recend "" --pipepart --block 1G wc -c


问:
Rewrite ASP.NET page output
A little background: I am trying to create a lightweight cookieless database-backed user session using a highly striped down ASP.NET implementation. This site audience will be mobile users connecting via celluar networks, so the page sizes need to be very small. I am not using the .NET session, viewstate, etc. and most page contain very few if any server controls.

I want to be able to process the output of a page request so I can modify internal links in the response with my own session information. I have read that there was an ISAPI filter to allow cookieless sessions pre-ASP.NET. That is basically what I want to build, just inside the application.

Has anyone done anything like this? I'm already inheiriting the System.Web.UI.Page class for my page base for other reasons. It seems like I should be able to do something from here.

Thanks

答:
HttpModules can give you complete control over your output, but there are also a couple other things you can do that are a little simpler.

Create a custom Filter for the Response.Filter. More or less you create a Stream that you run everything through before sending it onto the underlying stream letting you make your changes there.

Override the render event for the Page and write all your contents to a string and then make your changes there... for example...

.

```<code>//this is from memory, you might need to check it
override void Render(HtmlTextWriter writer) {

StringWriter html = new StringWriter();
HtmlTextWriter render = new HtmlTextWriter(html);
base.Render(render);
string output = html.ToString()

//make your changes to output
//output = ???

writer.Write(output);

}
</code>```

OwnerDisplayName: Paul

ContentLicense: CC BY-SA 2.5

Title: Rewrite ASP.NET page output

Body:
HttpModules can give you complete control over your output, but there are also a couple other things you can do that are a little simpler.

Create a custom Filter for the Response.Filter. More or less you create a Stream that you run everything through before sending it onto the underlying stream letting you make your changes there.

Override the render event for the Page and write all your contents to a string and then make your changes there... for example...

.

//this is from memory, you might need to check it
override void Render(HtmlTextWriter writer) {

StringWriter html = new StringWriter();
HtmlTextWriter render = new HtmlTextWriter(html);
base.Render(render);
string output = html.ToString()

//make your changes to output
//output = ???

writer.Write(output);

}

OwnerDisplayName: HBoss

LastEditorDisplayName: HBoss