问:
How do I get my Generate() method to recognize the values I set in my Password() method?
I have this block:

```<code>public Password2 (int numofSymbols, int numofCap, int numofLow, int numofDigit )throws Exception{
        if(numofSymbols<2||numofCap<2||numofLow<2||numofDigit<2){
        throw new Exception("Settings supplied not accpeted");
    }
    this.numofSymbols=numofSymbols;
    this.numofCap=numofCap;
    this.numofLow=numofLow;
    this.numofDigit=numofDigit;
    System.out.println("New Settings:"+"\n"+"Symbols: "+numofSymbols+"\n"+"Capitals: "+numofCap+"\n"+"Lowercase: "+numofLow+"\n"+"Digits: "+numofDigit);
    }
</code>```

and later I call it with:

```<code>  try{
    Password2 p1= new Password2();
    System.out.print("Default Password:");
    System.out.println(p1.getPassword());
    p1.setPassword();
    System.out.println(p1.getPassword());
  }catch(Exception e){
    System.out.println(e);
}
</code>```

and it works fine but the variables are not saved when I use this method:

```<code>public ArrayList<String> Generate(){
        ArrayList<String> result=new ArrayList<String>();
        Random rand=new Random();
    int count=0;
    while(count<5) {
        String placeholder="";
        int a;

        for(int i=0;i<=numofCap;i++){
            a='Z'+1-'A';
            a=rand.nextInt(a)+'A';
            placeholder+=(char)a;
        }

            for(int i=0;i<=numofLow;i++){
            a='z'+1-'a';
            a=rand.nextInt(a)+'a';
            placeholder+=(char)a;
        }

        for(int i=0;i<=numofDigit;i++){
            a='9'+1-'0';
            a=rand.nextInt(a)+'0';
            placeholder+=(char)a;
        }

        for(int i=0;i<=numofSymbols;i++){
            a=48+1-32;
            a=rand.nextInt(a)+32;
            placeholder+=(char)a;
        }

        if(Consecutive(placeholder)==true){
            continue;
        }
        count++;
        result.add(placeholder);
    }
 // return the ArrayList
        //System.out.println(result);
        return result;
    }
</code>```

Ive tried a few solutions but im just lost. Here is all of my code it is for a project and it is very confusing:

```<code>import java.util.*;
class Password1{
protected static String defaultPassword = "nDay@159";
protected static int length = 8;
protected static int numofSymbols;
protected static int numofCap;
protected static int numofLow;
protected static int numofDigit;
Password1(){
    numofSymbols = 1;
    numofCap = 1;
    numofLow = 1;
    numofDigit = 1;
}
void Password1( int numofSymbols, int numofCap, int numofLow, int numofDigit ){
    Password1.numofSymbols = numofSymbols;
    Password1.numofCap = numofCap;
    Password1.numofLow = numofLow;
    Password1.numofDigit = numofDigit;

}
public boolean validLength(String pass){
    if(pass.length() >= length){
        return true;
    }
    return false;
}
public boolean validSymbols(String pass){
    int count = 0;
    boolean result = false;

    for(int i=0;i<pass.length();i++){
        if(((int)pass.charAt(i) >= 32 && (int)pass.charAt(i) <=47) || ((int)pass.charAt(i) >= 58 && (int)pass.charAt(i) <= 64)){
            count++;
        }
    }if(count >= numofSymbols){
        result = true;
        return result;
    }
    return result;
}
public boolean validnumofDigit(String pass){
    int count = 0;
    boolean result = false;
    for(int i=0;i<pass.length();i++){
        if(((int)pass.charAt(i) >= 48 && (int)pass.charAt(i) <=57)){
            count++;
        }
    }if(count >= numofDigit){
        result = true;
        return result;
    }
    return result;
}
public boolean validCapitals(String pass){
    int count = 0;
    boolean result = false;
    for(int i=0;i<pass.length();i++){
        if(((int)pass.charAt(i) >= 65 && (int)pass.charAt(i) <=90)){
            count++;
        }
    }if(count >= numofCap){
        result = true;
        return result;
    }
    return result;
}
public boolean validnumofLow(String pass){
    int count = 0;
    boolean result = false;
    for(int i=0;i<pass.length();i++){
        if(((int)pass.charAt(i) >= 97 && (int)pass.charAt(i) <=122)){
            count++;
        }
    }
    if(count >= numofLow){
        result = true;
        return result;
    }
    return result;
}
public void setPassword( ){
    String newPassword ;
    boolean assume = true;
    Scanner s = new Scanner(System.in);
    while(assume){
        System.out.println("Please enter a valid password : ");
        newPassword = s.nextLine();
        if(!validLength(newPassword) || !validSymbols(newPassword) || !validCapitals(newPassword) || !validnumofLow(newPassword)|| !validnumofDigit(newPassword) ){
            if(!validLength(newPassword)){
                System.out.println("Password does not contain atleast 8 letters");
            }if(!validSymbols(newPassword)){
                System.out.println("Password does not contain atleast " + numofSymbols + " symbols");
            }if(!validCapitals(newPassword)){
                System.out.println("Password does not contain atleast " + numofCap + " Capitals");
            }if(!validnumofLow(newPassword)){
                System.out.println("Password does not contain atleast " + numofLow + " Lower Cases");
            }if(!validnumofDigit(newPassword)){
                System.out.println("Password does not contain atleast " + numofDigit + " numofDigit");
            }
        }else{
            System.out.print("Password Accepted : ");
            defaultPassword = newPassword;
            assume = false;
        }
        s.close();
    }
}
public String getPassword(){
    return defaultPassword;
}
}
public class Password2 extends Password1{

//Data field to represent minimum length of a passord based on the required settings.

private int minSettings;

/** 2pts
 * Default constructor that calls the superclass constructor with default
 * settings (default settings at least 1 capitals, lowers,numofDigit,....
 * initialize the minSettings using the method actualLength
 */

    Password2(){
    super();

   // call the superclass default constructor
    minSettings=actualLength();
   // set minSettings to the actual min length of a password based on the settings

    }
/** 10pts
    Overloaded constructor
    Make sure to prevent users from supplying settings that are
    invalid settings ( for instance , negative values or 0) or
    extreme cases like requiring more than 3 of (capitals,numofLow,
    symbols,numofDigit) in case, an extreme case supplied,
    print a message that the settings supplied is not acceptable and
    apply the default setting.
 */
    ArrayList<String> result;
    public Password2 (int numofSymbols, int numofCap, int numofLow, int numofDigit )throws Exception{
        if(numofSymbols<2||numofCap<2||numofLow<2||numofDigit<2){
        throw new Exception("Settings supplied not accpeted");
    }
    this.numofSymbols=numofSymbols;
    this.numofCap=numofCap;
    this.numofLow=numofLow;
    this.numofDigit=numofDigit;
    System.out.println("New Settings:"+"\n"+"Symbols: "+numofSymbols+"\n"+"Capitals: "+numofCap+"\n"+"Lowercase: "+numofLow+"\n"+"Digits: "+numofDigit);
    }

/** 5pts
 *   Create a method that checks the actual minimum length based on the
 *   required settings
 *   Use ternary operator
 *   if the addition of settings numbers is less than 8 , then minimum is 8
 *   for instance ( 1 capital, 1 small , 1 symbol, 1 number) = 4 which is less
 *   than the default length required, so minimum in this case 8
 *   if the addition of settings numbers is higher than 8 , then minimum is the
 *   addition of numbers.
 *   @return the actual minimum length of the password
 */

public int actualLength() {
        int passMin=numofCap+numofLow+numofDigit+numofSymbols;
    return(passMin>8)?passMin:8;
    }

/** 10pts
 * There are four methods that are similar to each other in Password1
 * one way to improve in here is to create one method that does their actions
 * take the first method that checks how many symbols and name it to checkRange
 * the method should look like this:
 * public boolean checkRange( String pass,int required, char start,char end)
 * the method will take the range of char to be checked against the required
 * number of the specific type of numofSymbols.
 * This method  will replace the 4 methods in Password1
 * This will reduce the lines of codes significantly.
 *
 * @param pass
 * @param required
 * @param start
 * @param end
 * @return boolean
 */

public boolean checkRange(String pass,int required,char start,char end){
    int count=0;
    boolean result2=false;
    for(int i=0;i<pass.length();i++){
        if(pass.charAt(i)>=start &&pass.charAt(i)<=end){
            count++;
        }if(count>=required){
            result2=true;
            return result2;
            }
    }return result2;
}
public int getValues(){
    return numofSymbols;
}

/** 10pts
 * Override the setPassword method
 * Use the annotation 'override'
 * Print out 4 suggested password based on the settings initialized by the constructor
 * Promote the user to choose from the suggested generated passwords or supply a
 * password that would meet the requirements
 * Prevent consecutive numofSymbols (Use the consecutive method, should be created afterward)
 * use the checkRange method to check the ranges of capital, small, numofDigit, symbols
 * the reset of the method is the same as superclass setPassword
 */
    @Override
public void setPassword(){  // Declare a String to hold a password
    ArrayList<String> pw2= new Password2().Generate();
    System.out.println("Suggested Passwords:"+pw2);

    String Password=defaultPassword;

    // Decalre a scanner object to recive a password from the keyboard

        Scanner scan= new Scanner(System.in);

    // Declare a boolean variable to be set whenever a password meets the settings.

    boolean flag= true;

    // Loop until the user provides a correct password

    while(flag){
            // Promt the user to enter the password based on the settings

            System.out.print("Enter Password based on set settings");

    // scan the next line and store in the String holding the password

        Password=scan.next();

    /* If the password provided is not the actual length required ,
       then print out a message and continue */

        if(Password.length()<actualLength()){
            System.out.println("Password length does not meet setting requrienments");
            continue;
        }

     /* If the password provided does not have the numofCap letters required ,
        then print out a message and continue
        pass to checkRange the range [65 -90] or[ A -Z]  */

            if(!checkRange(Password, numofCap,'A','Z')){
            System.out.println("Not enough numofCap letters");
            continue;
        }

    /* If the password provided does not have the numofLow letters required ,
        then print out a message and continue
        pass to checkRange the range [97 -122] or [a - z]  */

        if(!checkRange(Password, numofLow,'a','z')){
            System.out.println("Not enough numofLow letters");
            continue;
        }

     /* If the password provided does not have the symbols required ,
        then print out a message and continue
        pass to checkRange the range [32 -47] or [ space - /]
       ( no need for this range [58-64])*/

        if(!checkRange(Password, numofSymbols,' ','/')){
            System.out.println("Not enough symbols included");
            continue;
        }

     /* If the password provided does not have the numofDigit required ,
        then print out a message and continue
        pass to checkRange the range   [48 -57] or [0 -9]  */

            if(!checkRange(Password, numofDigit,'0','9')){
            System.out.println("Not enough numofDigit included");
            continue;
        }

     /* If the password provided have consecutive charcters,
        then print out a message and continue
        pass to consecutive the password*/

        if(Consecutive(Password)==true){
            System.out.println("Consecutive numofSymbols are not allowed");
            continue;
        }

    /* Password provided meets all the settings
        set the global variable password to the new qualified password
        set the flag to false, to stop iterations
    */
            flag=false;
        System.out.println("Password Accepted:");
        defaultPassword=Password;

    // end of while loop

        }

}

/**10pts
 * Create a new method that suggests few passwords based on
 * the settings required , you have to use Random class to generate
 * random values of ( numbers, numofSymbols, symbols , numofDigit)
 *
 * The method should generate based on the data fields settings
 * once generated a password, check if there is no consecutive values
 * Store the generated password into an arrayList
 *
 * @return  ArrayList encapsulating 4 generated passwords
 */

    public ArrayList<String> Generate(){
        ArrayList<String> result=new ArrayList<String>();
        Random rand=new Random();
    int count=0;
    while(count<5) {
        String placeholder="";
        int a;
                     // Generate random A-Z

        for(int i=0;i<=numofCap;i++){
            a='Z'+1-'A';
            a=rand.nextInt(a)+'A';
            placeholder+=(char)a;
        }
                    // Generate from a-z

            for(int i=0;i<=numofLow;i++){
            a='z'+1-'a';
            a=rand.nextInt(a)+'a';
            placeholder+=(char)a;
        }
                    // Generate numbers 0-9

        for(int i=0;i<=numofDigit;i++){
            a='9'+1-'0';
            a=rand.nextInt(a)+'0';
            placeholder+=(char)a;
        }
                    // Generate symbols , 1st part 32-48

        for(int i=0;i<=numofSymbols;i++){
            a=48+1-32;
            a=rand.nextInt(a)+32;
            placeholder+=(char)a;
        }
               // If no consecutive , add it to the ArrayList

        if(Consecutive(placeholder)==true){
            continue;
        }
        count++;
        result.add(placeholder);
    }
 // return the ArrayList
        //System.out.println(result);
        return result;
    }

public boolean Consecutive(String pass){
        boolean consecutive=false;
    for(int i=1;i<pass.length();i++){
        if(pass.charAt(i)==pass.charAt(i-1)){
            consecutive=true;
        }
    }  return consecutive;
}
/**public ArrayList getGenerate(){
*   Password2 gen=new Generate();
*   System.out.println("SuggestedPasswords: "+Generate());
*   }
*/
    public static void main(String[] args){

try{
    Password2 p1= new Password2();
    System.out.print("Default Password:");
    System.out.println(p1.getPassword());
    p1.setPassword();
    System.out.println(p1.getPassword());
  }catch(Exception e){
    System.out.println(e);
}

try{
    Password2 p2= new Password2(2,2,2,2);
    p2.setPassword();
    System.out.println(p2.getPassword());
}catch(Exception e){
    System.out.println(e);
}

try{
    Password2 p3= new Password2(3,3,3,3);
    p3.setPassword();
    System.out.println(p3.getPassword());
}catch(Exception e){
    System.out.println(e);
}

/*2pts
Declare an instance of password to have these settings
(0 capitals, 10 symbols, -1 numofDigit,100 small letters)
this settings is an extreme and thus the user
should get a warning message and the default settings applied.
*/
    try{
    Password2 p4= new Password2(10, 0,-1,100);
    p4.setPassword();
    System.out.println(p4.getPassword());
    }catch(Exception e){
    System.out.println(e);
}
}
</code>```

}

```<code></code>```

Body:
I have this block:

public Password2 (int numofSymbols, int numofCap, int numofLow, int numofDigit )throws Exception{
        if(numofSymbols<2||numofCap<2||numofLow<2||numofDigit<2){
        throw new Exception("Settings supplied not accpeted");
    }
    this.numofSymbols=numofSymbols;
    this.numofCap=numofCap;
    this.numofLow=numofLow;
    this.numofDigit=numofDigit;
    System.out.println("New Settings:"+"\n"+"Symbols: "+numofSymbols+"\n"+"Capitals: "+numofCap+"\n"+"Lowercase: "+numofLow+"\n"+"Digits: "+numofDigit);
    }

and later I call it with:

  try{
    Password2 p1= new Password2();
    System.out.print("Default Password:");
    System.out.println(p1.getPassword());
    p1.setPassword();
    System.out.println(p1.getPassword());
  }catch(Exception e){
    System.out.println(e);
}

and it works fine but the variables are not saved when I use this method:

public ArrayList<String> Generate(){
        ArrayList<String> result=new ArrayList<String>();
        Random rand=new Random();
    int count=0;
    while(count<5) {
        String placeholder="";
        int a;

        for(int i=0;i<=numofCap;i++){
            a='Z'+1-'A';
            a=rand.nextInt(a)+'A';
            placeholder+=(char)a;
        }

            for(int i=0;i<=numofLow;i++){
            a='z'+1-'a';
            a=rand.nextInt(a)+'a';
            placeholder+=(char)a;
        }

        for(int i=0;i<=numofDigit;i++){
            a='9'+1-'0';
            a=rand.nextInt(a)+'0';
            placeholder+=(char)a;
        }

        for(int i=0;i<=numofSymbols;i++){
            a=48+1-32;
            a=rand.nextInt(a)+32;
            placeholder+=(char)a;
        }

        if(Consecutive(placeholder)==true){
            continue;
        }
        count++;
        result.add(placeholder);
    }
 // return the ArrayList
        //System.out.println(result);
        return result;
    }

Ive tried a few solutions but im just lost. Here is all of my code it is for a project and it is very confusing:

import java.util.*;
class Password1{
protected static String defaultPassword = "nDay@159";
protected static int length = 8;
protected static int numofSymbols;
protected static int numofCap;
protected static int numofLow;
protected static int numofDigit;
Password1(){
    numofSymbols = 1;
    numofCap = 1;
    numofLow = 1;
    numofDigit = 1;
}
void Password1( int numofSymbols, int numofCap, int numofLow, int numofDigit ){
    Password1.numofSymbols = numofSymbols;
    Password1.numofCap = numofCap;
    Password1.numofLow = numofLow;
    Password1.numofDigit = numofDigit;

}
public boolean validLength(String pass){
    if(pass.length() >= length){
        return true;
    }
    return false;
}
public boolean validSymbols(String pass){
    int count = 0;
    boolean result = false;

    for(int i=0;i<pass.length();i++){
        if(((int)pass.charAt(i) >= 32 && (int)pass.charAt(i) <=47) || ((int)pass.charAt(i) >= 58 && (int)pass.charAt(i) <= 64)){
            count++;
        }
    }if(count >= numofSymbols){
        result = true;
        return result;
    }
    return result;
}
public boolean validnumofDigit(String pass){
    int count = 0;
    boolean result = false;
    for(int i=0;i<pass.length();i++){
        if(((int)pass.charAt(i) >= 48 && (int)pass.charAt(i) <=57)){
            count++;
        }
    }if(count >= numofDigit){
        result = true;
        return result;
    }
    return result;
}
public boolean validCapitals(String pass){
    int count = 0;
    boolean result = false;
    for(int i=0;i<pass.length();i++){
        if(((int)pass.charAt(i) >= 65 && (int)pass.charAt(i) <=90)){
            count++;
        }
    }if(count >= numofCap){
        result = true;
        return result;
    }
    return result;
}
public boolean validnumofLow(String pass){
    int count = 0;
    boolean result = false;
    for(int i=0;i<pass.length();i++){
        if(((int)pass.charAt(i) >= 97 && (int)pass.charAt(i) <=122)){
            count++;
        }
    }
    if(count >= numofLow){
        result = true;
        return result;
    }
    return result;
}
public void setPassword( ){
    String newPassword ;
    boolean assume = true;
    Scanner s = new Scanner(System.in);
    while(assume){
        System.out.println("Please enter a valid password : ");
        newPassword = s.nextLine();
        if(!validLength(newPassword) || !validSymbols(newPassword) || !validCapitals(newPassword) || !validnumofLow(newPassword)|| !validnumofDigit(newPassword) ){
            if(!validLength(newPassword)){
                System.out.println("Password does not contain atleast 8 letters");
            }if(!validSymbols(newPassword)){
                System.out.println("Password does not contain atleast " + numofSymbols + " symbols");
            }if(!validCapitals(newPassword)){
                System.out.println("Password does not contain atleast " + numofCap + " Capitals");
            }if(!validnumofLow(newPassword)){
                System.out.println("Password does not contain atleast " + numofLow + " Lower Cases");
            }if(!validnumofDigit(newPassword)){
                System.out.println("Password does not contain atleast " + numofDigit + " numofDigit");
            }
        }else{
            System.out.print("Password Accepted : ");
            defaultPassword = newPassword;
            assume = false;
        }
        s.close();
    }
}
public String getPassword(){
    return defaultPassword;
}
}
public class Password2 extends Password1{

//Data field to represent minimum length of a passord based on the required settings.

private int minSettings;

/** 2pts
 * Default constructor that calls the superclass constructor with default
 * settings (default settings at least 1 capitals, lowers,numofDigit,....
 * initialize the minSettings using the method actualLength
 */

    Password2(){
    super();

   // call the superclass default constructor
    minSettings=actualLength();
   // set minSettings to the actual min length of a password based on the settings

    }
/** 10pts
    Overloaded constructor
    Make sure to prevent users from supplying settings that are
    invalid settings ( for instance , negative values or 0) or
    extreme cases like requiring more than 3 of (capitals,numofLow,
    symbols,numofDigit) in case, an extreme case supplied,
    print a message that the settings supplied is not acceptable and
    apply the default setting.
 */
    ArrayList<String> result;
    public Password2 (int numofSymbols, int numofCap, int numofLow, int numofDigit )throws Exception{
        if(numofSymbols<2||numofCap<2||numofLow<2||numofDigit<2){
        throw new Exception("Settings supplied not accpeted");
    }
    this.numofSymbols=numofSymbols;
    this.numofCap=numofCap;
    this.numofLow=numofLow;
    this.numofDigit=numofDigit;
    System.out.println("New Settings:"+"\n"+"Symbols: "+numofSymbols+"\n"+"Capitals: "+numofCap+"\n"+"Lowercase: "+numofLow+"\n"+"Digits: "+numofDigit);
    }

/** 5pts
 *   Create a method that checks the actual minimum length based on the
 *   required settings
 *   Use ternary operator
 *   if the addition of settings numbers is less than 8 , then minimum is 8
 *   for instance ( 1 capital, 1 small , 1 symbol, 1 number) = 4 which is less
 *   than the default length required, so minimum in this case 8
 *   if the addition of settings numbers is higher than 8 , then minimum is the
 *   addition of numbers.
 *   @return the actual minimum length of the password
 */

public int actualLength() {
        int passMin=numofCap+numofLow+numofDigit+numofSymbols;
    return(passMin>8)?passMin:8;
    }

/** 10pts
 * There are four methods that are similar to each other in Password1
 * one way to improve in here is to create one method that does their actions
 * take the first method that checks how many symbols and name it to checkRange
 * the method should look like this:
 * public boolean checkRange( String pass,int required, char start,char end)
 * the method will take the range of char to be checked against the required
 * number of the specific type of numofSymbols.
 * This method  will replace the 4 methods in Password1
 * This will reduce the lines of codes significantly.
 *
 * @param pass
 * @param required
 * @param start
 * @param end
 * @return boolean
 */

public boolean checkRange(String pass,int required,char start,char end){
    int count=0;
    boolean result2=false;
    for(int i=0;i<pass.length();i++){
        if(pass.charAt(i)>=start &&pass.charAt(i)<=end){
            count++;
        }if(count>=required){
            result2=true;
            return result2;
            }
    }return result2;
}
public int getValues(){
    return numofSymbols;
}

/** 10pts
 * Override the setPassword method
 * Use the annotation 'override'
 * Print out 4 suggested password based on the settings initialized by the constructor
 * Promote the user to choose from the suggested generated passwords or supply a
 * password that would meet the requirements
 * Prevent consecutive numofSymbols (Use the consecutive method, should be created afterward)
 * use the checkRange method to check the ranges of capital, small, numofDigit, symbols
 * the reset of the method is the same as superclass setPassword
 */
    @Override
public void setPassword(){  // Declare a String to hold a password
    ArrayList<String> pw2= new Password2().Generate();
    System.out.println("Suggested Passwords:"+pw2);

    String Password=defaultPassword;

    // Decalre a scanner object to recive a password from the keyboard

        Scanner scan= new Scanner(System.in);

    // Declare a boolean variable to be set whenever a password meets the settings.

    boolean flag= true;

    // Loop until the user provides a correct password

    while(flag){
            // Promt the user to enter the password based on the settings

            System.out.print("Enter Password based on set settings");

    // scan the next line and store in the String holding the password

        Password=scan.next();

    /* If the password provided is not the actual length required ,
       then print out a message and continue */

        if(Password.length()<actualLength()){
            System.out.println("Password length does not meet setting requrienments");
            continue;
        }

     /* If the password provided does not have the numofCap letters required ,
        then print out a message and continue
        pass to checkRange the range [65 -90] or[ A -Z]  */

            if(!checkRange(Password, numofCap,'A','Z')){
            System.out.println("Not enough numofCap letters");
            continue;
        }

    /* If the password provided does not have the numofLow letters required ,
        then print out a message and continue
        pass to checkRange the range [97 -122] or [a - z]  */

        if(!checkRange(Password, numofLow,'a','z')){
            System.out.println("Not enough numofLow letters");
            continue;
        }

     /* If the password provided does not have the symbols required ,
        then print out a message and continue
        pass to checkRange the range [32 -47] or [ space - /]
       ( no need for this range [58-64])*/

        if(!checkRange(Password, numofSymbols,' ','/')){
            System.out.println("Not enough symbols included");
            continue;
        }

     /* If the password provided does not have the numofDigit required ,
        then print out a message and continue
        pass to checkRange the range   [48 -57] or [0 -9]  */

            if(!checkRange(Password, numofDigit,'0','9')){
            System.out.println("Not enough numofDigit included");
            continue;
        }

     /* If the password provided have consecutive charcters,
        then print out a message and continue
        pass to consecutive the password*/

        if(Consecutive(Password)==true){
            System.out.println("Consecutive numofSymbols are not allowed");
            continue;
        }

    /* Password provided meets all the settings
        set the global variable password to the new qualified password
        set the flag to false, to stop iterations
    */
            flag=false;
        System.out.println("Password Accepted:");
        defaultPassword=Password;

    // end of while loop

        }

}

/**10pts
 * Create a new method that suggests few passwords based on
 * the settings required , you have to use Random class to generate
 * random values of ( numbers, numofSymbols, symbols , numofDigit)
 *
 * The method should generate based on the data fields settings
 * once generated a password, check if there is no consecutive values
 * Store the generated password into an arrayList
 *
 * @return  ArrayList encapsulating 4 generated passwords
 */

    public ArrayList<String> Generate(){
        ArrayList<String> result=new ArrayList<String>();
        Random rand=new Random();
    int count=0;
    while(count<5) {
        String placeholder="";
        int a;
                     // Generate random A-Z

        for(int i=0;i<=numofCap;i++){
            a='Z'+1-'A';
            a=rand.nextInt(a)+'A';
            placeholder+=(char)a;
        }
                    // Generate from a-z

            for(int i=0;i<=numofLow;i++){
            a='z'+1-'a';
            a=rand.nextInt(a)+'a';
            placeholder+=(char)a;
        }
                    // Generate numbers 0-9

        for(int i=0;i<=numofDigit;i++){
            a='9'+1-'0';
            a=rand.nextInt(a)+'0';
            placeholder+=(char)a;
        }
                    // Generate symbols , 1st part 32-48

        for(int i=0;i<=numofSymbols;i++){
            a=48+1-32;
            a=rand.nextInt(a)+32;
            placeholder+=(char)a;
        }
               // If no consecutive , add it to the ArrayList

        if(Consecutive(placeholder)==true){
            continue;
        }
        count++;
        result.add(placeholder);
    }
 // return the ArrayList
        //System.out.println(result);
        return result;
    }

public boolean Consecutive(String pass){
        boolean consecutive=false;
    for(int i=1;i<pass.length();i++){
        if(pass.charAt(i)==pass.charAt(i-1)){
            consecutive=true;
        }
    }  return consecutive;
}
/**public ArrayList getGenerate(){
*   Password2 gen=new Generate();
*   System.out.println("SuggestedPasswords: "+Generate());
*   }
*/
    public static void main(String[] args){

try{
    Password2 p1= new Password2();
    System.out.print("Default Password:");
    System.out.println(p1.getPassword());
    p1.setPassword();
    System.out.println(p1.getPassword());
  }catch(Exception e){
    System.out.println(e);
}

try{
    Password2 p2= new Password2(2,2,2,2);
    p2.setPassword();
    System.out.println(p2.getPassword());
}catch(Exception e){
    System.out.println(e);
}

try{
    Password2 p3= new Password2(3,3,3,3);
    p3.setPassword();
    System.out.println(p3.getPassword());
}catch(Exception e){
    System.out.println(e);
}

/*2pts
Declare an instance of password to have these settings
(0 capitals, 10 symbols, -1 numofDigit,100 small letters)
this settings is an extreme and thus the user
should get a warning message and the default settings applied.
*/
    try{
    Password2 p4= new Password2(10, 0,-1,100);
    p4.setPassword();
    System.out.println(p4.getPassword());
    }catch(Exception e){
    System.out.println(e);
}
}

}


来源: stackexchange

问:
Swimlane ngx-pie-chart pie-label-line not showing issue

When smaller values came in pie chart, label lines are not displayed.
ngx-pie-chart example: The length is 4 comparing the values like(640,100,27,8,4) only the 3 values show in the
pie line label the last two values pie label line not display.

swimlane/ngx-charts version
20.1.0

If anyone knows about this issue kindly help me.

I am expecting the pie label line comes for all the values including smaller values also.

ContentLicense: CC BY-SA 4.0


问:
How to dynamic height set horizontal list view and grid view in flutter?

```<code> /*Grid layout*/

              Container(
                height: 225.h,
                width: double.infinity,
                padding: EdgeInsets.zero,
                child: GridView.builder(
                  scrollDirection: Axis.horizontal,
                  primary: false,
                  shrinkWrap: true,
                  padding: EdgeInsets.only(left: 16.w,top: 8.h,right: 16.w),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      childAspectRatio: 0.5,
                      mainAxisSpacing: 16.0,
                      crossAxisSpacing: 0.0),
                  itemCount: drConsultationModelList.length,
                  itemBuilder: (context, i) {
                    return Container(
                      width: 210.w,
                      margin: EdgeInsets.only(bottom: 15.h),
                      padding: EdgeInsets.only(left: 16.w,bottom: 10.h,right: 20.h,top: 10.h),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12.r),
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            color:
                            Color(0x14000000),
                            offset: const Offset(
                              0.0,
                              4.0,
                            ),
                            blurRadius: 14.0,
                            spreadRadius: 0.0,
                          ), //BoxShadow
                        ],
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        mainAxisSize: MainAxisSize.max,
                        children: [
                          Expanded(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(drConsultationModelList[i].tvTitle,style: TextStyle(fontFamily: fontInterSemibold,fontSize: 15.sp,color: blackes_1a1b25),),
                                SizedBox(height: 6.h,),
                                Text(drConsultationModelList[i].tvSubTitle,style: TextStyle(fontFamily: fontInterRegular,fontSize: 11.sp,color: dark_silver_6a7382),)
                              ],
                            ),
                          ),

                          Stack(
                            alignment: Alignment.center,
                            children: [
                              Container(
                                height: 50.h,width: 50.w,
                                decoration: BoxDecoration(
                                  color: Color(0xffe7f5f0),
                                  borderRadius: BorderRadius.circular(8.r),
                                ),
                              ),
                              SvgPicture.asset(drConsultationModelList[i].imgLogo,width: 34.w,height: 34.h,fit: BoxFit.fill,),
                            ],
                          )
                        ],
                      ),
                    );
                  },
                ),
              ),

</code>```

I used container fixed height but I am trying to set dynamic height so please give me proper suggestion.

Now the problem is that, to show layout in listview I have to pass fixed height in sizebox. If I remove height then layout will be gone. So, How do I display item layout without giving fixed height in sizebox.

Fixed height problem issued when we increased device default font size. So, cant fixed layout height. Plz give solution, Thanks in advance

Body:
 /*Grid layout*/

              Container(
                height: 225.h,
                width: double.infinity,
                padding: EdgeInsets.zero,
                child: GridView.builder(
                  scrollDirection: Axis.horizontal,
                  primary: false,
                  shrinkWrap: true,
                  padding: EdgeInsets.only(left: 16.w,top: 8.h,right: 16.w),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      childAspectRatio: 0.5,
                      mainAxisSpacing: 16.0,
                      crossAxisSpacing: 0.0),
                  itemCount: drConsultationModelList.length,
                  itemBuilder: (context, i) {
                    return Container(
                      width: 210.w,
                      margin: EdgeInsets.only(bottom: 15.h),
                      padding: EdgeInsets.only(left: 16.w,bottom: 10.h,right: 20.h,top: 10.h),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12.r),
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            color:
                            Color(0x14000000),
                            offset: const Offset(
                              0.0,
                              4.0,
                            ),
                            blurRadius: 14.0,
                            spreadRadius: 0.0,
                          ), //BoxShadow
                        ],
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        mainAxisSize: MainAxisSize.max,
                        children: [
                          Expanded(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(drConsultationModelList[i].tvTitle,style: TextStyle(fontFamily: fontInterSemibold,fontSize: 15.sp,color: blackes_1a1b25),),
                                SizedBox(height: 6.h,),
                                Text(drConsultationModelList[i].tvSubTitle,style: TextStyle(fontFamily: fontInterRegular,fontSize: 11.sp,color: dark_silver_6a7382),)
                              ],
                            ),
                          ),

                          Stack(
                            alignment: Alignment.center,
                            children: [
                              Container(
                                height: 50.h,width: 50.w,
                                decoration: BoxDecoration(
                                  color: Color(0xffe7f5f0),
                                  borderRadius: BorderRadius.circular(8.r),
                                ),
                              ),
                              SvgPicture.asset(drConsultationModelList[i].imgLogo,width: 34.w,height: 34.h,fit: BoxFit.fill,),
                            ],
                          )
                        ],
                      ),
                    );
                  },
                ),
              ),

I used container fixed height but I am trying to set dynamic height so please give me proper suggestion.

Now the problem is that, to show layout in listview I have to pass fixed height in sizebox. If I remove height then layout will be gone. So, How do I display item layout without giving fixed height in sizebox.

Fixed height problem issued when we increased device default font size. So, cant fixed layout height. Plz give solution, Thanks in advance


问:
How to use SPIto communicate with a AD7705 on raspberry PICO?
I connect the CS to GND, so there's no cs set in code.

code

spi = SoftSPI(baudrate=100_000, polarity=1, phase=1, bits=8, sck=Pin(18), mosi=Pin(16), miso=Pin(19))

dr = machine.Pin(21, machine.Pin.IN, Pin.PULL_UP)
# 0010 0000 select clock register
spi.write(b'0x20')
utime.sleep_ms(10)

# 0000 1100 for 4.9152MHz
spi.write(b'0x0c')
utime.sleep_ms(10)

# 0001 0000 select setup register
spi.write(b'0x10')
utime.sleep_ms(10)

# 0100 0010 self-calibration and gain=1
spi.write(b'0x42')
utime.sleep_ms(10)

# 0000 1000 request read
spi.write(b'0x08')
utime.sleep_ms(10)

for i in range(10):
    spi.write(b'0x38') # select data register

    # pass if not ready.
    while dr.value() != 0:
        pass

    data = spi.read(2)
    print(int(data.hex(),16))

    utime.sleep_ms(1)
```

The drdy is always 1，the code unable to read the correct data.
Please let me know where are errors in the code.
Thanks in advandce!

Body:
I connect the CS to GND, so there's no cs set in code.

code

spi = SoftSPI(baudrate=100_000, polarity=1, phase=1, bits=8, sck=Pin(18), mosi=Pin(16), miso=Pin(19))

dr = machine.Pin(21, machine.Pin.IN, Pin.PULL_UP)
# 0010 0000 select clock register
spi.write(b'0x20')
utime.sleep_ms(10)

# 0000 1100 for 4.9152MHz
spi.write(b'0x0c')
utime.sleep_ms(10)

# 0001 0000 select setup register
spi.write(b'0x10')
utime.sleep_ms(10)

# 0100 0010 self-calibration and gain=1
spi.write(b'0x42')
utime.sleep_ms(10)

# 0000 1000 request read
spi.write(b'0x08')
utime.sleep_ms(10)

for i in range(10):
    spi.write(b'0x38') # select data register

    # pass if not ready.
    while dr.value() != 0:
        pass

    data = spi.read(2)
    print(int(data.hex(),16))

    utime.sleep_ms(1)

The drdy is always 1，the code unable to read the correct data.
Please let me know where are errors in the code.
Thanks in advandce!


问:
My axios refresh token is success but after token is refreshed it wont refetch the failed request
So i have made use of axios interceptors to detect for 401 error and tried to refetch the access_token. I did it but after the token is refreshed it wont re-request the failed task.

Here is my response interceptor code.

```<code>/**
 * Axios Response Handler
 */
loggedAxios.interceptors.response.use(
  (response) =>
    new Promise((resolve, reject) => {
      resolve(response);
    }),
  (error) => {
    const originalConfig = error.config;
    let auths = JSON.parse(localStorage.getItem("htAuth"));

    // Access Token was expired
    if (error?.response?.status === 401 && auths !== undefined && loop < 1) {
      //Refresh token
      let rtkn = localStorage.getItem("rTkn");

      if (!isRefreshing) {
        loop++;
        isRefreshing = true;
        return new Promise(function (resolve, reject) {
          let payload = {
            refresh: rtkn,
          };
          refreshTokenApi(payload) //Getting new access token
            .then((res) => {
              loggedAxios.defaults.headers.common["Authorization"] =
                "Bearer " + res.data?.access;
              originalConfig.headers["Authorization"] =
                "Bearer " + res.data?.access;
              onRrefreshed(res.data?.access);
              resolve(loggedAxios(originalConfig));
              auths.token = res.data?.access;
              // localStorage.setItem("rTkn", res.data?.access); //Setting new rTkn
              localStorage.setItem("htAuth", JSON.stringify(auths)); //Updating user with new access token
              failedQueue = [];
            })
            .catch((error) => {
              reject(error);
            })
            .finally(() => {
              isRefreshing = false;
            });
        });
      }

      return new Promise((resolve) => {
        subscribeTokenRefresh((token) => {
          originalConfig.headers.Authorization = `Bearer ${token}`;
          resolve(axios(originalConfig));
        });
      });
    }
    return Promise.reject(error);
  }
);
</code>```

I tried a lot but i am really frustrated cause I am waiting 20min for the token to expire and recheck. Please save my day.

Body:
So i have made use of axios interceptors to detect for 401 error and tried to refetch the access_token. I did it but after the token is refreshed it wont re-request the failed task.

Here is my response interceptor code.

/**
 * Axios Response Handler
 */
loggedAxios.interceptors.response.use(
  (response) =>
    new Promise((resolve, reject) => {
      resolve(response);
    }),
  (error) => {
    const originalConfig = error.config;
    let auths = JSON.parse(localStorage.getItem("htAuth"));

    // Access Token was expired
    if (error?.response?.status === 401 && auths !== undefined && loop < 1) {
      //Refresh token
      let rtkn = localStorage.getItem("rTkn");

      if (!isRefreshing) {
        loop++;
        isRefreshing = true;
        return new Promise(function (resolve, reject) {
          let payload = {
            refresh: rtkn,
          };
          refreshTokenApi(payload) //Getting new access token
            .then((res) => {
              loggedAxios.defaults.headers.common["Authorization"] =
                "Bearer " + res.data?.access;
              originalConfig.headers["Authorization"] =
                "Bearer " + res.data?.access;
              onRrefreshed(res.data?.access);
              resolve(loggedAxios(originalConfig));
              auths.token = res.data?.access;
              // localStorage.setItem("rTkn", res.data?.access); //Setting new rTkn
              localStorage.setItem("htAuth", JSON.stringify(auths)); //Updating user with new access token
              failedQueue = [];
            })
            .catch((error) => {
              reject(error);
            })
            .finally(() => {
              isRefreshing = false;
            });
        });
      }

      return new Promise((resolve) => {
        subscribeTokenRefresh((token) => {
          originalConfig.headers.Authorization = `Bearer ${token}`;
          resolve(axios(originalConfig));
        });
      });
    }
    return Promise.reject(error);
  }
);

I tried a lot but i am really frustrated cause I am waiting 20min for the token to expire and recheck. Please save my day.


问:
STM32 Cube IDE Execute Command in Linux
I have installed STM32 Cube IDE in wsl.

So I'm trying to run it as a command in the terminal, but I don't know how to do it.

I need some help.

I connected to wsl with a virtual desktop screen and ran stm32cubeide, but it works without any problems.

However, I don't know about running it in terminal.

Title: STM32 Cube IDE Execute Command in Linux


问:
Expo build android failed React native
I am not able to generate the internal apk since the expo SDK 47 update occurred, I get an error installing dependencies on some occasions and in Run gradlew.

I show the error in installation of dependencies:

```<code>Running "npm install" in the root dir of your repository 2[stderr] npm ERR!3[stderr] code ERESOLVE4[stderr] npm ERR! ERESOLVE could not resolve5[stderr] npm ERR! 6[stderr] npm ERR! While resolving: react-navigation-tabs@2.11.27[stderr] npm ERR! Found: react-native-gesture-handler@2.8.08[stderr] npm ERR! node_modules/react-native-gesture-handler9[stderr] npm ERR!   react-native-gesture-handler@"~2.8.0" from the root project10[stderr] npm ERR!   peer react-native-gesture-handler@">= 1.0.0" from @react-navigation/stack@6.3.711[stderr] npm ERR!   node_modules/@react-navigation/stack12[stderr] npm ERR!     @react-navigation/stack@"^6.3.2" from the root project13[stderr] npm ERR!   1 more (react-native-tab-view)14[stderr] npm ERR! 15[stderr] npm ERR! Could not resolve dependency:16[stderr] npm ERR! peer react-native-gesture-handler@"^1.0.0" from react-navigation-tabs@2.11.217[stderr] npm ERR! node_modules/react-navigation-tabs18[stderr] npm ERR!   react-navigation-tabs@"^2.11.2" from the root project19[stderr] npm ERR! 20[stderr] npm ERR! Conflicting peer dependency: react-native-gesture-handler@1.10.321[stderr] npm ERR! node_modules/react-native-gesture-handler22[stderr] npm ERR!   peer react-native-gesture-handler@"^1.0.0" from react-navigation-tabs@2.11.223[stderr] npm ERR!   node_modules/react-navigation-tabs24[stderr] npm ERR!     react-navigation-tabs@"^2.11.2" from the root project25[stderr] npm ERR! 26[stderr] npm ERR! Fix the upstream dependency conflict, or retry27[stderr] npm ERR! this command with --force, or --legacy-peer-deps28[stderr] npm ERR! to accept an incorrect (and potentially broken) dependency resolution.29[stderr] npm ERR! 30[stderr] npm ERR! See /home/expo/.npm/eresolve-report.txt for a full report.31[stderr] 32[stderr] npm ERR! A complete log of this run can be found in:33[stderr] npm ERR!     /home/expo/.npm/_logs/2022-12-09T04_28_24_722Z-debug-0.log34npm exited with non-zero code: 1
</code>```

I show the error in "Run gradlew":

delete the package-lock.json file, delete the node_modules folder, npm cache clean --force, npm cache verify and install npm install again

Title: Expo build android failed React native

Body:
I am not able to generate the internal apk since the expo SDK 47 update occurred, I get an error installing dependencies on some occasions and in Run gradlew.

I show the error in installation of dependencies:

Running "npm install" in the root dir of your repository 2[stderr] npm ERR!3[stderr] code ERESOLVE4[stderr] npm ERR! ERESOLVE could not resolve5[stderr] npm ERR! 6[stderr] npm ERR! While resolving: react-navigation-tabs@2.11.27[stderr] npm ERR! Found: react-native-gesture-handler@2.8.08[stderr] npm ERR! node_modules/react-native-gesture-handler9[stderr] npm ERR!   react-native-gesture-handler@"~2.8.0" from the root project10[stderr] npm ERR!   peer react-native-gesture-handler@">= 1.0.0" from @react-navigation/stack@6.3.711[stderr] npm ERR!   node_modules/@react-navigation/stack12[stderr] npm ERR!     @react-navigation/stack@"^6.3.2" from the root project13[stderr] npm ERR!   1 more (react-native-tab-view)14[stderr] npm ERR! 15[stderr] npm ERR! Could not resolve dependency:16[stderr] npm ERR! peer react-native-gesture-handler@"^1.0.0" from react-navigation-tabs@2.11.217[stderr] npm ERR! node_modules/react-navigation-tabs18[stderr] npm ERR!   react-navigation-tabs@"^2.11.2" from the root project19[stderr] npm ERR! 20[stderr] npm ERR! Conflicting peer dependency: react-native-gesture-handler@1.10.321[stderr] npm ERR! node_modules/react-native-gesture-handler22[stderr] npm ERR!   peer react-native-gesture-handler@"^1.0.0" from react-navigation-tabs@2.11.223[stderr] npm ERR!   node_modules/react-navigation-tabs24[stderr] npm ERR!     react-navigation-tabs@"^2.11.2" from the root project25[stderr] npm ERR! 26[stderr] npm ERR! Fix the upstream dependency conflict, or retry27[stderr] npm ERR! this command with --force, or --legacy-peer-deps28[stderr] npm ERR! to accept an incorrect (and potentially broken) dependency resolution.29[stderr] npm ERR! 30[stderr] npm ERR! See /home/expo/.npm/eresolve-report.txt for a full report.31[stderr] 32[stderr] npm ERR! A complete log of this run can be found in:33[stderr] npm ERR!     /home/expo/.npm/_logs/2022-12-09T04_28_24_722Z-debug-0.log34npm exited with non-zero code: 1

I show the error in "Run gradlew":

delete the package-lock.json file, delete the node_modules folder, npm cache clean --force, npm cache verify and install npm install again


问:
Trying to create a simple python script. Keep getting errors
This is my first time posting here so i apologize if i have not posted in the correct format!

```<code>
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('drive', 'v3', credentials=creds)

        # Call the Drive v3 API
        results = service.files().list(
            pageSize=10, fields="nextPageToken, files(id, name)").execute()
        items = results.get('files', [])

        if not items:
            print('No files found.')
            return
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))
    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')

if __name__ == '__main__':
    main()
</code>```

I'm trying to create a simple python script that does the following.

1.Import the necessary Libraries.

2.Connect/Authenticate to Google drive.

3.Check a folder on google drive for file names and then upload all files that are not on the drive yet from a
specific folder on computer to the checked folder on google drive.

4.repeat every hour, If no new files found then restart loop.

this is what i tried so far but i get errors when running the script, The issue is it cannot find the credentials.json file.

The credentials.json file is in the same folder as the settings.yaml and the Setup.py

I was expecting to be directed to a login page when running the script.

To be fair i know very very little about python and the most experience i have with coding would be from my old modded minecraft days using lua. on computercraft. hahah thanks for your help in advance.**

Body:
This is my first time posting here so i apologize if i have not posted in the correct format!

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('drive', 'v3', credentials=creds)

        # Call the Drive v3 API
        results = service.files().list(
            pageSize=10, fields="nextPageToken, files(id, name)").execute()
        items = results.get('files', [])

        if not items:
            print('No files found.')
            return
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))
    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')

if __name__ == '__main__':
    main()

I'm trying to create a simple python script that does the following.

1.Import the necessary Libraries.

2.Connect/Authenticate to Google drive.

3.Check a folder on google drive for file names and then upload all files that are not on the drive yet from a
specific folder on computer to the checked folder on google drive.

4.repeat every hour, If no new files found then restart loop.

this is what i tried so far but i get errors when running the script, The issue is it cannot find the credentials.json file.

The credentials.json file is in the same folder as the settings.yaml and the Setup.py

I was expecting to be directed to a login page when running the script.

To be fair i know very very little about python and the most experience i have with coding would be from my old modded minecraft days using lua. on computercraft. hahah thanks for your help in advance.**


问:
Tkinter - UI gets broken when draw a big scrollable canvas
I'm working on a text clustering app and there's a screen showing all the clusters. I've learned to make scrollable lists of widgets from other questions. Each cluster is scrollable and the whole grid is also scrollable. When the app works, it looks like this:

When users adjust the slider, the clusters are updated, all the scrollable lists are destroyed and new clusters are drawn. However, after 3 or 4 times adjusting the slider, the UI gets broken and being drawn all over my desktop screen. Please let me know if I've missed something?

Here's the class for scrolling, other views just extend this class:

```<code>from typing import List
import platform
import tkinter as tk
from tkinter import ttk
from tksheet._tksheet_vars import *

class ScrollFrame(tk.Frame):
    def __init__(self, parent, bg="white", **kwargs):
        super().__init__(parent, bg=bg, borderwidth=0,  **kwargs)

        self.canvas = tk.Canvas(self, bg=bg, borderwidth=0)
        self.viewPort = tk.Frame(self.canvas, bg=bg, borderwidth=0)

        self.canvas.pack(side="left", fill="both", expand=True)
        self.canvas_window = self.canvas.create_window(
                (0,0),
                window=self.viewPort, anchor="nw",tags="self.viewPort")

        self.viewPort.bind("<Configure>", self.onFrameConfigure)
        self.canvas.bind("<Configure>", self.onCanvasConfigure)

        self.viewPort.bind('<Enter>', self.onEnter)
        self.viewPort.bind('<Leave>', self.onLeave)

        self.onFrameConfigure(None)

    def destroy(self):
        self.canvas.delete("alll")
        super().destroy()
        # self.destroy()

    def onFrameConfigure(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def onCanvasConfigure(self, event):
        canvas_width = event.width
        self.canvas.itemconfig(self.canvas_window, width = canvas_width)

    def onMouseWheel(self, event):
        if platform.system() == 'Windows':
            self.canvas.yview_scroll(int(-1* (event.delta/120)), "units")
        elif platform.system() == 'Darwin':
            self.canvas.yview_scroll(int(-1 * event.delta), "units")
        else:
            if event.num == 4:
                self.canvas.yview_scroll( -1, "units" )
            elif event.num == 5:
                self.canvas.yview_scroll( 1, "units" )

    def onEnter(self, event):
        if platform.system() == 'Linux':
            self.canvas.bind_all("<Button-4>", self.onMouseWheel)
            self.canvas.bind_all("<Button-5>", self.onMouseWheel)
        else:
            self.canvas.bind_all("<MouseWheel>", self.onMouseWheel)

    def onLeave(self, event):
        if platform.system() == 'Linux':
            self.canvas.unbind_all("<Button-4>")
            self.canvas.unbind_all("<Button-5>")
        else:
            self.canvas.unbind_all("<MouseWheel>")

    def scroll_to(self, fraction=1):
        self.canvas.yview_moveto(fraction)
</code>```

Here're classes for each text item and clusters:

```<code>class TextItem(tk.Frame):
    def __init__(
            self,
            master,
            idx:int,
            text:str,
            selectable = False,
            selected=True,
            bg="white",
            on_item_selected=None,
            **kwds
        ):
            tk.Frame.__init__(self, master, bg=bg, borderwidth=0, **kwds)
            self.__text = text
            self.__select_var = tk.BooleanVar()
            self.__select_var.set(selected)
            self.grid_rowconfigure(0, weight=1)
            self.grid_columnconfigure(1, weight=1)

            if selectable:
                self.check = tk.Checkbutton(
                        self,
                        anchor='e',
                        text=self.__text,
                        variable=self.__select_var,
                        bg=bg,
                        fg=theme_light_blue["header_fg"],
                        command=on_item_selected
                    )
                self.check.grid(row=0, column=1, sticky='e')
            else:
                self.idx = tk.Label(
                    self,
                    text=str(idx),
                    bg=bg,
                    fg="#728494"
                ).grid(row=0, column=0, sticky='e')
                self.check = tk.Label(
                        self,
                        anchor='e',
                        text=self.__text,
                        bg=bg,
                        fg=theme_light_blue["header_fg"]
                    )
                self.check.grid(row=0, column=1, sticky='e')

    @property
    def is_selected(self):
        return self.__select_var.get()

class Cluster():
    def __init__(self, id:int, samples: List[str],) -> None:
        self.__samples = samples
        self.__id = id

    @property
    def samples(self):
        return self.__samples

    @property
    def id(self):
        return self.__id

class ClusterFrame(tk.Frame):
    def __init__(
        self,
        root,
        cluster: Cluster,
        bg="white",
        selectable=False,
        selecteds=None,
        title=None,
        **kwds
        ):
            tk.Frame.__init__(self, root, bg=bg, **kwds)
            self.__wrapper = tk.Frame(
                self,
                highlightbackground = theme_light_blue["index_border_fg"],
                highlightthickness=0.5, bg=bg
            )
            self.__selectable = selectable
            self.__cluster = cluster
            if not title:
                title = f"Cluster {cluster.id}: { len(cluster.samples)} samples"
            self.__title_label = tk.Label(self.__wrapper, text = title)
            self.__title_label.pack(side="top", fill="both")
            if self.__selectable:
                self.__selection_status = tk.Label(self.__wrapper, text = "Selected: ")
                self.__selection_status.pack(side="top", fill="both")

            self.scrollFrame = ScrollFrame(self.__wrapper)
            if not selecteds:
                selecteds = [True] * len(cluster.samples)
            # self.__selected_count = selecteds.sum()
            self.__view_items = []
            for idx, sample in enumerate(cluster.samples):
                item = TextItem(
                    self.scrollFrame.viewPort,
                    idx + 1,
                    sample,
                    selected=selecteds[idx],
                    selectable=self.__selectable,
                    on_item_selected=self.update_selected_status
                )
                item.grid(row=idx, column=0, sticky='w', padx=1, pady=1)
                self.__view_items.append(item)

            self.scrollFrame.pack(side="top", fill="both", expand=True)
            self.__wrapper.pack( fill="both", expand=True)
            if self.__selectable:
                self.update_selected_status()

    def get_selected_samples(self):
        return [self.__cluster.samples[idx] for idx, item in enumerate(self.__view_items) if item.is_selected]

    def update_selected_status(self):
        selected_count = len(self.get_selected_samples())
        self.__selection_status.config(text=f"Selected: {selected_count}")

    def scroll_to(self, fraction=1):
        self.scrollFrame.scroll_to(fraction)
</code>```

Here's the code for the grid view.

class ClusterGrid(tk.Frame):
def init(self, root,  clusters, num_cols=3, **kwargs):
super().init(root, bg="white", **kwargs)

```<code>    # main_frame = tk.Frame(root)
    self.__num_cols = num_cols
    self.__clusters = clusters

    self.__main_canvas = tk.Canvas(self, borderwidth=0)
    self.__main_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

    main_scrbar = ttk.Scrollbar(
        self,
        orient=tk.VERTICAL,
        command=self.__main_canvas.yview
    )
    main_scrbar.pack(side=tk.RIGHT, fill=tk.Y)

    self.__main_canvas.configure(yscrollcommand=main_scrbar.set)
    # self.main_canvas.bind('<Configure>', lambda e: self.main_canvas.configure(scrollregion=self.main_canvas.bbox("all")))

    self.__scroll_frame = tk.Frame(self.__main_canvas, bg="white")
    self.__canvas_window = self.__main_canvas.create_window((0,0), window=self.__scroll_frame, anchor="nw")

    self.__scroll_frame.bind("<Configure>", self.onFrameConfigure)
    self.__main_canvas.bind("<Configure>", self.onCanvasConfigure)

    self.__scroll_frame.bind('<Enter>', self.onEnter)
    self.__scroll_frame.bind('<Leave>', self.onLeave)

    for i, intent in enumerate(self.__clusters[:30]):
        col = i % self.__num_cols
        row = int(i/self.__num_cols)
        sc = ClusterFrame(self.__scroll_frame, intent, selectable=True)
        sc.grid(row=row, column=col, sticky='nsew', padx=5, pady=5)

    self.onFrameConfigure(None)

def destroy(self):
    self.__main_canvas.delete("all")
    super().destroy()

def onFrameConfigure(self, event):
    '''Reset the scroll region to encompass the inner frame'''
    # print("ScrollFrame: onFrameConfigure")
    self.__main_canvas.configure(scrollregion=self.__main_canvas.bbox("all"))

def onCanvasConfigure(self, event):
    '''Reset the canvas window to encompass inner frame when required'''
    # print("ScrollFrame: onCanvasConfigure")
    canvas_width = event.width
    self.__main_canvas.itemconfig(self.__canvas_window, width = canvas_width)

def onEnter(self, event):
    print("ScrollFrame: onEnter")
    if platform.system() == 'Linux':
        self.__main_canvas.bind_all("<Button-4>", self.onMouseWheel)
        self.__main_canvas.bind_all("<Button-5>", self.onMouseWheel)
    else:
        self.__main_canvas.bind_all("<MouseWheel>", self.onMouseWheel)

def onMouseWheel(self, event):
    # print("ScrollFrame: onMouseWheel")
    if platform.system() == 'Windows':
        self.__main_canvas.yview_scroll(int(-1* (event.delta/120)), "units")
    elif platform.system() == 'Darwin':
        self.__main_canvas.yview_scroll(int(-1 * event.delta), "units")
    else:
        if event.num == 4:
            self.__main_canvas.yview_scroll( -1, "units" )
        elif event.num == 5:
            self.__main_canvas.yview_scroll( 1, "units" )

def onLeave(self, event):
    print("ScrollFrame: onLeave")
    if platform.system() == 'Linux':
        self.__main_canvas.unbind_all("<Button-4>")
        self.__main_canvas.unbind_all("<Button-5>")
    else:
        self.__main_canvas.unbind_all("<MouseWheel>")

def destroy(self) -> None:
    # self.__main_canvas.delete("all")
    return super().destroy()
</code>```

Finally the code for inflating the gridview.

```<code>import random
from threading import Timer
from tkinter import *
from scrollable_frames import ClusterGrid, Cluster

def clear_grid(view):
    print("clear_grid: ", view)
    if not view:
        return
    for widget in view.winfo_children():
        print("widget: ", widget)
        widget.destroy()

def on_slider_change(new_val, root):
    global slider_timer
    print("new_val: ", new_val)
    if slider_timer:
        slider_timer.cancel()
        print("cancelled")
    slider_timer = Timer(2, process, args=(new_val, root,))
    slider_timer.start()

def process(val, root):
    global intent_grid
    print("process...", val, intent_grid)

    print(val)
    clear_grid(intent_grid)
    clusters = []
    for i in range(100):
        samples = [ f"This is a sample text {i}" for i in range(100)]
        cl = Cluster(i, samples=samples)
        clusters.append(cl)
    intent_grid = ClusterGrid(root, clusters=clusters)
    intent_grid.grid(column=0, row=1, sticky="nsew")

root=Tk()
root.geometry("900x600")
intent_grid = None

root.columnconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)

slider_timer = None
threshold_slider_val = DoubleVar(value=0.6)
threshold_slider = Scale(
        root,
        from_= 0.3,
        to=1,
        resolution=0.05,
        orient=HORIZONTAL,
        variable=threshold_slider_val,
        command=lambda x: on_slider_change(new_val=x, root=root)
    )
threshold_slider.grid(column=0, row=0, pady=20)
root.mainloop()
</code>```

I know drawing all elements on the canvas is not cool. Is there any way to just draw what're visible? Thank you so much in advance.

Body:
I'm working on a text clustering app and there's a screen showing all the clusters. I've learned to make scrollable lists of widgets from other questions. Each cluster is scrollable and the whole grid is also scrollable. When the app works, it looks like this:

When users adjust the slider, the clusters are updated, all the scrollable lists are destroyed and new clusters are drawn. However, after 3 or 4 times adjusting the slider, the UI gets broken and being drawn all over my desktop screen. Please let me know if I've missed something?

Here's the class for scrolling, other views just extend this class:

from typing import List
import platform
import tkinter as tk
from tkinter import ttk
from tksheet._tksheet_vars import *

class ScrollFrame(tk.Frame):
    def __init__(self, parent, bg="white", **kwargs):
        super().__init__(parent, bg=bg, borderwidth=0,  **kwargs)

        self.canvas = tk.Canvas(self, bg=bg, borderwidth=0)
        self.viewPort = tk.Frame(self.canvas, bg=bg, borderwidth=0)

        self.canvas.pack(side="left", fill="both", expand=True)
        self.canvas_window = self.canvas.create_window(
                (0,0),
                window=self.viewPort, anchor="nw",tags="self.viewPort")

        self.viewPort.bind("<Configure>", self.onFrameConfigure)
        self.canvas.bind("<Configure>", self.onCanvasConfigure)

        self.viewPort.bind('<Enter>', self.onEnter)
        self.viewPort.bind('<Leave>', self.onLeave)

        self.onFrameConfigure(None)

    def destroy(self):
        self.canvas.delete("alll")
        super().destroy()
        # self.destroy()

    def onFrameConfigure(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def onCanvasConfigure(self, event):
        canvas_width = event.width
        self.canvas.itemconfig(self.canvas_window, width = canvas_width)

    def onMouseWheel(self, event):
        if platform.system() == 'Windows':
            self.canvas.yview_scroll(int(-1* (event.delta/120)), "units")
        elif platform.system() == 'Darwin':
            self.canvas.yview_scroll(int(-1 * event.delta), "units")
        else:
            if event.num == 4:
                self.canvas.yview_scroll( -1, "units" )
            elif event.num == 5:
                self.canvas.yview_scroll( 1, "units" )

    def onEnter(self, event):
        if platform.system() == 'Linux':
            self.canvas.bind_all("<Button-4>", self.onMouseWheel)
            self.canvas.bind_all("<Button-5>", self.onMouseWheel)
        else:
            self.canvas.bind_all("<MouseWheel>", self.onMouseWheel)

    def onLeave(self, event):
        if platform.system() == 'Linux':
            self.canvas.unbind_all("<Button-4>")
            self.canvas.unbind_all("<Button-5>")
        else:
            self.canvas.unbind_all("<MouseWheel>")

    def scroll_to(self, fraction=1):
        self.canvas.yview_moveto(fraction)

Here're classes for each text item and clusters:

class TextItem(tk.Frame):
    def __init__(
            self,
            master,
            idx:int,
            text:str,
            selectable = False,
            selected=True,
            bg="white",
            on_item_selected=None,
            **kwds
        ):
            tk.Frame.__init__(self, master, bg=bg, borderwidth=0, **kwds)
            self.__text = text
            self.__select_var = tk.BooleanVar()
            self.__select_var.set(selected)
            self.grid_rowconfigure(0, weight=1)
            self.grid_columnconfigure(1, weight=1)

            if selectable:
                self.check = tk.Checkbutton(
                        self,
                        anchor='e',
                        text=self.__text,
                        variable=self.__select_var,
                        bg=bg,
                        fg=theme_light_blue["header_fg"],
                        command=on_item_selected
                    )
                self.check.grid(row=0, column=1, sticky='e')
            else:
                self.idx = tk.Label(
                    self,
                    text=str(idx),
                    bg=bg,
                    fg="#728494"
                ).grid(row=0, column=0, sticky='e')
                self.check = tk.Label(
                        self,
                        anchor='e',
                        text=self.__text,
                        bg=bg,
                        fg=theme_light_blue["header_fg"]
                    )
                self.check.grid(row=0, column=1, sticky='e')

    @property
    def is_selected(self):
        return self.__select_var.get()

class Cluster():
    def __init__(self, id:int, samples: List[str],) -> None:
        self.__samples = samples
        self.__id = id

    @property
    def samples(self):
        return self.__samples

    @property
    def id(self):
        return self.__id

class ClusterFrame(tk.Frame):
    def __init__(
        self,
        root,
        cluster: Cluster,
        bg="white",
        selectable=False,
        selecteds=None,
        title=None,
        **kwds
        ):
            tk.Frame.__init__(self, root, bg=bg, **kwds)
            self.__wrapper = tk.Frame(
                self,
                highlightbackground = theme_light_blue["index_border_fg"],
                highlightthickness=0.5, bg=bg
            )
            self.__selectable = selectable
            self.__cluster = cluster
            if not title:
                title = f"Cluster {cluster.id}: { len(cluster.samples)} samples"
            self.__title_label = tk.Label(self.__wrapper, text = title)
            self.__title_label.pack(side="top", fill="both")
            if self.__selectable:
                self.__selection_status = tk.Label(self.__wrapper, text = "Selected: ")
                self.__selection_status.pack(side="top", fill="both")

            self.scrollFrame = ScrollFrame(self.__wrapper)
            if not selecteds:
                selecteds = [True] * len(cluster.samples)
            # self.__selected_count = selecteds.sum()
            self.__view_items = []
            for idx, sample in enumerate(cluster.samples):
                item = TextItem(
                    self.scrollFrame.viewPort,
                    idx + 1,
                    sample,
                    selected=selecteds[idx],
                    selectable=self.__selectable,
                    on_item_selected=self.update_selected_status
                )
                item.grid(row=idx, column=0, sticky='w', padx=1, pady=1)
                self.__view_items.append(item)

            self.scrollFrame.pack(side="top", fill="both", expand=True)
            self.__wrapper.pack( fill="both", expand=True)
            if self.__selectable:
                self.update_selected_status()

    def get_selected_samples(self):
        return [self.__cluster.samples[idx] for idx, item in enumerate(self.__view_items) if item.is_selected]

    def update_selected_status(self):
        selected_count = len(self.get_selected_samples())
        self.__selection_status.config(text=f"Selected: {selected_count}")

    def scroll_to(self, fraction=1):
        self.scrollFrame.scroll_to(fraction)

Here's the code for the grid view.

class ClusterGrid(tk.Frame):
def init(self, root,  clusters, num_cols=3, **kwargs):
super().init(root, bg="white", **kwargs)

    # main_frame = tk.Frame(root)
    self.__num_cols = num_cols
    self.__clusters = clusters

    self.__main_canvas = tk.Canvas(self, borderwidth=0)
    self.__main_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

    main_scrbar = ttk.Scrollbar(
        self,
        orient=tk.VERTICAL,
        command=self.__main_canvas.yview
    )
    main_scrbar.pack(side=tk.RIGHT, fill=tk.Y)

    self.__main_canvas.configure(yscrollcommand=main_scrbar.set)
    # self.main_canvas.bind('<Configure>', lambda e: self.main_canvas.configure(scrollregion=self.main_canvas.bbox("all")))

    self.__scroll_frame = tk.Frame(self.__main_canvas, bg="white")
    self.__canvas_window = self.__main_canvas.create_window((0,0), window=self.__scroll_frame, anchor="nw")

    self.__scroll_frame.bind("<Configure>", self.onFrameConfigure)
    self.__main_canvas.bind("<Configure>", self.onCanvasConfigure)

    self.__scroll_frame.bind('<Enter>', self.onEnter)
    self.__scroll_frame.bind('<Leave>', self.onLeave)

    for i, intent in enumerate(self.__clusters[:30]):
        col = i % self.__num_cols
        row = int(i/self.__num_cols)
        sc = ClusterFrame(self.__scroll_frame, intent, selectable=True)
        sc.grid(row=row, column=col, sticky='nsew', padx=5, pady=5)

    self.onFrameConfigure(None)

def destroy(self):
    self.__main_canvas.delete("all")
    super().destroy()

def onFrameConfigure(self, event):
    '''Reset the scroll region to encompass the inner frame'''
    # print("ScrollFrame: onFrameConfigure")
    self.__main_canvas.configure(scrollregion=self.__main_canvas.bbox("all"))

def onCanvasConfigure(self, event):
    '''Reset the canvas window to encompass inner frame when required'''
    # print("ScrollFrame: onCanvasConfigure")
    canvas_width = event.width
    self.__main_canvas.itemconfig(self.__canvas_window, width = canvas_width)

def onEnter(self, event):
    print("ScrollFrame: onEnter")
    if platform.system() == 'Linux':
        self.__main_canvas.bind_all("<Button-4>", self.onMouseWheel)
        self.__main_canvas.bind_all("<Button-5>", self.onMouseWheel)
    else:
        self.__main_canvas.bind_all("<MouseWheel>", self.onMouseWheel)

def onMouseWheel(self, event):
    # print("ScrollFrame: onMouseWheel")
    if platform.system() == 'Windows':
        self.__main_canvas.yview_scroll(int(-1* (event.delta/120)), "units")
    elif platform.system() == 'Darwin':
        self.__main_canvas.yview_scroll(int(-1 * event.delta), "units")
    else:
        if event.num == 4:
            self.__main_canvas.yview_scroll( -1, "units" )
        elif event.num == 5:
            self.__main_canvas.yview_scroll( 1, "units" )

def onLeave(self, event):
    print("ScrollFrame: onLeave")
    if platform.system() == 'Linux':
        self.__main_canvas.unbind_all("<Button-4>")
        self.__main_canvas.unbind_all("<Button-5>")
    else:
        self.__main_canvas.unbind_all("<MouseWheel>")

def destroy(self) -> None:
    # self.__main_canvas.delete("all")
    return super().destroy()

Finally the code for inflating the gridview.

import random
from threading import Timer
from tkinter import *
from scrollable_frames import ClusterGrid, Cluster

def clear_grid(view):
    print("clear_grid: ", view)
    if not view:
        return
    for widget in view.winfo_children():
        print("widget: ", widget)
        widget.destroy()

def on_slider_change(new_val, root):
    global slider_timer
    print("new_val: ", new_val)
    if slider_timer:
        slider_timer.cancel()
        print("cancelled")
    slider_timer = Timer(2, process, args=(new_val, root,))
    slider_timer.start()

def process(val, root):
    global intent_grid
    print("process...", val, intent_grid)

    print(val)
    clear_grid(intent_grid)
    clusters = []
    for i in range(100):
        samples = [ f"This is a sample text {i}" for i in range(100)]
        cl = Cluster(i, samples=samples)
        clusters.append(cl)
    intent_grid = ClusterGrid(root, clusters=clusters)
    intent_grid.grid(column=0, row=1, sticky="nsew")

root=Tk()
root.geometry("900x600")
intent_grid = None

root.columnconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)

slider_timer = None
threshold_slider_val = DoubleVar(value=0.6)
threshold_slider = Scale(
        root,
        from_= 0.3,
        to=1,
        resolution=0.05,
        orient=HORIZONTAL,
        variable=threshold_slider_val,
        command=lambda x: on_slider_change(new_val=x, root=root)
    )
threshold_slider.grid(column=0, row=0, pady=20)
root.mainloop()

I know drawing all elements on the canvas is not cool. Is there any way to just draw what're visible? Thank you so much in advance.


问:
How do I Join the output of One Vrf?
I am excuting command on cisco router

Here is the sample output:-

```<code>ABISVP_01     65:235
                                         import  65:236           IPV4  Unicast
                                         import  65:237           IPV4  Unicast
                                         export  65:236           IPV4  Unicast
                                         export  65:237           IPV4  Unicast
ABISVP_01     653:235
                                         import  65:236           IPV4  Unicast
                                         import  65:237           IPV4  Unicast
                                         export  65:236           IPV4  Unicast
                                         export  65:237           IPV4  Unicast
</code>```

textfsm template

```<code>Value VRF (\S+)
Value RD (\S+)
Value TYPE (import|export| )
Value RT (\S+)

Start
  ^${VRF}\s+${RD}.*$$
  ^\s+${TYPE}\s+${RT} -> Record

EOF
</code>```

Output was:-
[['ABISVP_01', '65:235', 'import', '65:236'], ['', '', 'import', '65:237'], ['', '', 'export', '65:236'], ['', '', 'export', '65:237'], ['ABISVP_01', '653:235', 'import', '65:236'], ['', '', 'import', '65:237'], ['', '', 'export', '65:236'], ['', '', 'export', '65:237']]

Required output is:-

[['ABISVP_01', '65:235', 'import', '65:236','import', '65:237', 'export', '65:236','export', '65:237'], ['ABISVP_01', '653:235', 'import', '65:236', 'import', '65:237', 'export', '65:236', 'export', '65:237']]

Title: How do I Join the output of One Vrf?

Body:
I am excuting command on cisco router

Here is the sample output:-

ABISVP_01     65:235
                                         import  65:236           IPV4  Unicast
                                         import  65:237           IPV4  Unicast
                                         export  65:236           IPV4  Unicast
                                         export  65:237           IPV4  Unicast
ABISVP_01     653:235
                                         import  65:236           IPV4  Unicast
                                         import  65:237           IPV4  Unicast
                                         export  65:236           IPV4  Unicast
                                         export  65:237           IPV4  Unicast

textfsm template

Value VRF (\S+)
Value RD (\S+)
Value TYPE (import|export| )
Value RT (\S+)

Start
  ^${VRF}\s+${RD}.*$$
  ^\s+${TYPE}\s+${RT} -> Record

EOF

Output was:-
[['ABISVP_01', '65:235', 'import', '65:236'], ['', '', 'import', '65:237'], ['', '', 'export', '65:236'], ['', '', 'export', '65:237'], ['ABISVP_01', '653:235', 'import', '65:236'], ['', '', 'import', '65:237'], ['', '', 'export', '65:236'], ['', '', 'export', '65:237']]

Required output is:-

[['ABISVP_01', '65:235', 'import', '65:236','import', '65:237', 'export', '65:236','export', '65:237'], ['ABISVP_01', '653:235', 'import', '65:236', 'import', '65:237', 'export', '65:236', 'export', '65:237']]


问:
How to publish messages over gRPC stream from another thread in Python?
I want to use gRPC to publish a stream of messages, but I also want to abstract away gRPC from the rest of my code. Ideally, I would have a thread in my main program that calls publish(message), and under the hood, publish would use a gRPC stream.

All the examples I've found online use yield semantics, and I'm not sure if it's possible to yield from another thread. And I'd prefer not to have to pass messages between the threads, because that would cause non-deterministic latency.

Take this rpc service request handler:

```<code>class SampleServiceServicer(sample_pb2_grpc.SampleServiceServicer):
    ''' this servicer method will read the request from the iterator supplied
        by incoming stream and send back the response in a stream
    '''
    def createBulkEntries(self, request_iterator, context):
        entry_info = dict()
        for request in request_iterator:
            print(request)

            ##### save to database #####

            # simulate the response after saving to database
            entry_info = {
                "id": str(uuid.uuid4()),
                "title": request.title,
                "code": request.code,
                "description": request.description,
                "created_on": round(datetime.now().timestamp())
            }

            # stream the response back
            yield sample_pb2.EntryResponse(**entry_info)
</code>```

You can see a full example here: https://github.com/techunits/bidirectional-streaming-grpc-sample-python/blob/main/servicers.py

It seems the only way to stream a response back is to yield. Is there not another way to do this? Can I pass some kind of socket to another thread and call send on it?

Body:
I want to use gRPC to publish a stream of messages, but I also want to abstract away gRPC from the rest of my code. Ideally, I would have a thread in my main program that calls publish(message), and under the hood, publish would use a gRPC stream.

All the examples I've found online use yield semantics, and I'm not sure if it's possible to yield from another thread. And I'd prefer not to have to pass messages between the threads, because that would cause non-deterministic latency.

Take this rpc service request handler:

class SampleServiceServicer(sample_pb2_grpc.SampleServiceServicer):
    ''' this servicer method will read the request from the iterator supplied
        by incoming stream and send back the response in a stream
    '''
    def createBulkEntries(self, request_iterator, context):
        entry_info = dict()
        for request in request_iterator:
            print(request)

            ##### save to database #####

            # simulate the response after saving to database
            entry_info = {
                "id": str(uuid.uuid4()),
                "title": request.title,
                "code": request.code,
                "description": request.description,
                "created_on": round(datetime.now().timestamp())
            }

            # stream the response back
            yield sample_pb2.EntryResponse(**entry_info)

You can see a full example here: https://github.com/techunits/bidirectional-streaming-grpc-sample-python/blob/main/servicers.py

It seems the only way to stream a response back is to yield. Is there not another way to do this? Can I pass some kind of socket to another thread and call send on it?


问:
Product Image not showing on Home Page
Basically, Product image on showing.
i try this method as given below. after product image appeared , banner background picture stop to showing.

Open PluginListGenerator.php file located at vendor/magento/framework/Interception.
Replace the line
$cacheId = implode('|', $this->scopePriorityScheme) . "|" . $this->cacheId;
with below:
$cacheId = implode('-', $this->scopePriorityScheme) . "-" . $this->cacheId;
Save the PluginListGenerator.php file.
I have try this code, problem solved but after that banner image not showing.

Title: Product Image not showing on Home Page


问:
Snapping Objects to hit boxes after an intersection in java
I'm working on a game for a game jam, and can't get my collision system to work. The way it's supposed to work is when an the player intersects with a wall hitbox it moves the player towards the last position until it no longer intersects. This doesn't work though, this is the code:`

```<code>while(worldBox.intersects((Rectangle2D) Player.entity)) {
      if(offsetX - lastX > 0) offsetX --;
      if(offsetX - lastX < 0) offsetX ++;
      if(offsetY - lastY > 0) offsetY --;
      if(offsetY - lastY < 0) offsetY ++;
      makeWorldHitBox();
}
</code>```

` and here is the link to the github repo: https://github.com/DJPretzel-bit64/LemonRunner.git

I tried changing sines and offsets, nothing worked

Body:
I'm working on a game for a game jam, and can't get my collision system to work. The way it's supposed to work is when an the player intersects with a wall hitbox it moves the player towards the last position until it no longer intersects. This doesn't work though, this is the code:`

while(worldBox.intersects((Rectangle2D) Player.entity)) {
      if(offsetX - lastX > 0) offsetX --;
      if(offsetX - lastX < 0) offsetX ++;
      if(offsetY - lastY > 0) offsetY --;
      if(offsetY - lastY < 0) offsetY ++;
      makeWorldHitBox();
}

` and here is the link to the github repo: https://github.com/DJPretzel-bit64/LemonRunner.git

I tried changing sines and offsets, nothing worked


问:
Progress Bar Implementation for CodeGen in Theia
on clicking generate java code button in theia editor
it’s calling registry command in command contribution in theia.
registry command is hitting IExecutableCommandService in backend LSP to generate java code.

now i need value of execution progress in theia editor so that i can implement that in progress bar.


问:
Play Integrity alternative for China region
Google provides play integrity API for app integrity protection in android applications. But, since Google services are not available in China region, then what are the alternative APIs for integrity protection for Android apps in China (Huawei, Baidu, Vivo, Xiaomi, Oppo, etc)?

After exploring a lot, I found an alternative API for Huawei which is SysIntegrity API (https://developer.huawei.com/consum...ides/dysintegritydevelopment-0000001050156331), but I want to know about the availability of similar APIs in Baidu and other providers as well.


问:
Response of get request in nodeJS is not sending?
I have transform response in to array look like below.(Get this array in console log).

```<code>[
  '63873a0ec1578bce01934dd2': [
    {
      _id: new ObjectId("63874a8dc1578bce01934e0d"),
      fromDate: '2022-07-22 12:37:29',
      toDate: '0000-00-00 00:00:00',
      description: 'testing description',
      productId: new ObjectId("63874773c1578bce01934dfc"),
      userId: new ObjectId("63873a0ec1578bce01934dd2"),
      Product: [Object],
      media: [],
      user: [Object]
    },
    {
      _id: new ObjectId("63874a8dc1578bce01934e0e"),
      fromDate: '2022-07-22 22:08:57',
      toDate: '2026-08-12 22:08:00',
      description: 'this is good',
      productId: new ObjectId("63874773c1578bce01934dfc"),
      userId: new ObjectId("63873a0ec1578bce01934dd2"),
      Product: [Object],
      media: [],
      user: [Object]
    }
  ],
]
</code>```

I am expecting to get response but I get an empty array.I did data to string as well as to JSON. But I didn't get response.

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

Body:
I have transform response in to array look like below.(Get this array in console log).

[
  '63873a0ec1578bce01934dd2': [
    {
      _id: new ObjectId("63874a8dc1578bce01934e0d"),
      fromDate: '2022-07-22 12:37:29',
      toDate: '0000-00-00 00:00:00',
      description: 'testing description',
      productId: new ObjectId("63874773c1578bce01934dfc"),
      userId: new ObjectId("63873a0ec1578bce01934dd2"),
      Product: [Object],
      media: [],
      user: [Object]
    },
    {
      _id: new ObjectId("63874a8dc1578bce01934e0e"),
      fromDate: '2022-07-22 22:08:57',
      toDate: '2026-08-12 22:08:00',
      description: 'this is good',
      productId: new ObjectId("63874773c1578bce01934dfc"),
      userId: new ObjectId("63873a0ec1578bce01934dd2"),
      Product: [Object],
      media: [],
      user: [Object]
    }
  ],
]

I am expecting to get response but I get an empty array.I did data to string as well as to JSON. But I didn't get response.

{
    "data": [],
}