问:
How to correct the order of my attempted reverse array?
I was working on a project that would see an array of decimals be printed out in reverse and in a lateral printing. I have gotten the java code to be printed in lateral format, but when it comes to have my arrays variables printed, it is not in revers order, but in a random order.
I am not sure where I have gone wrong, looking for a second pare of eyes to catch where I went wrong, thanks.</p>
```<code>public static void main(String[] args) {
    // TODO Auto-generated method stub
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    double [] dArray = {3.1415, 17.4567, 8.3132};
    int i = 0;
    for (double d : dArray) {
        dArray [i] = Double.valueOf(decimalFormat.format(d));
        i++;
    }
    for (double d = dArray.length-1;d>=1;d--)
        //System.out.println(dArray[i]);
    Arrays.stream(dArray).forEach(System.out::println);
}

}
</code>```

答:
You made a few mistakes in your code:

In

```<code>for (double d = dArray.length-1;d>=1;d--)
    System.out.println(dArray[i]);
</code>```

d should be an int and should be decremented down to zero and not one. Also, dArray[i], should've been dArray[d] since that is what you chose as counter variable. Lastly, the statement System.out.println(dArray[i]); won't print out the internal values of the array. It will print out the object's hashcode (yes, arrays are objects in Java).

```<code>for (double d = dArray.length-1;d>=1;d--)
    //System.out.println(dArray[i]);
    Arrays.stream(dArray).forEach(System.out::println);
</code>```

Because you fail to use curly braces with your loop, commenting out your previous attempt to print out the array produced the ill effect of calling the stream operation INSIDE THE LOOP. So basically, you are printing out the whole array while iterating through it. The contents of the array is then printed twice. You should've commented out the for loop as well.

The solution:

```<code>public class ReverseArray {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        double[] dArray = {3.1415, 17.4567, 8.3132};
        double[] reversedArray = new double[dArray.length];
        System.out.print("[");
        for(int i = 0; i < dArray.length; i++) {
            double value = dArray[i];
            System.out.print(value);
            if (i < dArray.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");

        for (int i = dArray.length - 1, j = 0; i >= 0; i--, j++) {
            reversedArray[j] = dArray [i];
        }
        System.out.print("[");
        for(int i = 0; i < reversedArray.length; i++) {
            double value = reversedArray[i];
            System.out.print(value);
            if (i < reversedArray.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }
}
</code>```

The above code outputs:

```<code>[3.1415, 17.4567, 8.3132]
[8.3132, 17.4567, 3.1415]
</code>```

You can use DecimalFormat to display the output using your pattern. You should not use it to format the values and then save them in your array. If you were doing that in financial software, you would end up in jail eventually. Using your decimal format pattern, I can modify the two System.out.print() as follows: System.out.print(decimalFormat.format(value));. With that change, the program now outputs:

```<code>[3.14, 17.46, 8.31]
[8.31, 17.46, 3.14]
</code>```

Without modifying the values of the array.

Body:
I was working on a project that would see an array of decimals be printed out in reverse and in a lateral printing. I have gotten the java code to be printed in lateral format, but when it comes to have my arrays variables printed, it is not in revers order, but in a random order.
I am not sure where I have gone wrong, looking for a second pare of eyes to catch where I went wrong, thanks.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    double [] dArray = {3.1415, 17.4567, 8.3132};
    int i = 0;
    for (double d : dArray) {
        dArray [i] = Double.valueOf(decimalFormat.format(d));
        i++;
    }
    for (double d = dArray.length-1;d>=1;d--)
        //System.out.println(dArray[i]);
    Arrays.stream(dArray).forEach(System.out::println);
}

}

Body:
You made a few mistakes in your code:

In

for (double d = dArray.length-1;d>=1;d--)
    System.out.println(dArray[i]);

d should be an int and should be decremented down to zero and not one. Also, dArray[i], should've been dArray[d] since that is what you chose as counter variable. Lastly, the statement System.out.println(dArray[i]); won't print out the internal values of the array. It will print out the object's hashcode (yes, arrays are objects in Java).

for (double d = dArray.length-1;d>=1;d--)
    //System.out.println(dArray[i]);
    Arrays.stream(dArray).forEach(System.out::println);

Because you fail to use curly braces with your loop, commenting out your previous attempt to print out the array produced the ill effect of calling the stream operation INSIDE THE LOOP. So basically, you are printing out the whole array while iterating through it. The contents of the array is then printed twice. You should've commented out the for loop as well.

The solution:

public class ReverseArray {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        double[] dArray = {3.1415, 17.4567, 8.3132};
        double[] reversedArray = new double[dArray.length];
        System.out.print("[");
        for(int i = 0; i < dArray.length; i++) {
            double value = dArray[i];
            System.out.print(value);
            if (i < dArray.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");

        for (int i = dArray.length - 1, j = 0; i >= 0; i--, j++) {
            reversedArray[j] = dArray [i];
        }
        System.out.print("[");
        for(int i = 0; i < reversedArray.length; i++) {
            double value = reversedArray[i];
            System.out.print(value);
            if (i < reversedArray.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }
}

The above code outputs:

[3.1415, 17.4567, 8.3132]
[8.3132, 17.4567, 3.1415]

You can use DecimalFormat to display the output using your pattern. You should not use it to format the values and then save them in your array. If you were doing that in financial software, you would end up in jail eventually. Using your decimal format pattern, I can modify the two System.out.print() as follows: System.out.print(decimalFormat.format(value));. With that change, the program now outputs:

[3.14, 17.46, 8.31]
[8.31, 17.46, 3.14]

Without modifying the values of the array.


来源: stackexchange

问:
I made a Student registration program using arraylist in Java and had problems in arranging the result in descending order by Percentage
When I run the option to sort the results, the first 2 are in correct form but the remaining are just the copy of the 2nd detail. The other functions run fairly smoothly, the only problem I am facing is with the sort() function. I have given it much thoughts to no avail.

import java.util.ArrayList;
import java.util.Scanner;

class Test {

    public static int totaln=0;
    public static ArrayList<String> fname;
    public static ArrayList<String> lname;
    public static ArrayList<String> dob;
    public static ArrayList<String> gender;
    public static ArrayList<Integer> standard;
    public static ArrayList<Integer> rollno;
    public static ArrayList<Float> maths;
    public static ArrayList<Float> science;
    public static ArrayList<Float> social;
    public static ArrayList<Float> eng;
    public static ArrayList<Float> percentage ;

     public static void entry() {

        int num;

        Scanner sc=new Scanner(System.in);
         fname= new ArrayList<>();
         lname= new ArrayList<>();
         dob= new ArrayList<>();
         gender= new ArrayList<>();
         standard= new ArrayList<>();
         rollno= new ArrayList<>();
         maths =new ArrayList<>();
         science = new ArrayList<>();
         social = new ArrayList<>();
         eng = new ArrayList<>();
         percentage = new ArrayList<>();

        System.out.print("Enter the number of students: ");
        num = sc.nextInt();
        if(num==0 || num<0){
            System.out.println("Invalid Entry.");
        }
           else {
                for (int i = 0; i < num; i++) {
                    System.out.println();
                    System.out.println("Student: " +(i+1));
                    System.out.print("Enter the standard: ");
                    standard.add(sc.nextInt());
                    System.out.print("Enter the first name: ");
                    fname.add(sc.next());
                    System.out.print("Enter the last name: ");
                    lname.add(sc.next());
                    System.out.print("Enter the roll no: ");
                    rollno.add(sc.nextInt());
                    System.out.print("Enter the date of birth: ");
                    dob.add(sc.next());
                    System.out.print("Enter the gender: ");
                    gender.add(sc.next());
                    System.out.print("Enter the marks in Maths: ");
                    maths.add(sc.nextFloat());
                    System.out.print("Enter the marks in Science: ");
                    science.add(sc.nextFloat());
                    System.out.print("Enter the marks in Social: ");
                    social.add(sc.nextFloat());
                    System.out.print("Enter the marks in English: ");
                    eng.add(sc.nextFloat());
                    percentage.add((maths.get(i)+ science.get(i)+ social.get(i)+ eng.get(i))/4);
                }
                totaln+=num;

            }

    }
    public static void display(){
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            System.out.println();
            System.out.println("Student Details");
            for (int i=0;i<totaln;i++){
                System.out.println();
                System.out.println("Name " +fname.get(i)+" "+lname.get(i));
                System.out.println("Standard: "+standard.get(i));
                System.out.println("Roll no: " +rollno.get(i));
                System.out.println("Date of birth: " +dob.get(i));
                System.out.println("Gender: " +gender.get(i));
                System.out.println("Percentage: " +percentage.get(i));
            }

        }

    }
    public static void search(){
        int roll;
        Scanner sc= new Scanner(System.in);
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            System.out.println();
            System.out.println("Enter the roll no of the student to search: ");
            roll = sc.nextInt();
            int s=0;

            for(int i=0;i<totaln;i++){
                if(roll==rollno.get(i)){
                    s=s+1;
                    System.out.println();
                    System.out.println("Name " +fname.get(i)+" "+lname.get(i));
                    System.out.println("Standard: "+standard.get(i));
                    System.out.println("Roll no: " +rollno.get(i));
                    System.out.println("Maths: "+maths.get(i));
                    System.out.println("Science: "+science.get(i));
                    System.out.println("Social: "+social.get(i));
                    System.out.println("English: "+eng.get(i));
                    System.out.println("Percentage: " +percentage.get(i));

                }

            }
            if(s>0) {
                System.out.println("Invalid entry. ");
            }
        }

    }
    public static void sort(){
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            int c= percentage.size();
            for (int i=0; i<c-1; i++)
            {
                int pos = i;
                for (int j=i+1; j<c; j++)
                {
                    if (percentage.get(j) > percentage.get(pos))
                    {
                        pos = j;
                    }
                }
                float t1 = percentage.get(pos);
                percentage.add(pos, percentage.get(i)) ;
                percentage.add(i,t1);

                String f = fname.get(pos);
                fname.add(pos,fname.get(i));
                fname.add(i,f);

                String l = lname.get(pos);
                lname.add(pos,lname.get(i));
                lname.add(i,l);
            }
            System.out.println("The required order: ");

            for (int i=0;i<3;i++){
                System.out.println("Rank: " +(i+1));
                System.out.println("Percentage: "+percentage.get(i));
                System.out.println("Name: " +fname.get(i)+" "+lname.get(i));
            }

        }
    }

    public static void delete(){
        int roll;
        Scanner sc= new Scanner(System.in);
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            int choice;
            System.out.println("Enter 1 to delete all record:");
            System.out.println("Enter 2 to delete the record of a student");
            choice= sc.nextInt();
            if(choice==1){
                totaln=0;
                System.out.println("All the records have been deleted.");

            }
            else if(choice==2){
                System.out.println();
                System.out.println("Enter the roll no of the student you miss delete the record of: ");
                roll = sc.nextInt();

                for(int i=0;i<totaln;i++){
                    if(roll==rollno.get(i)){
                        for(int j=i;j<totaln;j++){
                            standard.remove(j);
                            fname.remove(j);
                            lname.remove(j);
                            rollno.remove(j);
                            dob.remove(j);
                            gender.remove(j);
                            percentage.remove(j);
                        }
                        totaln--;
                        System.out.println("The record has been deleted.");

                    }
                }

            }
            else {
                System.out.println("Invalid input.");
            }

        }

    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int value;
        char ch;
        do {
            System.out.println("Enter 1 to enter data.");
            System.out.println("Enter 2 to show data.");
            System.out.println("Enter 3 to search data.");
            System.out.println("Enter 4 to view the result in descending order: ");
            System.out.println("Enter 5 to delete data.");
            System.out.println("Enter 6 to exit.");
            System.out.println();
            System.out.print("Enter the value: ");
            value=sc.nextInt();
            switch(value){
                case 1:
                    entry();
                    break;
                case 2:
                    display();
                    break;
                case 3:
                    search();
                    break;
                case 4:
                    sort();
                    break;
                case 5:
                    delete();
                    break;
                case 6:
                    break;
                default:
                    System.out.println("Invalid input.");
                    break;
            }
            System.out.println("Do you want to continue(y/n): ");
            ch=sc.next().charAt(0);
        }while(ch=='y' || ch=='Y');
    }
}
```

答:
I would suggest a step by step solution:

first create a class of Student and implement a Comparable then override the compareTo method as follows:

```<code>public class Student implements Comparable<Student>{

    private String fName;
    private String lName;
    private int age;
    private double percentage;

    public Student() {}

    public Student(String fName, String lName, int age, double percentage) {
        this.fName = fName;
        this.lName = lName;
        this.age = age;
        this.percentage = percentage;
    }

    public String getfName() {
        return fName;
    }

    public String getlName() {
        return lName;
    }

    public int getAge() {
        return age;
    }

    public double getPercentage(){return percentage;}

    @Override
    public int compareTo(Student o) {
        if (percentage == o.percentage){
            return 0;
        } else if(percentage > o.percentage){
            return 1;
        }else{
            return -1;
        }
    }

    @Override
    public String toString() {
        return "Student{" +
                "fName='" + fName + '\'' +
                ", lName='" + lName + '\'' +
                ", age=" + age +
                ", percentage=" + percentage +
                '}';
    }
}
</code>```

Second in your main method create objects of Student and store them inside an ArrayList:

```<code>public class StudentRun{
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<Student>(){
            {
                add(new Student("Bob","Logan", 24, 78.9));
                add(new Student("Mike","Staats", 22, 90.4));
                add(new Student("Robert", "Finley", 44, 85.3));
                add(new Student("Hector", "Kalona", 35, 73.8));
            }
        };

        Collections.sort(students);
        System.out.println(students);

    }
}
</code>```

I would suggest to have a look at Java Collections and Comparable interface.

ContentLicense: CC BY-SA 4.0

Body:
I would suggest a step by step solution:

first create a class of Student and implement a Comparable then override the compareTo method as follows:

public class Student implements Comparable<Student>{

    private String fName;
    private String lName;
    private int age;
    private double percentage;

    public Student() {}

    public Student(String fName, String lName, int age, double percentage) {
        this.fName = fName;
        this.lName = lName;
        this.age = age;
        this.percentage = percentage;
    }

    public String getfName() {
        return fName;
    }

    public String getlName() {
        return lName;
    }

    public int getAge() {
        return age;
    }

    public double getPercentage(){return percentage;}

    @Override
    public int compareTo(Student o) {
        if (percentage == o.percentage){
            return 0;
        } else if(percentage > o.percentage){
            return 1;
        }else{
            return -1;
        }
    }

    @Override
    public String toString() {
        return "Student{" +
                "fName='" + fName + '\'' +
                ", lName='" + lName + '\'' +
                ", age=" + age +
                ", percentage=" + percentage +
                '}';
    }
}

Second in your main method create objects of Student and store them inside an ArrayList:

public class StudentRun{
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<Student>(){
            {
                add(new Student("Bob","Logan", 24, 78.9));
                add(new Student("Mike","Staats", 22, 90.4));
                add(new Student("Robert", "Finley", 44, 85.3));
                add(new Student("Hector", "Kalona", 35, 73.8));
            }
        };

        Collections.sort(students);
        System.out.println(students);

    }
}

I would suggest to have a look at Java Collections and Comparable interface.


问:
Can't get DependencyProperty to work
I wrote a small attached property called "IsValid" for the WPF TextBox, like so:

```<code>public enum InputTypes
{
    Any,

    Integer,

    Double,

    Float
}

/// <summary>
/// This attached property can be used to validate input for <see cref="TextBox"/>.
/// </summary>
public class IsValid : DependencyObject
{
    public static readonly DependencyProperty InputProperty = DependencyProperty.Register(
        "Input",
        typeof(InputTypes),
        typeof(IsValid),
        new UIPropertyMetadata(InputTypes.Any, onInput));

    public static InputTypes GetInput(DependencyObject d)
    {
        return (InputTypes)d.GetValue(InputProperty);
    }

    public static void SetInput(DependencyObject d, InputTypes value)
    {
        d.SetValue(InputProperty, value);
    }

    private static void onInput(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textBox = (TextBox)d;
        var value = (InputTypes)e.NewValue;
        switch (value)
        {
            case InputTypes.Any:
                textBox.PreviewTextInput -= validateInput;
                textBox.PreviewKeyDown -= validateKeyDown;
                break;

            default:
                textBox.PreviewTextInput += validateInput;
                textBox.PreviewKeyDown += validateKeyDown;
                break;
        }
    }

    private static void validateInput(object sender, TextCompositionEventArgs e)
    {
        // enforce numeric input when configured ...
        var textBox = (TextBox) sender;
        var inputTypes = (InputTypes) textBox.GetValue(InputProperty);
        foreach (var c in e.Text)
        {
            switch (inputTypes)
            {
                case InputTypes.Integer:
                    if (!char.IsDigit(c))
                    {
                        e.Handled = true;
                        return;
                    }
                    break;

                case InputTypes.Double:
                case InputTypes.Float:
                    if (!char.IsNumber(c))
                    {
                        e.Handled = true;
                        return;
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    private static void validateKeyDown(object sender, KeyEventArgs e)
    {
        // block [SPACE] when numeric input is expected ...
        var textBox = (TextBox)sender;
        var inputTypes = (InputTypes)textBox.GetValue(InputProperty);
        if (inputTypes != InputTypes.Any && e.Key == Key.Space)
            e.Handled = true;
    }
}
</code>```

End here's how I've used it:

```<code><Window x:Class="Spike.Wpf.Controls.TestApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:values="clr-namespace:Spike.Wpf.Controls.Input;assembly=Spike.Wpf.Controls"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox values:IsValid.Input="Double" />
</Grid>
</code>```

After the initialization (of the DependencyProperty) none of the methods in IsValid gets called however. What am I missing?

答:
Earlier you probably got an error telling you that IsValid needs to derive from DependecyObject, so you added that, you should have asked yourself why that is. The answer is right here:

```<code>public static readonly DependencyProperty InputProperty = DependencyProperty.Register(...
</code>```

You try to register a normal property for objects on type IsValid, change it to RegisterAttached and it should work. (I would also remove the inheritance and make IsValid a static class)

ContentLicense: CC BY-SA 3.0

Title: Can't get DependencyProperty to work

Body:
I wrote a small attached property called "IsValid" for the WPF TextBox, like so:

public enum InputTypes
{
    Any,

    Integer,

    Double,

    Float
}

///
/// This attached property can be used to validate input for <see cref="TextBox"/>.
///
public class IsValid : DependencyObject
{
    public static readonly DependencyProperty InputProperty = DependencyProperty.Register(
        "Input",
        typeof(InputTypes),
        typeof(IsValid),
        new UIPropertyMetadata(InputTypes.Any, onInput));

    public static InputTypes GetInput(DependencyObject d)
    {
        return (InputTypes)d.GetValue(InputProperty);
    }

    public static void SetInput(DependencyObject d, InputTypes value)
    {
        d.SetValue(InputProperty, value);
    }

    private static void onInput(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textBox = (TextBox)d;
        var value = (InputTypes)e.NewValue;
        switch (value)
        {
            case InputTypes.Any:
                textBox.PreviewTextInput -= validateInput;
                textBox.PreviewKeyDown -= validateKeyDown;
                break;

            default:
                textBox.PreviewTextInput += validateInput;
                textBox.PreviewKeyDown += validateKeyDown;
                break;
        }
    }

    private static void validateInput(object sender, TextCompositionEventArgs e)
    {
        // enforce numeric input when configured ...
        var textBox = (TextBox) sender;
        var inputTypes = (InputTypes) textBox.GetValue(InputProperty);
        foreach (var c in e.Text)
        {
            switch (inputTypes)
            {
                case InputTypes.Integer:
                    if (!char.IsDigit(c))
                    {
                        e.Handled = true;
                        return;
                    }
                    break;

                case InputTypes.Double:
                case InputTypes.Float:
                    if (!char.IsNumber(c))
                    {
                        e.Handled = true;
                        return;
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    private static void validateKeyDown(object sender, KeyEventArgs e)
    {
        // block [SPACE] when numeric input is expected ...
        var textBox = (TextBox)sender;
        var inputTypes = (InputTypes)textBox.GetValue(InputProperty);
        if (inputTypes != InputTypes.Any && e.Key == Key.Space)
            e.Handled = true;
    }
}

End here's how I've used it:

<Window x:Class="Spike.Wpf.Controls.TestApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:values="clr-namespace:Spike.Wpf.Controls.Input;assembly=Spike.Wpf.Controls"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox values:IsValid.Input="Double" />
</Grid>

After the initialization (of the DependencyProperty) none of the methods in IsValid gets called however. What am I missing?

Body:
Earlier you probably got an error telling you that IsValid needs to derive from DependecyObject, so you added that, you should have asked yourself why that is. The answer is right here:

public static readonly DependencyProperty InputProperty = DependencyProperty.Register(...

You try to register a normal property for objects on type IsValid, change it to RegisterAttached and it should work. (I would also remove the inheritance and make IsValid a static class)


问:
Enter-PSSession doesn't execute command on remote computer
I want execute some of powershell comand on remote computer. My ps1 file is contain below data:

```<code>$secure_password = 'password' | ConvertTo-SecureString -AsPlainText -Force
$credential_object = New-Object System.Management.Automation.PSCredential -ArgumentList 'administrator', $secure_password
$new_session = New-PSSession -Credential $credential_object -ComputerName  192.168.1.222
Enter-PSSession $new_session
{
  mkdir "C:\Users\Administrator\Desktop\new_folder"
}
Exit-PSSession
Remove-PSSession $new_session
</code>```

I want make a directory in my remote computer that ip is 192.168.1.222 but unfortunately doesn't make directory in remote computer.
Why doesn't it work?

答:
You create PSSession when you want to execute multiple commands on a remote system. However, if you only need to run a single command/script, no need for a persistent PSSession.

You use Enter-PSSession for interactive work. However, when you using PSSession in a script/function, simply use Invoke-Command instead. It will be easier and faster.

Example

```<code>$secure_password = 'password' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'administrator', $secure_password

Invoke-Command -ComputerName 192.168.1.222 -Credential $cred -ScriptBlock { New-Item -Name "C:\Users\Administrator\Desktop\new_folder" -ItemType Directory }
</code>```

Note: It is a bad idea to hardcode clear-text passwords into your scripts. Have a look at a native way to store credentials externally: SecretManagement

Body:
I want execute some of powershell comand on remote computer. My ps1 file is contain below data:

$secure_password = 'password' | ConvertTo-SecureString -AsPlainText -Force
$credential_object = New-Object System.Management.Automation.PSCredential -ArgumentList 'administrator', $secure_password
$new_session = New-PSSession -Credential $credential_object -ComputerName  192.168.1.222
Enter-PSSession $new_session
{
  mkdir "C:\Users\Administrator\Desktop\new_folder"
}
Exit-PSSession
Remove-PSSession $new_session

I want make a directory in my remote computer that ip is 192.168.1.222 but unfortunately doesn't make directory in remote computer.
Why doesn't it work?

Body:
You create PSSession when you want to execute multiple commands on a remote system. However, if you only need to run a single command/script, no need for a persistent PSSession.

You use Enter-PSSession for interactive work. However, when you using PSSession in a script/function, simply use Invoke-Command instead. It will be easier and faster.

Example

$secure_password = 'password' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'administrator', $secure_password

Invoke-Command -ComputerName 192.168.1.222 -Credential $cred -ScriptBlock { New-Item -Name "C:\Users\Administrator\Desktop\new_folder" -ItemType Directory }

Note: It is a bad idea to hardcode clear-text passwords into your scripts. Have a look at a native way to store credentials externally: SecretManagement


问:
How can I retry a function with try/catch in react js?
I have a function with try catch inside. I call to the API about response. This response returns me a Result object with some data. But sometimes I'd like to retry the function if I have no name and have bundle_id.

I'd like to retry this functions max 3 times. If no result, I'd like to throw an error.

I have sth like this, but it doesn't work for me.

```<code>const getECommerceProduct = async ({
    item,
    getParent = false,
    variantInfo,
}) => {
    if (!item.id) return null;
    let retryCounter = 0;
    try {
        const response = await getEvaService(Core.GetProductDetail, {
            ID: item.id,
        });
        const itemResponse = response?.Result;
        if (!itemResponse) return null;

        // Retry the function if the item has no name and has a bundle product.
        // The bundle product will give back more information about the product.
        const retry = !!itemResponse.bundle_id && !itemResponse.product_name;
        if (retry && !getParent && retryCounter <= 3) {
            retryCounter += 1;
            return getECommerceProduct({
                item: {
                    id: itemResponse.bundle_id,
                    quantity: item.quantity,
                    variantInfo,
                },
                getParent: true,
            });
        }
        return transformProductToECommerce(itemResponse, item);
    } catch (e) {
        console.error(e);
        return null;
    }
};
</code>```

Could you help me?

答:
You could use a state to track the attempt count.

```<code>[retry_count, setRetryCount] = useState(0);

useEffect(() => {
   if (retry_count < 3) {
      // .... put fetch code here
   }
}, [retry_count])

</code>```

Increment the retry_count every time by putting it in the catch block within your fetch function

```<code>    React.useEffect(() => {
        const getECommerceProduct = async ({ item, getParent = false, variantInfo }) => {
            if (!item.id) return null;

            const response = await getEvaService(Core.GetProductDetail, {
                ID: item.id,
            });

            const itemResponse = response?.Result;
            if (!itemResponse) return null;

            return transformProductToECommerce(itemResponse, item);
        };

        if (retry_count < 3) {
            getECommerceProduct().catch((e) => {
                console.error(e);
                setRetryCount(retry_count + 1);
                return null;
            });
        }
    }, [retry_count]);
</code>```

With the useEffect, this means that every time the retry_count is incremented (in this case an error happens), the function within the useEffect call will be performed.

Body:
I have a function with try catch inside. I call to the API about response. This response returns me a Result object with some data. But sometimes I'd like to retry the function if I have no name and have bundle_id.

I'd like to retry this functions max 3 times. If no result, I'd like to throw an error.

I have sth like this, but it doesn't work for me.

const getECommerceProduct = async ({
    item,
    getParent = false,
    variantInfo,
}) => {
    if (!item.id) return null;
    let retryCounter = 0;
    try {
        const response = await getEvaService(Core.GetProductDetail, {
            ID: item.id,
        });
        const itemResponse = response?.Result;
        if (!itemResponse) return null;

        // Retry the function if the item has no name and has a bundle product.
        // The bundle product will give back more information about the product.
        const retry = !!itemResponse.bundle_id && !itemResponse.product_name;
        if (retry && !getParent && retryCounter <= 3) {
            retryCounter += 1;
            return getECommerceProduct({
                item: {
                    id: itemResponse.bundle_id,
                    quantity: item.quantity,
                    variantInfo,
                },
                getParent: true,
            });
        }
        return transformProductToECommerce(itemResponse, item);
    } catch (e) {
        console.error(e);
        return null;
    }
};

Could you help me?

Body:
You could use a state to track the attempt count.

[retry_count, setRetryCount] = useState(0);

useEffect(() => {
   if (retry_count < 3) {
      // .... put fetch code here
   }
}, [retry_count])

Increment the retry_count every time by putting it in the catch block within your fetch function

    React.useEffect(() => {
        const getECommerceProduct = async ({ item, getParent = false, variantInfo }) => {
            if (!item.id) return null;

            const response = await getEvaService(Core.GetProductDetail, {
                ID: item.id,
            });

            const itemResponse = response?.Result;
            if (!itemResponse) return null;

            return transformProductToECommerce(itemResponse, item);
        };

        if (retry_count < 3) {
            getECommerceProduct().catch((e) => {
                console.error(e);
                setRetryCount(retry_count + 1);
                return null;
            });
        }
    }, [retry_count]);

With the useEffect, this means that every time the retry_count is incremented (in this case an error happens), the function within the useEffect call will be performed.


问:
nullPointerException when replacing char sequence
I developed a very simple android app and then I obfuscated the code. A nullPointerException is throwed when, probably, I replace a char sequence.

Here is my stack trace:

```<code>java.lang.NullPointerException
at com.xpandit.pemobile.android.loadactivity.ak.d(Unknown Source)
at com.xpandit.pemobile.android.loadactivity.g.onTextChanged(Unknown Source)
at android.widget.TextView.sendOnTextChanged(TextView.java:6335)
at android.widget.TextView.handleTextChanged(TextView.java:6376)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6520)
at android.text.SpannableStringBuilder.sendTextChange(SpannableStringBuilder.java:889)
at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:352)
at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:269)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:432)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:409)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:28)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:583)
at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:174)
at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:120)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:257)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)
</code>```

As i said the code is obfuscated and by the mapping file I've found the right method (at least I think). The question is: In what situation can a replace method throw a null pointer?

Maybe the problem is not the replace method! Can anyone tell me where is the problem and how to resolve it? Thanks in advance...

EDIT:
I think the problem must be on that simple if instruction.

```<code>if (aux.contains(" ")){
    aux = aux.replace(" ", "%20");
}
</code>```

答:
```<code>if (aux.contains(" ")){
</code>```

throws an NPE if aux is null. It should be

```<code>if (anx != null && aux.contains(" ")){
</code>```

Body:
I developed a very simple android app and then I obfuscated the code. A nullPointerException is throwed when, probably, I replace a char sequence.

Here is my stack trace:

java.lang.NullPointerException
at com.xpandit.pemobile.android.loadactivity.ak.d(Unknown Source)
at com.xpandit.pemobile.android.loadactivity.g.onTextChanged(Unknown Source)
at android.widget.TextView.sendOnTextChanged(TextView.java:6335)
at android.widget.TextView.handleTextChanged(TextView.java:6376)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6520)
at android.text.SpannableStringBuilder.sendTextChange(SpannableStringBuilder.java:889)
at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:352)
at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:269)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:432)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:409)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:28)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:583)
at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:174)
at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:120)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:257)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)

As i said the code is obfuscated and by the mapping file I've found the right method (at least I think). The question is: In what situation can a replace method throw a null pointer?

Maybe the problem is not the replace method! Can anyone tell me where is the problem and how to resolve it? Thanks in advance...

EDIT:
I think the problem must be on that simple if instruction.

if (aux.contains(" ")){
    aux = aux.replace(" ", "%20");
}

Body:
if (aux.contains(" ")){

throws an NPE if aux is null. It should be

if (anx != null && aux.contains(" ")){


问:
'No frame for given id found' in puppetter
i am using puppetter for web scrapping ;
matchesLinks is an array that contains urls of some games.
my code looks like :

```<code>for (let i = 0; i < matchesLinks.length; i++) {
   await page.goto(matchesLinks[i]);
   await page.goto(matchesLinks[i]);
   await new Promise((r) => setTimeout(r, 6000));
 }
</code>```

after going to 1 or 2 URL i get error: originalMessage: 'No frame for given id found'
anyone can help my why i am getting this error

答:
You might be facing the issue described here: https://github.com/puppeteer/puppeteer/pull/7848

You may try to downgrade puppeteer version to 11.0.0 as a workaround

EDIT: The fix has most likely been released. Consider upgrading the puppeteer.

Body:
i am using puppetter for web scrapping ;
matchesLinks is an array that contains urls of some games.
my code looks like :

for (let i = 0; i < matchesLinks.length; i++) {
   await page.goto(matchesLinks[i]);
   await page.goto(matchesLinks[i]);
   await new Promise((r) => setTimeout(r, 6000));
 }

after going to 1 or 2 URL i get error: originalMessage: 'No frame for given id found'
anyone can help my why i am getting this error


问:
12 spaces added in front and at the end when passing jinja2 variable to HTML and I cannot remove it
I have problem with this 12 whitespaces in front and end of everything I send with Jinja2 to HTML.

I tried almost every advice which I found on web and nothing changes.

routes.py

@app.route("/test", methods=["GET", "POST"])
def test():
    form = TestForm()
    if form.validate_on_submit():
        output = test_procesing(test_input=form.test_input.data)
        return render_template("test.html", form=form, output=output)
    return render_template("test.html", form=form)
```
<p>test.py</p>
<pre class="lang-py prettyprint-override"><code>def test_procesing(test_input):
    output = test_input
    return output
</code>```

Template:

            ```
            {{ output }}
            ```

```
<p>Result:
visual result</p>
<p>Result in editor with whitespaces visible:</p>
<pre class="lang-none prettyprint-override"><code>            123456789

</code>```

答:
You're putting those twelve spaces there in your markup. (The <code>```</code> tag is special in that it doesn't consume the inner whitespace in the tag.)</p>
<p>Simply: Instead of</p>
```<code>            ```
            {{ output }}
            ```
</code>```
<p>do</p>
```<code>            ```{{ output }}```
</code>```
<p>or if you do want to keep the three-lined layout, you can add <code>-</code>s to have Jinja eat the whitespace:</p>
```<code>            ```
            {{- output -}}
            ```
</code>```

Body:
I have problem with this 12 whitespaces in front and end of everything I send with Jinja2 to HTML.

I tried almost every advice which I found on web and nothing changes.

routes.py

@app.route("/test", methods=["GET", "POST"])
def test():
    form = TestForm()
    if form.validate_on_submit():
        output = test_procesing(test_input=form.test_input.data)
        return render_template("test.html", form=form, output=output)
    return render_template("test.html", form=form)

test.py

def test_procesing(test_input):
    output = test_input
    return output

Template:

            {{ output }}

Result:
visual result

Result in editor with whitespaces visible:

            123456789

Body:
You're putting those twelve spaces there in your markup. (The <pre> tag is special in that it doesn't consume the inner whitespace in the tag.)

Simply: Instead of

            <pre>
            {{ output }}
            </pre>

do

            <pre>{{ output }}</pre>

or if you do want to keep the three-lined layout, you can add -s to have Jinja eat the whitespace:

            <pre>
            {{- output -}}
            </pre>


问:
.NET Core Web Application with AngularJS - JS Debug not working for JS files in VS Code

VS Code v1.64.2

.NET Core v3.1

AngularJS v1.8.2

I am trying to use Visual Studio Code for debugging .NET Core web application which is using AngularJS. I am able to debug breakpoints placed inside .CS files once I generate .NET: Generate assets for build and debug which creates launch and tasks json files inside .vscode folder.

But the debug points placed in js files of angularJS controller and services are not hitting  eventhough application is running.

Am I missing some settings to be enabled for debug js files while running .NET Core in VS Code?

//// Update Feb 15 2022
I tried with the below launch.json which attaches a Chrome browser launch with the .NET Core build + launch.

Now I am able to debug both C# and Javascript in VSCode. But only issue I am facing: its opening 2 browser instances with localhost:5000. I had to manually close 1 instance which is not attached with debugger.

Is this correct way to debug both JS & C# files which are inside .NET Core web application using AngularJS.

```<code>{
    "compounds": [
        {
            "name": ".Net+Browser",
            "configurations": [ ".NET Core Launch (web)", "Launch Chrome" ]
        }
    ],
    "configurations": [
        {
            "name": "Launch Chrome",
            "request": "launch",
            "type": "chrome",
            "url": "http://localhost:5000",
            "webRoot": "${workspaceFolder}/wwwroot",
            "runtimeArgs": [
                "--disable-web-security"
            ]
        },
    {
        // Use IntelliSense to find out which attributes exist for C# debugging
        // Use hover for the description of the existing attributes
        // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
        "name": ".NET Core Launch (web)",
        "type": "coreclr",
        "request": "launch",
        "preLaunchTask": "build",
        // If you have changed target frameworks, make sure to update the program path.
        "program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/PROJECTNAME.dll",
        "args": [],
        "cwd": "${workspaceFolder}",
        "stopAtEntry": false,
        "serverReadyAction": {
            "action": "openExternally",
            "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
        },
        "env": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        },
        "sourceFileMap": {
            "/Views": "${workspaceFolder}/Views"
        }
    },
    {
        "name": ".NET Core Attach",
        "type": "coreclr",
        "request": "attach"
    }
    ]
}
</code>```

答:
To debug in Visual Studio Code (or any other Editor, IDE), you need to run the app and attach a debugger to it.

In VS Code, you can configure it in .vscode/launch.json file.

For example, I run my app via an NPM script:

npm start run:dev

In such a case, I need to create a .vscode/launch.json file:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch via NPM",
            "request": "launch",
            "runtimeArgs": [
                "run",
                "start:dev"
            ],
            "runtimeExecutable": "npm",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "type": "pwa-node"
        }

    ]
}
```

Whenever I press F5, this debugging configuration will run npm command with arguments start run:dev and then attach a debugger to my application.

All the breakpoints and watches will work.

Visual Studio Code Docs

https://code.visualstudio.com/docs/editor/debugging

To do it by yourself:

Create an empty file .vscode/launch.json.

Find the button "Add Configuration..." in the right bottom corner and click it.

Choose "Node.js: Launch via npm".

Replace "runtimeArgs" with your arguments.

Body:
VS Code v1.64.2

.NET Core v3.1

AngularJS v1.8.2

I am trying to use Visual Studio Code for debugging .NET Core web application which is using AngularJS. I am able to debug breakpoints placed inside .CS files once I generate .NET: Generate assets for build and debug which creates launch and tasks json files inside .vscode folder.

But the debug points placed in js files of angularJS controller and services are not hitting  eventhough application is running.

Am I missing some settings to be enabled for debug js files while running .NET Core in VS Code?

//// Update Feb 15 2022
I tried with the below launch.json which attaches a Chrome browser launch with the .NET Core build + launch.

Now I am able to debug both C# and Javascript in VSCode. But only issue I am facing: its opening 2 browser instances with localhost:5000. I had to manually close 1 instance which is not attached with debugger.

Is this correct way to debug both JS & C# files which are inside .NET Core web application using AngularJS.

{
    "compounds": [
        {
            "name": ".Net+Browser",
            "configurations": [ ".NET Core Launch (web)", "Launch Chrome" ]
        }
    ],
    "configurations": [
        {
            "name": "Launch Chrome",
            "request": "launch",
            "type": "chrome",
            "url": "http://localhost:5000",
            "webRoot": "${workspaceFolder}/wwwroot",
            "runtimeArgs": [
                "--disable-web-security"
            ]
        },
    {
        // Use IntelliSense to find out which attributes exist for C# debugging
        // Use hover for the description of the existing attributes
        // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
        "name": ".NET Core Launch (web)",
        "type": "coreclr",
        "request": "launch",
        "preLaunchTask": "build",
        // If you have changed target frameworks, make sure to update the program path.
        "program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/PROJECTNAME.dll",
        "args": [],
        "cwd": "${workspaceFolder}",
        "stopAtEntry": false,
        "serverReadyAction": {
            "action": "openExternally",
            "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
        },
        "env": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        },
        "sourceFileMap": {
            "/Views": "${workspaceFolder}/Views"
        }
    },
    {
        "name": ".NET Core Attach",
        "type": "coreclr",
        "request": "attach"
    }
    ]
}

Body:
To debug in Visual Studio Code (or any other Editor, IDE), you need to run the app and attach a debugger to it.

In VS Code, you can configure it in .vscode/launch.json file.

For example, I run my app via an NPM script:

npm start run:dev

In such a case, I need to create a .vscode/launch.json file:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch via NPM",
            "request": "launch",
            "runtimeArgs": [
                "run",
                "start:dev"
            ],
            "runtimeExecutable": "npm",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "type": "pwa-node"
        }

    ]
}

Whenever I press F5, this debugging configuration will run npm command with arguments start run:dev and then attach a debugger to my application.

All the breakpoints and watches will work.

Visual Studio Code Docs

https://code.visualstudio.com/docs/editor/debugging

To do it by yourself:

Create an empty file .vscode/launch.json.

Find the button "Add Configuration..." in the right bottom corner and click it.

Choose "Node.js: Launch via npm".

Replace "runtimeArgs" with your arguments.


问:
Saving image list in a dir
```<code>X_image_train = []
for fname in os.listdir(images_dir):
    fpath = os.path.join(images_dir, fname)
    im = Image.open(fpath)
    im_resized = im.resize(dim)
    X_image_train.append(im_resized)
</code>```

I want to save the above X_image_train list as dir in my laptop. How can I do that?

答: If you are using Image objects from the PIL package, simply use im.save('folder/path', 'JPEG') in your foor loop

Title: Saving image list in a dir

Body:
X_image_train = []
for fname in os.listdir(images_dir):
    fpath = os.path.join(images_dir, fname)
    im = Image.open(fpath)
    im_resized = im.resize(dim)
    X_image_train.append(im_resized)

I want to save the above X_image_train list as dir in my laptop. How can I do that?


问:
Failed to terminate ec-2 instance: How to modify its 'disableApiTermination' attribute from EC2 Dashboard?
I opened a free tier instance for some practice.

I tried to terminate it, as I've done many times successfully.

But upon selecting Terminate instance from the dropdown;

I got the following error:

```<code>Failed to terminate the instance <instance id>
The instance '<instance id>' may not be terminated. Modify its 'disableApiTermination' instance attribute and try again.
</code>```

Where can I find the disableApiTermination attribute?

答:
Solution: you need to disable api termination protection by changing instance attribute, I'll demonstrate how to do it with aws api.
(documentation attached)

```<code>instance_id=$(aws ec2 describe-instances \
               --filter "Name=tag:Name,Values=instance-name-example" \
               --query "Reservations[].Instances[].InstanceId[]" \
               --output text)

aws ec2 modify-instance-attribute --instance-id $instance_id  --no-disable-api-termination
</code>```

Body:
I opened a free tier instance for some practice.

I tried to terminate it, as I've done many times successfully.

But upon selecting Terminate instance from the dropdown;

I got the following error:

Failed to terminate the instance <instance id>
The instance '<instance id>' may not be terminated. Modify its 'disableApiTermination' instance attribute and try again.

Where can I find the disableApiTermination attribute?

Body:
Solution: you need to disable api termination protection by changing instance attribute, I'll demonstrate how to do it with aws api.
(documentation attached)

instance_id=$(aws ec2 describe-instances \
               --filter "Name=tag:Name,Values=instance-name-example" \
               --query "Reservations[].Instances[].InstanceId[]" \
               --output text)

aws ec2 modify-instance-attribute --instance-id $instance_id  --no-disable-api-termination


问:
REACT onclick change color of div
I am trying to change each div's color onClick. The problem in my code is that all divs change color when one is clicked. Looking for a way to change each one's color individually

Here is my code :

```<code>class Main extends React.PureComponent {
state = {
    color: 'blue',
};
onChange = () => {
    this.setState({color: 'red'});
};
render() {
    return (
        <Box sx={SX.root}>
            <Box sx={SX.page}>
                <Box sx={SX.shapeContainer}>
                    <div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
                    <div
                        style={{backgroundColor: this.state.color, width: 20, height: 20, opacity: '50%'}}
                        onClick={this.onChange}
                    />
                </Box>
                <MathGrid sx={SX.math1} />
            </Box>

            <Box sx={SX.header} />
            <Box sx={SX.footer} />
        </Box>
    );
}
</code>```

output

Title: REACT onclick change color of div

Body:
I am trying to change each div's color onClick. The problem in my code is that all divs change color when one is clicked. Looking for a way to change each one's color individually

Here is my code :

class Main extends React.PureComponent {
state = {
    color: 'blue',
};
onChange = () => {
    this.setState({color: 'red'});
};
render() {
    return (
        <Box sx={SX.root}>
            <Box sx={SX.page}>
                <Box sx={SX.shapeContainer}>

                </Box>
                <MathGrid sx={SX.math1} />
            </Box>

            <Box sx={SX.header} />
            <Box sx={SX.footer} />
        </Box>
    );
}

output

Body:
Put your state variable like ${this.state.color} in backtick.

<div style={{ backgroundColor: this.state.color , width: 20, height: 20, opacity: "50%" }} onClick={this.onChange}></div>


问:
async-aware mock/override environment variables?
Is there an async-aware way to mock environment variables?

What I want is a context manager that lets me mock the code inside the with block, so that when that code is executing the mock is applied, but it's not applied when other code is executing.

Something like this, but passing:

```<code>import pytest
import os
import asyncio
import mock

async def aaa():
    with mock.patch.dict(os.environ, {"FAVORITE_LETTER": "A"}, clear=True):
        for _ in range(50):
            assert os.environ["FAVORITE_LETTER"] == "A"
            await asyncio.sleep(0)

async def bbb():
    with mock.patch.dict(os.environ, {"FAVORITE_LETTER": "B"}, clear=True):
        for _ in range(50):
            assert os.environ["FAVORITE_LETTER"] == "B"
            await asyncio.sleep(0)

@pytest.mark.asyncio
async def test_mock_env():
    await asyncio.gather(aaa(), bbb())
</code>```

This currently fails with:

```<code>    async def aaa():
        with mock.patch.dict(os.environ, {"FAVORITE_LETTER": "A"}, clear=True):
            for _ in range(50):
>               assert os.environ["FAVORITE_LETTER"] == "A"
E               AssertionError: assert 'B' == 'A'
E                 - A
E                 + B

test_mock_env.py:9: AssertionError
</code>```

=======

Edit:

The accepted answer addresses the question as I asked it, but doesn't solve my problem because I simplified too much when I made the example. My real problem wouldn't make a good example to paste here, but this is closer to my real situation:

```<code>from my_library import some_component_i_control
from someone_elses_library import not_my_code

async def wrap_not_my_code():
    with patch.dict(os.environ, {"ENV_VARS_NEEDED_FOR_COMPONENT_I_DONT_CONTROL": "A"}, clear=True):
        await not_my_code()  # this runs forever but does not block the event loop

@pytest.mark.asyncio
async def test_mock_env():
    task_for_not_my_code = asyncio.create_task(wrap_not_my_code())
    task_for_my_component = asyncio.create_task(some_component_i_control())
    await asyncio.wait([task_for_my_component, task_for_not_my_code], return_when=asyncio.FIRST_COMPLETED)
    # ...
    # Make some assertions about the results
</code>```

I'm trying to test the interaction between a library I control, and one I don't, with the component I don't control seeing a modified version of the environment.

In fact it's even worse: I need multiple instances of the task for the component I don't control, all seeing different environments, and all running concurrently with my own code. Is that possible?

答:
You will need something to allow exclusive access to state, in this case an asyncio.Lock object would work. This requires you to modify the original code to the following.

```<code>import pytest
import os
import asyncio
from unittest.mock import patch

async def aaa(lock):
    for _ in range(50):
        async with lock:
            with patch.dict(os.environ, {"FAVORITE_LETTER": "A"}, clear=True):
                assert os.environ["FAVORITE_LETTER"] == "A"
        await asyncio.sleep(0)

async def bbb(lock):
    for _ in range(50):
        async with lock:
            with patch.dict(os.environ, {"FAVORITE_LETTER": "B"}, clear=True):
                assert os.environ["FAVORITE_LETTER"] == "B"
        await asyncio.sleep(0)

@pytest.mark.asyncio
async def test_mock_env():
    lock = asyncio.Lock()
    await asyncio.gather(aaa(lock), bbb(lock))
</code>```

Body:
Is there an async-aware way to mock environment variables?

What I want is a context manager that lets me mock the code inside the with block, so that when that code is executing the mock is applied, but it's not applied when other code is executing.

Something like this, but passing:

import pytest
import os
import asyncio
import mock

async def aaa():
    with mock.patch.dict(os.environ, {"FAVORITE_LETTER": "A"}, clear=True):
        for _ in range(50):
            assert os.environ["FAVORITE_LETTER"] == "A"
            await asyncio.sleep(0)

async def bbb():
    with mock.patch.dict(os.environ, {"FAVORITE_LETTER": "B"}, clear=True):
        for _ in range(50):
            assert os.environ["FAVORITE_LETTER"] == "B"
            await asyncio.sleep(0)

@pytest.mark.asyncio
async def test_mock_env():
    await asyncio.gather(aaa(), bbb())

This currently fails with:

    async def aaa():
        with mock.patch.dict(os.environ, {"FAVORITE_LETTER": "A"}, clear=True):
            for _ in range(50):
>               assert os.environ["FAVORITE_LETTER"] == "A"
E               AssertionError: assert 'B' == 'A'
E                 - A
E                 + B

test_mock_env.py:9: AssertionError

=======

Edit:

The accepted answer addresses the question as I asked it, but doesn't solve my problem because I simplified too much when I made the example. My real problem wouldn't make a good example to paste here, but this is closer to my real situation:

from my_library import some_component_i_control
from someone_elses_library import not_my_code

async def wrap_not_my_code():
    with patch.dict(os.environ, {"ENV_VARS_NEEDED_FOR_COMPONENT_I_DONT_CONTROL": "A"}, clear=True):
        await not_my_code()  # this runs forever but does not block the event loop

@pytest.mark.asyncio
async def test_mock_env():
    task_for_not_my_code = asyncio.create_task(wrap_not_my_code())
    task_for_my_component = asyncio.create_task(some_component_i_control())
    await asyncio.wait([task_for_my_component, task_for_not_my_code], return_when=asyncio.FIRST_COMPLETED)
    # ...
    # Make some assertions about the results

I'm trying to test the interaction between a library I control, and one I don't, with the component I don't control seeing a modified version of the environment.

In fact it's even worse: I need multiple instances of the task for the component I don't control, all seeing different environments, and all running concurrently with my own code. Is that possible?

Body:
You will need something to allow exclusive access to state, in this case an asyncio.Lock object would work. This requires you to modify the original code to the following.

import pytest
import os
import asyncio
from unittest.mock import patch

async def aaa(lock):
    for _ in range(50):
        async with lock:
            with patch.dict(os.environ, {"FAVORITE_LETTER": "A"}, clear=True):
                assert os.environ["FAVORITE_LETTER"] == "A"
        await asyncio.sleep(0)

async def bbb(lock):
    for _ in range(50):
        async with lock:
            with patch.dict(os.environ, {"FAVORITE_LETTER": "B"}, clear=True):
                assert os.environ["FAVORITE_LETTER"] == "B"
        await asyncio.sleep(0)

@pytest.mark.asyncio
async def test_mock_env():
    lock = asyncio.Lock()
    await asyncio.gather(aaa(lock), bbb(lock))


问:
How to sanitize user input string in nodejs, before injecting it in a template engine or say simple JS template string?
I have webpages (basically business cards) whose titles are created based on user inputs.
I am planning to use simple JS template string for this purpose, instead of some template engine. (I am using express.js/node.js for this purpose)

response.send(`

  <title>${user_inputed_title_got_from_DB}</title>
  <meta property="og:title" content="${some_more_user_content}" />

`)
```

How to avoid XSS injection from a malacious user?

答:
For normal HTML tags, this answer should suffice:

function escapeHtml(unsafe)
{
    return unsafe
         .replace(/&/g, "&")
         .replace(/</g, "<")
         .replace(/>/g, ">")
         .replace(/"/g, """)
         .replace(/'/g, "'");
 }
```
<p>However, your redirect in the script tag needs to be treated a bit more carefully. One common approach is to put the redirect in an attribute, which can be escaped with the above function:</p>
<pre class="lang-js prettyprint-override"><code><script data-redir="/business-card/${escapeHtml(user_input_number)}">
    window.location.href = document.currentScript.dataset.redir;
</script>
</code>```

Body:
I have webpages (basically business cards) whose titles are created based on user inputs.
I am planning to use simple JS template string for this purpose, instead of some template engine. (I am using express.js/node.js for this purpose)

response.send(`

  <title>${user_inputed_title_got_from_DB}</title>
  <meta property="og:title" content="${some_more_user_content}" />

`)

How to avoid XSS injection from a malacious user?

Body:
For normal HTML tags, this answer should suffice:

function escapeHtml(unsafe)
{
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

However, your redirect in the script tag needs to be treated a bit more carefully. One common approach is to put the redirect in an attribute, which can be escaped with the above function:

<script data-redir="/business-card/${escapeHtml(user_input_number)}">
    window.location.href = document.currentScript.dataset.redir;
</script>


答:
Both divs are using the “color” state value. You’ll need to use two separate pieces of state to manage the color of these two divs independently.

You’ll also need to either add another onChange handler, or modify the existing one to accept a color as an argument.

Title: REACT onclick change color of div


问:
In Python, how to make a custom type to describe a more specific type hints?
I am running a script using openpyxl and i have some function copy_value that shows like this:

```<code>from openpyxl.workbook.workbook import Workbook

def copy_value(source: Workbook, target: Workbook, cell: str) -> None:
    do something...
</code>```

Now my concern is that the type hint for argument cell is a just a generic str. I want to have a custom and more specific typing, say Cell (which is also a str), so that the user will know that this argument will take not just any other string like 'abc' or '123worksheet', but must be a valid cell like 'D12' or 'AA345'.

Or how else to properly do this?

答:
If you want to have this validation with type hinting, You could do something like

```<code>class Cell(str):
    def __new__(cls, cell_identifier: str):
        if not cell_identifier.startswith('abc'):  # Add your string validation logic here
            raise ValueError('Cell identifier is not valid!')

        return str.__new__(cls, cell_identifier)
</code>```

then your function would be like

```<code>def copy_value(source: Workbook, target: Workbook, cell: Cell) -> None:
    do something...
</code>```

Note that type hinting is aimed to check the type of variables, not their runtime value.
Type hinting does not ensure the parameters passed to your function are from the hinted type and therefore does not guarantee that they follow your desired string pattern.
Inheriting from primitive types is not very common, and generally not needed.

If the validation is important, it's up to you to validate the data. Either when calling the function and passing the parameters, or even better in your function such as

```<code>def copy_value(source: Workbook, target: Workbook, cell: str) -> None:
    if cell.startswith('abc'):  # Your validation logic here
            raise ValueError('Cell identifier is not valid!')
    do something...
</code>```

Body:
I am running a script using openpyxl and i have some function copy_value that shows like this:

from openpyxl.workbook.workbook import Workbook

def copy_value(source: Workbook, target: Workbook, cell: str) -> None:
    do something...

Now my concern is that the type hint for argument cell is a just a generic str. I want to have a custom and more specific typing, say Cell (which is also a str), so that the user will know that this argument will take not just any other string like 'abc' or '123worksheet', but must be a valid cell like 'D12' or 'AA345'.

Or how else to properly do this?

Body:
If you want to have this validation with type hinting, You could do something like

class Cell(str):
    def __new__(cls, cell_identifier: str):
        if not cell_identifier.startswith('abc'):  # Add your string validation logic here
            raise ValueError('Cell identifier is not valid!')

        return str.__new__(cls, cell_identifier)

then your function would be like

def copy_value(source: Workbook, target: Workbook, cell: Cell) -> None:
    do something...

Note that type hinting is aimed to check the type of variables, not their runtime value.
Type hinting does not ensure the parameters passed to your function are from the hinted type and therefore does not guarantee that they follow your desired string pattern.
Inheriting from primitive types is not very common, and generally not needed.

If the validation is important, it's up to you to validate the data. Either when calling the function and passing the parameters, or even better in your function such as

def copy_value(source: Workbook, target: Workbook, cell: str) -> None:
    if cell.startswith('abc'):  # Your validation logic here
            raise ValueError('Cell identifier is not valid!')
    do something...


问:
Create another Widget when OnTap() is triggered
Does anyone know how to generate a new widget in Flutter when OnTap() is triggered?

In my case, I want to create a new column inside a container, when the column icon is pressed.

The icon is wrapped with an InkWell().

InkWell(
  onTap: () {
    print("Create Column in another Container");
  },
  child: Column(
    children: const [
      Icon(
        Icons.view_agenda,
        color: iconGreyColor,
        size: 20.0,
      ),
    ],
  ),
),

```
<p>The Goal shut look like this.</p>
<pre class="lang-dart prettyprint-override"><code>    Container(child: Column(children:[]),)
</code>```

答:
You can implement this using StatefulWidget(). Create a List<Widget> outside your build of StatefulWidget() and inside your InkWell() append new Widget() you want to add and call setState((){})

```<code>class YellowBird extends StatefulWidget {
  const YellowBird({Key? key}) : super(key: key);

@override
  State<YellowBird> createState() => _YellowBirdState();
}

class _YellowBirdState extends State<YellowBird> {
List<Widget> myWidgetList = [
  Text("hello"),
];
@override
Widget build(BuildContext context) {
  return Column(
    children: [
      InkWell(
        onTap: () {
          print("Create Column in another Container");
          myWidgetList.add(Text("hello 2"));
          setState(() {});
        },
        child: Column(
          children: const [
            Icon(
              Icons.view_agenda,
              size: 20.0,
            ),
          ],
        ),
      ),
      Column(
        children: myWidgetList,
      ),
    ],
  );
 }
}
</code>```

You can run same code here Link

Body:
Does anyone know how to generate a new widget in Flutter when OnTap() is triggered?

In my case, I want to create a new column inside a container, when the column icon is pressed.

The icon is wrapped with an InkWell().

InkWell(
  onTap: () {
    print("Create Column in another Container");
  },
  child: Column(
    children: const [
      Icon(
        Icons.view_agenda,
        color: iconGreyColor,
        size: 20.0,
      ),
    ],
  ),
),

The Goal shut look like this.

    Container(child: Column(children:[]),)

Body:
You can implement this using StatefulWidget(). Create a List<Widget> outside your build of StatefulWidget() and inside your InkWell() append new Widget() you want to add and call setState((){})

class YellowBird extends StatefulWidget {
  const YellowBird({Key? key}) : super(key: key);

@override
  State<YellowBird> createState() => _YellowBirdState();
}

class _YellowBirdState extends State<YellowBird> {
List<Widget> myWidgetList = [
  Text("hello"),
];
@override
Widget build(BuildContext context) {
  return Column(
    children: [
      InkWell(
        onTap: () {
          print("Create Column in another Container");
          myWidgetList.add(Text("hello 2"));
          setState(() {});
        },
        child: Column(
          children: const [
            Icon(
              Icons.view_agenda,
              size: 20.0,
            ),
          ],
        ),
      ),
      Column(
        children: myWidgetList,
      ),
    ],
  );
 }
}

You can run same code here Link


问:
Change values in np array Python
I am trying to change the value in np array if there is a match

For example, a np array a and its shape is (50,4)

```<code>a.shape#(50,4)
</code>```

I need to check if the np array a has this value [0,1,20,4] in the 1st axis, then I need to change that into [-1,-1,-1,-1].

I tried this format -

```<code>a[a==[0,1,20,4]]=[-1,-1,-1,-1]
</code>```

But, this is not working,

How to do this modification?

Title: Change values in np array Python

Body:
I am trying to change the value in np array if there is a match

For example, a np array a and its shape is (50,4)

a.shape#(50,4)

I need to check if the np array a has this value [0,1,20,4] in the 1st axis, then I need to change that into [-1,-1,-1,-1].

I tried this format -

a[a==[0,1,20,4]]=[-1,-1,-1,-1]

But, this is not working,

How to do this modification?

Body:
Maybe try doing row-wise comparison with np.tile and np.argwhere like this:

import numpy as np

# Create dummy data
x = np.random.randint(29, size=(49, 4))
x = np.concatenate([[[0,1,20,4]], x])
print('Before --> \n', x)

# Compare row-wise
x[np.argwhere(np.all(x==np.reshape(np.tile([0,1,20,4], reps=x.shape[0]), x.shape),axis=1))] = [-1,-1,-1,-1]

print('After --> \n', x)

Before -->
 [[ 0  1 20  4]
 [ 1 17  5  2]
 [19  8 24 17]
 [ 1 23 16  3]
 [ 0 15  0 20]
 [14 23  9 23]
 [ 1 27  5 27]
 [15 24 24 17]
 [ 2 28  8  4]
 [26 26  6 10]
 [18 13  5 28]
 [10 25 18 15]
 [ 6 17  8  2]
 [ 4 26 26 15]
 [18 16 18 24]
 [ 0 11 15 22]
 [20 27  0  0]
 [ 9 22 16  2]
 [22 11  8 23]
 [21 10  6 23]
 [14 16  0 10]
 [14 27 22  9]
 [ 4  0 10 15]
 [12  0 28 25]
 [ 8 28  9 28]
 [12  3 26 24]
 [23  3 26 25]
 [ 0  6 16  4]
 [ 1 20  1 19]
 [11  5  9 11]
 [20 15 18  5]
 [25  0 17 27]
 [20 24  3 19]
 [13 12 17  4]
 [ 1 13 25 22]
 [27 10 11 18]
 [ 4  5 12  8]
 [11 19 17 15]
 [26  7  3 10]
 [21 14 27 21]
 [26 12  8 13]
 [27  8  1 17]
 [20 28  0 20]
 [ 1 12 11 16]
 [ 4  0  3 22]
 [11 12  3  8]
 [15 24  3  8]
 [ 4 23 17 20]
 [21  1 23 12]
 [ 0 27  3 22]
 [15  5 17 28]]
After -->
 [[-1 -1 -1 -1]
 [ 1 17  5  2]
 [19  8 24 17]
 [ 1 23 16  3]
 [ 0 15  0 20]
 [14 23  9 23]
 [ 1 27  5 27]
 [15 24 24 17]
 [ 2 28  8  4]
 [26 26  6 10]
 [18 13  5 28]
 [10 25 18 15]
 [ 6 17  8  2]
 [ 4 26 26 15]
 [18 16 18 24]
 [ 0 11 15 22]
 [20 27  0  0]
 [ 9 22 16  2]
 [22 11  8 23]
 [21 10  6 23]
 [14 16  0 10]
 [14 27 22  9]
 [ 4  0 10 15]
 [12  0 28 25]
 [ 8 28  9 28]
 [12  3 26 24]
 [23  3 26 25]
 [ 0  6 16  4]
 [ 1 20  1 19]
 [11  5  9 11]
 [20 15 18  5]
 [25  0 17 27]
 [20 24  3 19]
 [13 12 17  4]
 [ 1 13 25 22]
 [27 10 11 18]
 [ 4  5 12  8]
 [11 19 17 15]
 [26  7  3 10]
 [21 14 27 21]
 [26 12  8 13]
 [27  8  1 17]
 [20 28  0 20]
 [ 1 12 11 16]
 [ 4  0  3 22]
 [11 12  3  8]
 [15 24  3  8]
 [ 4 23 17 20]
 [21  1 23 12]
 [ 0 27  3 22]
 [15  5 17 28]]


问:
Polyfit Function with Stock Prices from yfinance
i have the following issue to solve:
I want to download stockdata from yfinance and store that into a dataframe.

Then, instead of just plotting the data via matplotlib i additionally want to approximate the movement of that chart with a polynomial function, in order to be able to perform the derivatives of that function and apply some analysis.

Therefore i thought it might a solution to apply the polyfit function and feed the stock data into that.

Please let me know, if there would be a more appropiate solution to my goal. This is what i can conclude so far.

Going with my approach, i came up with this Code:

```<code>import yfinance as yf
import matplotlib.pyplot as plt
import numpy as np

stock = 'TSLA'
start = '2020-11-01'

df = yf.download(stock , start=start)

x_data = df.index
y_data = df['Close']

xx = np.asarray(x_data).astype(int)
yy = np.asarray(y_data).astype(int)

x = np.linspace(200, 15.0, 200)

# polynomial fit of degree 7
p7 = np.polyfit(xx, yy, 7)
y_p7 = np.polyval(p7, x)

#plotting
plt.plot(xx, yy, 'o')
plt.plot(x, y_p7, ':')
plt.ylim(0.,1200)

plt.legend(['data', 'polyfit7'])
plt.show()
</code>```

However what comes out when i run this, is the following plot:

This might come, because the Polyfitfunction dont know how to interprete the converted timestamp dates.

In this sense, i thought i could be a solution to connect the days (datetime) to simple and uprising integers (numbers) starting from 1 up and ongoing.

What are your thoughts on this? should i use another approach or can i fix this one?

Best wishes and many thanks,
Benjamin

答:
The approach of converting timestamp dates to integers works fine, you just need to match the x-coordinates sample points used in the fit with the polyval step. Here I'm using min and max to obtain the full range of dates used in the polyfit. For the plot you can then convert the dates back using astype('datetime64[ns]').

...
xx = np.asarray(x_data).astype(int)
yy = np.asarray(y_data).astype(int)

x = np.linspace(min(xx), max(xx), 200)
# polynomial fit of degree 7
p7 = np.polyfit(xx, yy, 7)
y_p7 = np.polyval(p7, x)

#plotting
plt.plot(xx.astype('datetime64[ns]'), yy, 'o')
plt.plot(x.astype('datetime64[ns]'), y_p7, '.', ms=4)

plt.xticks(rotation=45)
plt.legend(['data', 'polyfit7'])
plt.show()
```

Body:
i have the following issue to solve:
I want to download stockdata from yfinance and store that into a dataframe.

Then, instead of just plotting the data via matplotlib i additionally want to approximate the movement of that chart with a polynomial function, in order to be able to perform the derivatives of that function and apply some analysis.

Therefore i thought it might a solution to apply the polyfit function and feed the stock data into that.

Please let me know, if there would be a more appropiate solution to my goal. This is what i can conclude so far.

Going with my approach, i came up with this Code:

import yfinance as yf
import matplotlib.pyplot as plt
import numpy as np

stock = 'TSLA'
start = '2020-11-01'

df = yf.download(stock , start=start)

x_data = df.index
y_data = df['Close']

xx = np.asarray(x_data).astype(int)
yy = np.asarray(y_data).astype(int)

x = np.linspace(200, 15.0, 200)

# polynomial fit of degree 7
p7 = np.polyfit(xx, yy, 7)
y_p7 = np.polyval(p7, x)

#plotting
plt.plot(xx, yy, 'o')
plt.plot(x, y_p7, ':')
plt.ylim(0.,1200)

plt.legend(['data', 'polyfit7'])
plt.show()

However what comes out when i run this, is the following plot:

This might come, because the Polyfitfunction dont know how to interprete the converted timestamp dates.

In this sense, i thought i could be a solution to connect the days (datetime) to simple and uprising integers (numbers) starting from 1 up and ongoing.

What are your thoughts on this? should i use another approach or can i fix this one?

Best wishes and many thanks,
Benjamin


问:
Laravel Sum with where and alias with Eloquent
I have this query for an old Codeigniter project:

```<code>$this->db->select("SUM(source = 'FBS) AS facebook");
$this->db->select("SUM(source = 'FBS' AND promotion = 0) AS facebook_promotion");
$this->db->select("SUM(source = 'IG') AS instagram");
$this->db->select("SUM(source = 'LP') AS landing_page");
</code>```

I'd like to have same result using Laravel, if is possible with Eloquent instead of Query Builder or Raw Query.

答:
If you want to use raw Query Builder, it would be like,

```<code>DB::table('table_name')->where('source','=','FBS')->sum('source');
</code>```

For Eloquent Models,

```<code> Model::where('source','=','FBS')->sum('source')
</code>```

It also works with eloquent relationship.

Besides, for multiple sum results like yours, it would be like,

DB::table('table_name')->get( array(
  DB::raw("SUM(source = 'FBS) AS facebook"),
  DB::raw("SUM(source = 'FBS' AND promotion = 0) AS facebook_promotion"),
));
```

Body:
I have this query for an old Codeigniter project:

$this->db->select("SUM(source = 'FBS) AS facebook");
$this->db->select("SUM(source = 'FBS' AND promotion = 0) AS facebook_promotion");
$this->db->select("SUM(source = 'IG') AS instagram");
$this->db->select("SUM(source = 'LP') AS landing_page");

I'd like to have same result using Laravel, if is possible with Eloquent instead of Query Builder or Raw Query.

Body:
If you want to use raw Query Builder, it would be like,

DB::table('table_name')->where('source','=','FBS')->sum('source');

For Eloquent Models,

 Model::where('source','=','FBS')->sum('source')

It also works with eloquent relationship.

Besides, for multiple sum results like yours, it would be like,

DB::table('table_name')->get( array(
  DB::raw("SUM(source = 'FBS) AS facebook"),
  DB::raw("SUM(source = 'FBS' AND promotion = 0) AS facebook_promotion"),
));


问:
How to achieve the following? C++ "advanced" map/list/array?
I am trying to create some sort of list, map or what ever may be suggested that does the following

```<code>something [] = {
        mainvalue1 = 2001 {
            value2 = 1905
            value3 = 2000
            result = 500

            value2 = 1910
            value3 = 2030
            result = 700
        }
        mainvalue2 = 2005 {
            value2 = 1635
            value3 = 2070
            result = 300

            value2 = 2310
            value3 = 5930
            result = 599
        }
}
</code>```

cout << "result: " << something[2001][1905][2000] << endl;

result: 500

cout << "result: " something[2001][1910][2030] << endl;

result: 700

cout << "result: " something[2005][2310][5930] << endl;

result: 599

Is this possible? I would appreciate if someone could guide me how to start my thought process or give me an example how this can be achievable in C++

答:
I find your structure utterly confusing, but it's possible to make the lookup nearly like you want it:

#include <iostream>
#include <map>
#include <vector>

int main() {
    std::map<int, std::map<std::vector<int>, int>> something{
        {2001, {
            {{1905, 2000}, 500},
            {{1910, 2030}, 700}
        }},
        {2005, {
            {{1635, 2070}, 300},
            {{2310, 5930}, 599}
        }}
    };

    std::cout << "result: " << something[2001][{1905,2000}] << '\n';
    //>> result: 500

    std::cout << "result: " << something[2001][{1910,2030}] << '\n';
    //>> result: 700

    std::cout << "result: " << something[2005][{2310,5930}] << '\n';
    //>> result: 599
}
```
<p>If there are always <em>two</em> values (<code>value2</code> and <code>value3</code>) in the above <code>std::vector<int></code>, you can replace it with a <code>std::pair<int, int></code> instead:</p>
<pre class="lang-cpp prettyprint-override"><code>std::map<int, std::map<std::pair<int, int>, int>> something[...};
</code>```

Note: A std::map is ordered (with respect to the keys in the map). If you don't need it to be ordered you can replace the outer std::map with a std::unordered_map. The lookup and insertion etc. is usually a bit quicker that way.

#include <unordered_map>
//...
std::unordered_map<int, std::map<std::pair<int, int>, int>> something{...};
```

Body:
I am trying to create some sort of list, map or what ever may be suggested that does the following

something [] = {
        mainvalue1 = 2001 {
            value2 = 1905
            value3 = 2000
            result = 500

            value2 = 1910
            value3 = 2030
            result = 700
        }
        mainvalue2 = 2005 {
            value2 = 1635
            value3 = 2070
            result = 300

            value2 = 2310
            value3 = 5930
            result = 599
        }
}

cout << "result: " << something[2001][1905][2000] << endl;

result: 500

cout << "result: " something[2001][1910][2030] << endl;

result: 700

cout << "result: " something[2005][2310][5930] << endl;

result: 599

Is this possible? I would appreciate if someone could guide me how to start my thought process or give me an example how this can be achievable in C++

Body:
I find your structure utterly confusing, but it's possible to make the lookup nearly like you want it:

#include <iostream>
#include <map>
#include <vector>

int main() {
    std::map<int, std::map<std::vector<int>, int>> something{
        {2001, {
            {{1905, 2000}, 500},
            {{1910, 2030}, 700}
        }},
        {2005, {
            {{1635, 2070}, 300},
            {{2310, 5930}, 599}
        }}
    };

    std::cout << "result: " << something[2001][{1905,2000}] << '\n';
    //>> result: 500

    std::cout << "result: " << something[2001][{1910,2030}] << '\n';
    //>> result: 700

    std::cout << "result: " << something[2005][{2310,5930}] << '\n';
    //>> result: 599
}

If there are always two values (value2 and value3) in the above std::vector<int>, you can replace it with a std::pair<int, int> instead:

std::map<int, std::map<std::pair<int, int>, int>> something[...};

Note: A std::map is ordered (with respect to the keys in the map). If you don't need it to be ordered you can replace the outer std::map with a std::unordered_map. The lookup and insertion etc. is usually a bit quicker that way.

#include <unordered_map>
//...
std::unordered_map<int, std::map<std::pair<int, int>, int>> something{...};


问:
Can a Base64 String contain tabs?
Simple yes or no question, and I'm 90% sure that it is no... but I'm not sure.

Can a Base64 string contain tabs?

答:
It seems that there is lots of confusion here; and surprisingly most answers are of "No" variety. I don't think that is a good canonical answer.
The reason for confusion is probably the fact that Base64 is not strictly specified; multiple practical implementations and interpretations exist.
You can check out link text for more discussion on this.

In general, however, conforming base64 codecs SHOULD understand linefeeds, as they are mandated by some base64 definitions (76 character segments, then linefeed etc).
Because of this, most decoders also allow for indentation whitespace, and quite commonly any whitespace between 4-character "triplets" (so named since they encode 3 bytes).

So there's a good chance that in practice you can use tabs and other white space.

But I would not add tabs myself if generating base64 content sent to a service -- be conservative at what you send, (more) liberal at what you receive.

OwnerDisplayName: Jason

ContentLicense: CC BY-SA 2.5

Title: Can a Base64 String contain tabs?

OwnerDisplayName: StaxMan


问:
Git push halts on "Writing Objects: 100%"
I have set up a linux box with a Git repository (using xinetd).

I have enabled receive-pack for the git daemon to enable pushing to the repository.

Here's my current testing workflow:

On git server, run:

mkdir something

cd something

git init --bare

On a client box:

git clone git://server/repo

(msg about cloning an empty repository)

Perform some commits to the cloned repository.

git push

getting this msg:

```<code>Counting objects: 8, done.
Compressing objects: 100% (3/3) done,
Writing objects: 100% (6/6)
</code>```

This does not finish. I have introduced only a small change, so this should be completed very quickly.

am i doing something wrong here?

答:
The issue is with mgitsys client

Read more here: MGitsys Bug

As a workaround, i am using an older version: git version 1.7.4.rc1.3197.gbf965

This one doesn't have this bug in it.

I have placed this specific build in my SkyDrive public folder, link: http://sdrv.ms/MeuWTD

Hopefully it will be fixed in the near future.

Body:
I have set up a linux box with a Git repository (using xinetd).

I have enabled receive-pack for the git daemon to enable pushing to the repository.

Here's my current testing workflow:

On git server, run:

mkdir something

cd something

git init --bare

On a client box:

git clone git://server/repo

(msg about cloning an empty repository)

Perform some commits to the cloned repository.

git push

getting this msg:

Counting objects: 8, done.
Compressing objects: 100% (3/3) done,
Writing objects: 100% (6/6)

This does not finish. I have introduced only a small change, so this should be completed very quickly.

am i doing something wrong here?


问:
Problem with loading module ‘Distribution.Simple’
I was trying to build one new project in Haskell (GHC version 8.10.4, stack version 2.7.3, cabal version 3.6.2.0) using stack, but at the time of running the command stack setup I (surprisingly) got the following error:

```<code>Setup.hs:2:1: error:
    Could not load module ‘Distribution.Simple’
    It is a member of the hidden package ‘Cabal-3.2.1.0’.
    You can run ‘:set -package Cabal’ to expose it.
    (Note: this unloads all the modules in the current scope.)
    Use -v (or `:set -v` in ghci) to see a list of the files searched for.
  |
2 | import Distribution.Simple
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

Also, it is worth noting that I was trying to look for different solutions on the Internet, but didn't find the working one for me. The general idea was to explicitly add Cabal into the package.yaml file here:

```<code>library:
  source-dirs: src
  dependencies:
    - Cabal
</code>```

But that didn't save my situation. I was able to build the project without that step (well, just skipped that part), but I was interested to solve the issue.

Moreover, when I was trying to build Haskell package timeit (as an example, using the command line), there was the same error at the time of executing
runhaskell Setup.hs configure.

Interestingly, I didn't have this problem before (probably, it appeared after I updated GHC).

Does anybody know any ways of how to deal with such issue? Is there any way probably to reinstall the GHC, or cabal, or stack (if it helps)? Would be glad to see any comments and solutions.

答:
Instead of deleting the

~/.ghc/*/environments/default

file, just add the Cabal package to it, including version number, which you can find if you run the command:

```<code>ghc-pkg list
</code>```

Body:
I was trying to build one new project in Haskell (GHC version 8.10.4, stack version 2.7.3, cabal version 3.6.2.0) using stack, but at the time of running the command stack setup I (surprisingly) got the following error:

Setup.hs:2:1: error:
    Could not load module ‘Distribution.Simple’
    It is a member of the hidden package ‘Cabal-3.2.1.0’.
    You can run ‘:set -package Cabal’ to expose it.
    (Note: this unloads all the modules in the current scope.)
    Use -v (or `:set -v` in ghci) to see a list of the files searched for.
  |
2 | import Distribution.Simple
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^

Also, it is worth noting that I was trying to look for different solutions on the Internet, but didn't find the working one for me. The general idea was to explicitly add Cabal into the package.yaml file here:

library:
  source-dirs: src
  dependencies:
    - Cabal

But that didn't save my situation. I was able to build the project without that step (well, just skipped that part), but I was interested to solve the issue.

Moreover, when I was trying to build Haskell package timeit (as an example, using the command line), there was the same error at the time of executing
runhaskell Setup.hs configure.

Interestingly, I didn't have this problem before (probably, it appeared after I updated GHC).

Does anybody know any ways of how to deal with such issue? Is there any way probably to reinstall the GHC, or cabal, or stack (if it helps)? Would be glad to see any comments and solutions.

Body:
Instead of deleting the

~/.ghc/*/environments/default

file, just add the Cabal package to it, including version number, which you can find if you run the command:

ghc-pkg list