问:
NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference

java.lang.NullPointerException:Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference

Logcat

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
        at com.marsad.earningapp.activity.RegisterActivity$4.onComplete(RegisterActivity.java:138)
        at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6711)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
</code>```

Error

reference.child(currentUser.getUid()).setValue(userInformation).addOnSuccessListener(new OnSuccessListener() {...

Here is the RegisterActivity.java

```<code>public class RegisterActivity extends AppCompatActivity {

    private EditText nameEdit, emailEdit, phoneEdit, passwordEdit;
    private Button loginBtn, signupBtn;

    private static final String TAG = "SignUpActivity";
    String defaultImage = "https://firebasestorage.googleapis.com/v0/b/earning-app-27780.appspot.com/o/woman.png?alt=media&token=4d66f140-4bd9-4a25-9838-cca28ebf48bb";

    private FirebaseDatabase userinfoDatabase;
    private DatabaseReference reference;
    private FirebaseAuth mAuth;
    private FirebaseUser currentUser;
    private SweetAlertDialog sweetAlertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        nameEdit = findViewById(R.id.nameEditSignup);
        emailEdit = findViewById(R.id.emailEditSignup);
        phoneEdit = findViewById(R.id.phoneEditSignup);
        passwordEdit = findViewById(R.id.passwordEditSignup);
        loginBtn = findViewById(R.id.loginBtnSignup);
        signupBtn = findViewById(R.id.registerBTn);

        userinfoDatabase = FirebaseDatabase.getInstance();
        reference = userinfoDatabase.getReference("Users");
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });

        signupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameEdit.getText().toString();
                String phone = phoneEdit.getText().toString();

                if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone)){

                    if (TextUtils.isEmpty(name)){
                        nameEdit.setError("Enter Your Name");
                        nameEdit.requestFocus();
                    }

                    if (TextUtils.isEmpty(phone)){
                        phoneEdit.setError("Enter Your Phone Number");
                        phoneEdit.requestFocus();
                    }

                } else {

                    showRegisterDialog();
                    authenticationListener();

                }
            }
        });

    }

    private void authenticationListener(){

        final String email = emailEdit.getText().toString();
        final String password = passwordEdit.getText().toString();

        if(TextUtils.isEmpty(email) && TextUtils.isEmpty(password)){

            if (TextUtils.isEmpty(email)){
                emailEdit.setError("Enter Your Email");
                emailEdit.requestFocus();
            }
            if (TextUtils.isEmpty(password)){
                passwordEdit.setError("Enter Your Password");
                passwordEdit.requestFocus();
            }

        } else
            mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    RegisterModel userInformation = new RegisterModel();

                    userInformation.setEmail(email);
                    userInformation.setName(nameEdit.getText().toString());
                    userInformation.setPassword(password);
                    userInformation.setPhone(phoneEdit.getText().toString());
                    userInformation.setRupees(0);
                    userInformation.setPoints(0);
                    userInformation.setImage(defaultImage);

                    reference.child(currentUser.getUid()).setValue(userInformation).addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            //user registered successfully
                            sweetAlertDialog.dismissWithAnimation();
                            startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                            finish();

                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            //user failed to register
                            sweetAlertDialog.dismissWithAnimation();
                            showRegisterErrorDialog();
                        }
                    });

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    //Error
                    sweetAlertDialog.dismissWithAnimation();
                    showRegisterErrorDialog();
                }
            });

    }
}
</code>```

答:
The following lines of code</p>

```<code>String currentUserId;
</code>```

```<code>mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();

if(currentUser!= null) {
    currentUserId = currentUser.getUid(); //Do what you need to do with the id
}
</code>```

Body:
java.lang.NullPointerException:Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference

Logcat

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
        at com.marsad.earningapp.activity.RegisterActivity$4.onComplete(RegisterActivity.java:138)
        at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6711)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)

Error

reference.child(currentUser.getUid()).setValue(userInformation).addOnSuccessListener(new OnSuccessListener() {...

Here is the RegisterActivity.java

public class RegisterActivity extends AppCompatActivity {

    private EditText nameEdit, emailEdit, phoneEdit, passwordEdit;
    private Button loginBtn, signupBtn;

    private static final String TAG = "SignUpActivity";
    String defaultImage = "https://firebasestorage.googleapis.com/v0/b/earning-app-27780.appspot.com/o/woman.png?alt=media&token=4d66f140-4bd9-4a25-9838-cca28ebf48bb";

    private FirebaseDatabase userinfoDatabase;
    private DatabaseReference reference;
    private FirebaseAuth mAuth;
    private FirebaseUser currentUser;
    private SweetAlertDialog sweetAlertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        nameEdit = findViewById(R.id.nameEditSignup);
        emailEdit = findViewById(R.id.emailEditSignup);
        phoneEdit = findViewById(R.id.phoneEditSignup);
        passwordEdit = findViewById(R.id.passwordEditSignup);
        loginBtn = findViewById(R.id.loginBtnSignup);
        signupBtn = findViewById(R.id.registerBTn);

        userinfoDatabase = FirebaseDatabase.getInstance();
        reference = userinfoDatabase.getReference("Users");
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });

        signupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameEdit.getText().toString();
                String phone = phoneEdit.getText().toString();

                if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone)){

                    if (TextUtils.isEmpty(name)){
                        nameEdit.setError("Enter Your Name");
                        nameEdit.requestFocus();
                    }

                    if (TextUtils.isEmpty(phone)){
                        phoneEdit.setError("Enter Your Phone Number");
                        phoneEdit.requestFocus();
                    }

                } else {

                    showRegisterDialog();
                    authenticationListener();

                }
            }
        });

    }

    private void authenticationListener(){

        final String email = emailEdit.getText().toString();
        final String password = passwordEdit.getText().toString();

        if(TextUtils.isEmpty(email) && TextUtils.isEmpty(password)){

            if (TextUtils.isEmpty(email)){
                emailEdit.setError("Enter Your Email");
                emailEdit.requestFocus();
            }
            if (TextUtils.isEmpty(password)){
                passwordEdit.setError("Enter Your Password");
                passwordEdit.requestFocus();
            }

        } else
            mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    RegisterModel userInformation = new RegisterModel();

                    userInformation.setEmail(email);
                    userInformation.setName(nameEdit.getText().toString());
                    userInformation.setPassword(password);
                    userInformation.setPhone(phoneEdit.getText().toString());
                    userInformation.setRupees(0);
                    userInformation.setPoints(0);
                    userInformation.setImage(defaultImage);

                    reference.child(currentUser.getUid()).setValue(userInformation).addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            //user registered successfully
                            sweetAlertDialog.dismissWithAnimation();
                            startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                            finish();

                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            //user failed to register
                            sweetAlertDialog.dismissWithAnimation();
                            showRegisterErrorDialog();
                        }
                    });

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    //Error
                    sweetAlertDialog.dismissWithAnimation();
                    showRegisterErrorDialog();
                }
            });

    }
}

Body:
The following lines of code

String currentUserId;

mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();

if(currentUser!= null) {
    currentUserId = currentUser.getUid(); //Do what you need to do with the id
}


来源: stackexchange

问:
Multiple student entry using structure and functions in cpp
I used structure for multiple entry of students. But I am getting error in the following code:

```<code>#include <iostream>
using namespace std;
struct Student{
   char stuName[30];
   int stuRollNo;
   int stuAge;
};

void printStudentInfo(struct Student s[]);

int main(){
    int i;
    for(i=0;i<3;i++){
   Student s[i];
   cout<<"Enter Student Name: ";
   cin.getline(s[i].stuName, 30);
   cout<<"Enter Student Roll No: ";
   cin>>s[i].stuRollNo;
   cout<<"Enter Student Age: ";
   cin>>s[i].stuAge;
   printStudentInfo(s[i]);}
   return 0;
}

void printStudentInfo(struct Student s[i]){
   cout<<"Student Record:"<<endl;
   cout<<"Name: "<<s[i].stuName<<endl;
   cout<<"Roll No: "<<s[i].stuRollNo<<endl;
   cout<<"Age: "<<s[i].stuAge;
}
</code>```

error:

```<code>main.cpp:29:25: error: cannot convert ‘Student’ to ‘Student*’ for argument ‘1’ to ‘void printStudentInfo(Student*)’
    printStudentInfo(s[i]);}
                         ^
main.cpp: At global scope:
main.cpp:33:40: error: ‘i’ was not declared in this scope
 void printStudentInfo(struct Student s[i]){
                                        ^
main.cpp: In function ‘void printStudentInfo(...)’:
main.cpp:35:20: error: ‘s’ was not declared in this scope
    cout<<"Name: "<<s[i].stuName<<endl;
                    ^
main.cpp:35:22: error: ‘i’ was not declared in this scope
    cout<<"Name: "<<s[i].stuName<<endl;
</code>```

I get the point that I need to define i in the function but how will it take values accordingly. If i take a for loop in the function the values will get printed more than the time required. If i do not take an array it will give a segmentation fault.

Please help me with this code. I am new to c++.

答:
A few points:

First of all, the code is not indented. Use your IDEs code beautify options or use some online to indent your code. Example: https://codebeautify.org/cpp-formatter-beautifier

For learning purposes using namespace std; is fine. But, try to avoid it in a more serious code. Read this thread for more information: Why is "using namespace std;" considered bad practice?

In the Student type, the members are prefixed with stu which is redundant because they're already part of a properly named type i.e. Student and would be referenced in the code by meaningful named objects. Simple and direct member names such as name, rollno, and age would suffice.

The member for student name is a char array with a magic number i.e. 30. Try to learn and use std::string which is more safe and straightforward. And, always try to avoid magic numbers. Use proper names for magic numbers using const, constexpr (if C++11 or above), or #define macro replacements according to your requirements. For example, #define NAME_LENGTH 30.

In C++, you don't need to use prefix struct everywhere reference the type except the definition or a forward declaration. So, void printStudentInfo(struct Student s[]); would be void printStudentInfo(Student s[]);.

The function printStudentInfo is supposed to print only one object of Student type so the subscript operator with argument s[] is redundant. The correct type for this argument in this context would be Student s i.e. void printStudentInfo(Stdudent s). There are multiple ways to pass arguments to a function in C++ such as pass-by-value and pass-by-reference. In your context, pass-by-reference makes more sense i.e. void printStudentInfo(const Student& s). Read this relevant thread on the subject: What's the difference between passing by reference vs. passing by value?

Again, a magic number for array size. Use a constant with a proper name such as MAX_STUDENTS.

In C++, declare and define a loop control variable inside loop:
for ( int i = 0; ... )

Declare Student s[i]; outside the loop. In loop, it means that it is being created every time the loop iterates with a new variable size i.e. 0, 1, 2. That is not intended here. Move it outside with a constant as its size e.g. Student s[MAX_STUDENTS];. A relevant thread: Why aren't variable-length arrays part of the C++ standard?. In the future, when you're familiar with STL (Standard Template Library), use std::vector.

Miscellaneous (you can study as you go along): array initialization, std::endl vs \n, unsigned vs signed (for age, rollno, ...), std::size_t, etc.

Here's a working example (live):

```<code>#include <iostream>
#include <string>

struct Student
{
    std::string name;
    int         rollno;
    int         age;
};

void printStudentInfo( const Student& s );

int main()
{
    const int MAX_STUDENTS = 3;
    Student s[MAX_STUDENTS];

    for ( int i = 0; i < MAX_STUDENTS; ++i )
    {
        std::cout << "Enter Student Name: ";
        std::getline( std::cin, s[i].name );

        std::cout << "Enter Student Roll No: ";
        std::cin >> s[i].rollno;

        std::cout << "Enter Student Age: ";
        std::cin >> s[i].age;

        printStudentInfo( s[i] );
    }

    return 0;
}

void printStudentInfo( const Student& s )
{
    std::cout << "Student Record:\n"
              << "Name    : " << s.name << '\n'
              << "Roll No : " << s.rollno << '\n'
              << "Age     : " << s.age << '\n';
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I used structure for multiple entry of students. But I am getting error in the following code:

#include <iostream>
using namespace std;
struct Student{
   char stuName[30];
   int stuRollNo;
   int stuAge;
};

void printStudentInfo(struct Student s[]);

int main(){
    int i;
    for(i=0;i<3;i++){
   Student s[i];
   cout<<"Enter Student Name: ";
   cin.getline(s[i].stuName, 30);
   cout<<"Enter Student Roll No: ";
   cin>>s[i].stuRollNo;
   cout<<"Enter Student Age: ";
   cin>>s[i].stuAge;
   printStudentInfo(s[i]);}
   return 0;
}

void printStudentInfo(struct Student s[i]){
   cout<<"Student Record:"<<endl;
   cout<<"Name: "<<s[i].stuName<<endl;
   cout<<"Roll No: "<<s[i].stuRollNo<<endl;
   cout<<"Age: "<<s[i].stuAge;
}

error:

main.cpp:29:25: error: cannot convert ‘Student’ to ‘Student*’ for argument ‘1’ to ‘void printStudentInfo(Student*)’
    printStudentInfo(s[i]);}
                         ^
main.cpp: At global scope:
main.cpp:33:40: error: ‘i’ was not declared in this scope
 void printStudentInfo(struct Student s[i]){
                                        ^
main.cpp: In function ‘void printStudentInfo(...)’:
main.cpp:35:20: error: ‘s’ was not declared in this scope
    cout<<"Name: "<<s[i].stuName<<endl;
                    ^
main.cpp:35:22: error: ‘i’ was not declared in this scope
    cout<<"Name: "<<s[i].stuName<<endl;

I get the point that I need to define i in the function but how will it take values accordingly. If i take a for loop in the function the values will get printed more than the time required. If i do not take an array it will give a segmentation fault.

Please help me with this code. I am new to c++.

Body:
A few points:

First of all, the code is not indented. Use your IDEs code beautify options or use some online to indent your code. Example: https://codebeautify.org/cpp-formatter-beautifier

For learning purposes using namespace std; is fine. But, try to avoid it in a more serious code. Read this thread for more information: Why is "using namespace std;" considered bad practice?

In the Student type, the members are prefixed with stu which is redundant because they're already part of a properly named type i.e. Student and would be referenced in the code by meaningful named objects. Simple and direct member names such as name, rollno, and age would suffice.

The member for student name is a char array with a magic number i.e. 30. Try to learn and use std::string which is more safe and straightforward. And, always try to avoid magic numbers. Use proper names for magic numbers using const, constexpr (if C++11 or above), or #define macro replacements according to your requirements. For example, #define NAME_LENGTH 30.

In C++, you don't need to use prefix struct everywhere reference the type except the definition or a forward declaration. So, void printStudentInfo(struct Student s[]); would be void printStudentInfo(Student s[]);.

The function printStudentInfo is supposed to print only one object of Student type so the subscript operator with argument s[] is redundant. The correct type for this argument in this context would be Student s i.e. void printStudentInfo(Stdudent s). There are multiple ways to pass arguments to a function in C++ such as pass-by-value and pass-by-reference. In your context, pass-by-reference makes more sense i.e. void printStudentInfo(const Student& s). Read this relevant thread on the subject: What's the difference between passing by reference vs. passing by value?

Again, a magic number for array size. Use a constant with a proper name such as MAX_STUDENTS.

In C++, declare and define a loop control variable inside loop:
for ( int i = 0; ... )

Declare Student s[i]; outside the loop. In loop, it means that it is being created every time the loop iterates with a new variable size i.e. 0, 1, 2. That is not intended here. Move it outside with a constant as its size e.g. Student s[MAX_STUDENTS];. A relevant thread: Why aren't variable-length arrays part of the C++ standard?. In the future, when you're familiar with STL (Standard Template Library), use std::vector.

Miscellaneous (you can study as you go along): array initialization, std::endl vs \n, unsigned vs signed (for age, rollno, ...), std::size_t, etc.

Here's a working example (live):

#include <iostream>
#include <string>

struct Student
{
    std::string name;
    int         rollno;
    int         age;
};

void printStudentInfo( const Student& s );

int main()
{
    const int MAX_STUDENTS = 3;
    Student s[MAX_STUDENTS];

    for ( int i = 0; i < MAX_STUDENTS; ++i )
    {
        std::cout << "Enter Student Name: ";
        std::getline( std::cin, s[i].name );

        std::cout << "Enter Student Roll No: ";
        std::cin >> s[i].rollno;

        std::cout << "Enter Student Age: ";
        std::cin >> s[i].age;

        printStudentInfo( s[i] );
    }

    return 0;
}

void printStudentInfo( const Student& s )
{
    std::cout << "Student Record:\n"
              << "Name    : " << s.name << '\n'
              << "Roll No : " << s.rollno << '\n'
              << "Age     : " << s.age << '\n';
}


问:
Inserting indexed array into an database with PHP and MySqli
I'm trying to get an indexed array's values inserted into a SQL database with MySQLi and PHP but I can't figure out why it's not working.</p>

```<code>$con = mysqli_connect("localhost","user","pword","db");
if (mysqli_connect_errno()) {
   echo "Unable to connect to MySQL! ". mysqli_connect_error();
   exit();
}

$sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";
$stmt= $con->prepare($sqli);
$stmt->bindParam("ssss",$csv[0],$csv[1],$csv[2],$csv[3]);
$status = $stmt->execute();
if (!$status) {
    echo "Error ".$stmt->errorCode()."\nMessage ".implode($stmt->errorInfo())."\n";
    exit(1);
}
</code>```

答:
It's bind_param when working with mysqli.
It's bindParam when working with PDO.</p>

```<code><?php
    $con = mysqli_connect("localhost","user","pword","db");
    if (mysqli_connect_errno()) {
       echo "Unable to connect to MySQL! ". mysqli_connect_error();
       exit();
    }

    $sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";
    $stmt= $con->prepare($sqli);
    $stmt->bind_param("ssss", $csv[0],$csv[1],$csv[2],$csv[3]);
    $status = $stmt->execute();
</code>```

Body:
I'm trying to get an indexed array's values inserted into a SQL database with MySQLi and PHP but I can't figure out why it's not working.

$con = mysqli_connect("localhost","user","pword","db");
if (mysqli_connect_errno()) {
   echo "Unable to connect to MySQL! ". mysqli_connect_error();
   exit();
}

$sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";
$stmt= $con->prepare($sqli);
$stmt->bindParam("ssss",$csv[0],$csv[1],$csv[2],$csv[3]);
$status = $stmt->execute();
if (!$status) {
    echo "Error ".$stmt->errorCode()."\nMessage ".implode($stmt->errorInfo())."\n";
    exit(1);
}

Body:
It's bind_param when working with mysqli.
It's bindParam when working with PDO.

<?php
    $con = mysqli_connect("localhost","user","pword","db");
    if (mysqli_connect_errno()) {
       echo "Unable to connect to MySQL! ". mysqli_connect_error();
       exit();
    }

    $sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";
    $stmt= $con->prepare($sqli);
    $stmt->bind_param("ssss", $csv[0],$csv[1],$csv[2],$csv[3]);
    $status = $stmt->execute();


问:
python populating array using while loop
All I am trying to do is populate an array with numbers in order. So, array[0][0] = 0, array[0][1]=1, etc. Why is this not working?  I cannot figure it out.</p>

```<code>def populateArray(ar):
    count = 0
    i=0
    j=0
    while (i<len(ar)):
        while (j<len(ar[i])):
            ar[i][j] = count
            count = count + 1
            j=j+1
        j=0
        i=i+1
    return ar

numColumns = input('how many columns?')
numRows = input('how many rows?')
arr = [[0]*int(numColumns)]*int(numRows)
arr=populateArray(arr)
print(arr)
</code>```

答:
When you use this syntax to create multi dimensional array

```<code>arr = [[0]*int(numColumns)]*int(numRows)
</code>```

the reference of same element is created  many times , so if you assign a value to one of them then you are basically changing all the elements because they all reference to the same data.
for ex :

```<code>arr = [[0]*int(numColumns)]*int(numRows)
arr[0][1]=2
print(arr)
</code>```

output

```<code>[[0, 2], [0, 2], [0, 2], [0, 2]]
</code>```

I only changed one element and this is the result .
you should use :

```<code>arr = [[0 for i in range(int(numColumns))] for j in range(int(numRows))]
arr[0][1]=2
print(arr)
</code>```

output :

```<code>[[0, 2], [0, 0], [0, 0], [0, 0]]
</code>```

Body:
All I am trying to do is populate an array with numbers in order. So, array[0][0] = 0, array[0][1]=1, etc. Why is this not working?  I cannot figure it out.

def populateArray(ar):
    count = 0
    i=0
    j=0
    while (i<len(ar)):
        while (j<len(ar[i])):
            ar[i][j] = count
            count = count + 1
            j=j+1
        j=0
        i=i+1
    return ar

numColumns = input('how many columns?')
numRows = input('how many rows?')
arr = [[0]*int(numColumns)]*int(numRows)
arr=populateArray(arr)
print(arr)

Body:
When you use this syntax to create multi dimensional array

arr = [[0]*int(numColumns)]*int(numRows)

the reference of same element is created  many times , so if you assign a value to one of them then you are basically changing all the elements because they all reference to the same data.
for ex :

arr = [[0]*int(numColumns)]*int(numRows)
arr[0][1]=2
print(arr)

output

[[0, 2], [0, 2], [0, 2], [0, 2]]

I only changed one element and this is the result .
you should use :

arr = [[0 for i in range(int(numColumns))] for j in range(int(numRows))]
arr[0][1]=2
print(arr)

output :

[[0, 2], [0, 0], [0, 0], [0, 0]]


问:
Passing function from another class to this class
I know, title is hard to understand.

So, i have this class:

```<code>class ConfigDict(dict):

    def __init__(self, dic):
        super(ConfigDict, self).__init__(dic)

    def required(self, keys_array, function):
        print 'required'

    def valid(self, function = None):
        print 'valid'
</code>```

And what i want - i create instance of this class with dict as parameter:

```<code>ConfigDict({'a' : 'b'})
</code>```

It's working, thats good. But i want pass function as argument in dict from ConfigDict class without importing methods from ConfigDict.

For example, i want do this:

```<code> ConfigDict({'a' : ('b', required(['test'], valid))})
</code>```

I know that required in ConfigDict do nothing now. Expected result is:

```<code>>> ConfigDict({'a' : ('b', required(['test'], valid()))})
required called with ['test'], valid for {a : b}
valid called from required with None for {a : b}
</code>```

So, after creating instance of ConfigDict with {'a' : ('b', required['test'], valid())} dict, i want that this instance in __init__ method make loop in all dict elements, and if founds tuple in value, execute founded nested function in itselfs.

Is here any way to do this without importing all methods from ConfigDict?

EDIT:

As i expected i must better explain what i need.

Ok, we take this fragment:

```<code>ConfigDict({'a' : ('b', required(['test'], valid))})
</code>```

This made us new instance of ConfigDict. These functions in touple is used to validate value, in this case it is 'b'. I made few changes waiting for response, so calling this class is now look that:

```<code>cd = ConfigDict()
cd.feed({'a' : 'b'})
</code>```

I can call functions like that:

```<code>cd.feed({'a' : ('b', cg.required(['test']))})
</code>```

What is work's very well, but there's one thing - it not pass to required function the value. ConfigDicts.required should get an array and value, in this case 'b'. I don't expect to find way to do this myself, except using everywhere lambda's what i like to avoid.

So, my question been bit changed - is there a any way to get 'b' value from inside required function? I can pass 'b' as argument directly into required, but i expect to have many functions call in tuple, passing value for each make a little mess in code.

Also, anyone please, edit title of my post, i lack of words to describe this problem :)

答:
Your English is a bit hard to understand, and your question contains some errors (or just inconsistencies), so I'm not sure what exactly you want, but here's one thing the may work for you:

(Edit) Try this:

```<code>class CallWrapper(object):
    def __init__(self, fn):
        self.fn = fn

    def __call__(self, *args, **kwargs):
        self.args   = args
        self.kwargs = kwargs
        return self

    def invoke_with_value(self, value):
        return self.fn(value, *self.args, **self.kwargs)

class ConfigDict(dict):
    def __init__(self, ldic):
        myvars = globals()
        for name in dir(self):
            attr = getattr(self, name)
            if callable(attr) and not name.startswith('_'):
                myvars[name] = CallWrapper(attr)

        wrapped_dic = eval(ldic.func_code, myvars)

        dic = {}
        for key, value in wrapped_dic.iteritems():
            # Check if value is a tuple with call wrappers
            if isinstance(value, tuple) and len(value) > 1 and \
                        isinstance(value[1], CallWrapper):
                wrappers = value[1:]
                value = value[0]
                for wrapper in wrappers:
                    # Run wrappers
                    result = wrapper.invoke_with_value(value)
                    if result:
                        value = result # Wrapper modified value

            dic[key] = value # No wrappers

        super(ConfigDict, self).__init__(dic)

    def prefix(self, value, pref):
        print 'prefix called for value: ', value
        return pref + '_' + value

    def required(self, value, keys_array):
        print 'required called for value: ', value
        print 'with keys: ', keys_array

    def valid(self, value):
        print 'valid called for value: ', value

cfg = ConfigDict(lambda: {'A': ('a', required(['test']), valid()),
                          'B': ('b', prefix('hello')),
                          'C': 'c'})
print cfg
</code>```

Output:

```<code>required called for value:  a
with keys:  ['test']
valid called for value:  a
prefix called for value:  b
{'A': 'a', 'C': 'c', 'B': 'hello_b'}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know, title is hard to understand.

So, i have this class:

class ConfigDict(dict):

    def __init__(self, dic):
        super(ConfigDict, self).__init__(dic)

    def required(self, keys_array, function):
        print 'required'

    def valid(self, function = None):
        print 'valid'

And what i want - i create instance of this class with dict as parameter:

ConfigDict({'a' : 'b'})

It's working, thats good. But i want pass function as argument in dict from ConfigDict class without importing methods from ConfigDict.

For example, i want do this:

 ConfigDict({'a' : ('b', required(['test'], valid))})

I know that required in ConfigDict do nothing now. Expected result is:

>> ConfigDict({'a' : ('b', required(['test'], valid()))})
required called with ['test'], valid for {a : b}
valid called from required with None for {a : b}

So, after creating instance of ConfigDict with {'a' : ('b', required['test'], valid())} dict, i want that this instance in __init__ method make loop in all dict elements, and if founds tuple in value, execute founded nested function in itselfs.

Is here any way to do this without importing all methods from ConfigDict?

EDIT:

As i expected i must better explain what i need.

Ok, we take this fragment:

ConfigDict({'a' : ('b', required(['test'], valid))})

This made us new instance of ConfigDict. These functions in touple is used to validate value, in this case it is 'b'. I made few changes waiting for response, so calling this class is now look that:

cd = ConfigDict()
cd.feed({'a' : 'b'})

I can call functions like that:

cd.feed({'a' : ('b', cg.required(['test']))})

What is work's very well, but there's one thing - it not pass to required function the value. ConfigDicts.required should get an array and value, in this case 'b'. I don't expect to find way to do this myself, except using everywhere lambda's what i like to avoid.

So, my question been bit changed - is there a any way to get 'b' value from inside required function? I can pass 'b' as argument directly into required, but i expect to have many functions call in tuple, passing value for each make a little mess in code.

Also, anyone please, edit title of my post, i lack of words to describe this problem :)

Body:
Your English is a bit hard to understand, and your question contains some errors (or just inconsistencies), so I'm not sure what exactly you want, but here's one thing the may work for you:

(Edit) Try this:

class CallWrapper(object):
    def __init__(self, fn):
        self.fn = fn

    def __call__(self, *args, **kwargs):
        self.args   = args
        self.kwargs = kwargs
        return self

    def invoke_with_value(self, value):
        return self.fn(value, *self.args, **self.kwargs)

class ConfigDict(dict):
    def __init__(self, ldic):
        myvars = globals()
        for name in dir(self):
            attr = getattr(self, name)
            if callable(attr) and not name.startswith('_'):
                myvars[name] = CallWrapper(attr)

        wrapped_dic = eval(ldic.func_code, myvars)

        dic = {}
        for key, value in wrapped_dic.iteritems():
            # Check if value is a tuple with call wrappers
            if isinstance(value, tuple) and len(value) > 1 and \
                        isinstance(value[1], CallWrapper):
                wrappers = value[1:]
                value = value[0]
                for wrapper in wrappers:
                    # Run wrappers
                    result = wrapper.invoke_with_value(value)
                    if result:
                        value = result # Wrapper modified value

            dic[key] = value # No wrappers

        super(ConfigDict, self).__init__(dic)

    def prefix(self, value, pref):
        print 'prefix called for value: ', value
        return pref + '_' + value

    def required(self, value, keys_array):
        print 'required called for value: ', value
        print 'with keys: ', keys_array

    def valid(self, value):
        print 'valid called for value: ', value

cfg = ConfigDict(lambda: {'A': ('a', required(['test']), valid()),
                          'B': ('b', prefix('hello')),
                          'C': 'c'})
print cfg

Output:

required called for value:  a
with keys:  ['test']
valid called for value:  a
prefix called for value:  b
{'A': 'a', 'C': 'c', 'B': 'hello_b'}


问:
AdvancedWebView (delight-im/Android-AdvancedWebView) stops showing web pages if I set targetSdkVersion 28
I'm using this WebView extension:

https://github.com/delight-im/Android-AdvancedWebView

Google Play Console is requesting a targetSdkVersion 28 for future pubblications. I tryed to update my project but the component stop showing web pages. If I set targetSdkVersion 26 everyting works normally.

Anyone is in the same situation maybe with others WebView extensions?

答:
Reading the LogCat I see ERR_CLEARTEXT_NOT_PERMITTED.

This problem is solved adding

```<code><application
    ....
    android:usesCleartextTraffic="true"
    ....>
</code>```

in the manifest file.

The author (Marco) correctly says that all we need to know is already here:

https://github.com/delight-im/Android-AdvancedWebView#cleartext-non-https-traffic

Cleartext (non-HTTPS) traffic
If you want to serve sites or just single resources over plain http instead of https, there’s usually nothing to do if you’re targeting Android 8.1 (API level 27) or earlier. On Android 9 (API level 28) and later, however, cleartext support is disabled by default. You may have to set android:usesCleartextTraffic="true" on the  element in AndroidManifest.xml or provide a custom network security configuration.

Thank you Marco!

Body:
Reading the LogCat I see ERR_CLEARTEXT_NOT_PERMITTED.

This problem is solved adding

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

in the manifest file.

The author (Marco) correctly says that all we need to know is already here:

https://github.com/delight-im/Android-AdvancedWebView#cleartext-non-https-traffic

Cleartext (non-HTTPS) traffic
If you want to serve sites or just single resources over plain http instead of https, there’s usually nothing to do if you’re targeting Android 8.1 (API level 27) or earlier. On Android 9 (API level 28) and later, however, cleartext support is disabled by default. You may have to set android:usesCleartextTraffic="true" on the  element in AndroidManifest.xml or provide a custom network security configuration.

Thank you Marco!


问:
Stanardize only a few selected columns in machine learning
I have a CSV file out of which only a few columns need normalization(others are binary values). Should I selectively normalize the required columns or should I normalize all the columns in the table? If I normalize the entire table will I lose some information or noise is introduced into data that don't require any normalization or standardization?</p>

答:
Let's make some points clear.

Binary Data is a categorical data (IsEmployed - 0/1)

Only numerical data has to be normalized

Understanding part:

When we say normalized data, it means we are moving distribution
scale to range of 0-1.

+Added:

In perspective of Categorical data, we do OneHotEncoding and convert it back to binary data for each category.


问:
Why is the Geopandas Dataframe returning an Index Error
I'm using geopandas 0.6.1 and pandas 1.0.0 in a VS Code notebook. While working today, I was surprised calling the geopandas function head() on a seemingly valid geopandas data frame caused the below error.

Methods such as gpd.columns and gpd.shape work normally and return the expected results. .iloc returns the expected record. For example:

```<code>for item in new_west_df.columns.values.tolist():
    print(item)

TYPE
NWID
LICENCE
TRADE_NAME
LICENCEE_NAME
CIVIC_ADDRESS
LICENCE_DESCRIPTION
YEAR_OPENED
APPROVED_DATE
SIC
SIC_GROUP
CIVIC_POSTAL_CODE
geometry
</code>```

However, columns() and .geometry cause the below error. In my research of the problem, none of the scenarios were similar to these conditions, and reading the error I can't understand the root cause.

```<code>IndexError                                Traceback (most recent call last)
/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, obj)
    700                 type_pprinters=self.type_printers,
    701                 deferred_pprinters=self.deferred_printers)
--> 702             printer.pretty(obj)
    703             printer.flush()
    704             return stream.getvalue()

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/IPython/lib/pretty.py in pretty(self, obj)
    397                         if cls is not object \
    398                                 and callable(cls.__dict__.get('__repr__')):
--> 399                             return _repr_pprint(obj, self, cycle)
    400
    401             return _default_pprint(obj, self, cycle)

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/IPython/lib/pretty.py in _repr_pprint(obj, p, cycle)
    687     """A pprint that just redirects to the normal repr function."""
    688     # Find newlines and replace them with p.break_()
--> 689     output = repr(obj)
    690     for idx,output_line in enumerate(output.splitlines()):
    691         if idx:

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/core/series.py in __repr__(self)
   1370             min_rows=min_rows,
   1371             max_rows=max_rows,
-> 1372             length=show_dimensions,
   1373         )
   1374         result = buf.getvalue()

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/core/series.py in to_string(self, buf, na_rep, float_format, header, index, length, dtype, name, max_rows, min_rows)
   1436             max_rows=max_rows,
   1437         )
-> 1438         result = formatter.to_string()
   1439
   1440         # catch contract violations

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/io/formats/format.py in to_string(self)
    359
    360         fmt_index, have_header = self._get_formatted_index()
--> 361         fmt_values = self._get_formatted_values()
    362
    363         if self.truncate_v:

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/io/formats/format.py in _get_formatted_values(self)
    346             None,
    347             float_format=self.float_format,
--> 348             na_rep=self.na_rep,
    349         )
    350

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/io/formats/format.py in format_array(values, formatter, float_format, na_rep, digits, space, justify, decimal, leading_space)
   1172     )
   1173
-> 1174     return fmt_obj.get_result()
   1175
   1176

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/io/formats/format.py in get_result(self)
   1203
   1204     def get_result(self) -> List[str]:
-> 1205         fmt_values = self._format_strings()
   1206         return _make_fixed_width(fmt_values, self.justify)
   1207

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/io/formats/format.py in _format_strings(self)
   1483             values = values._values
   1484
-> 1485         formatter = values._formatter(boxed=True)
   1486
   1487         if is_categorical_dtype(values.dtype):

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/geopandas/array.py in _formatter(self, boxed)
   1009                 # dummy heuristic based on 10 first geometries that should
   1010                 # work in most cases
-> 1011                 xmin, ymin, xmax, ymax = self[~self.isna()][:10].total_bounds
   1012                 if (
   1013                     (-180 <= xmin <= 180)

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/geopandas/array.py in total_bounds(self)
    750         return np.array(
    751             (
--> 752                 b[:, 0].min(),  # minx
    753                 b[:, 1].min(),  # miny
    754                 b[:, 2].max(),  # maxx

IndexError: too many indices for array
</code>```

答: This is a bug that was fixed in GeoPandas 0.6.2 (https://github.com/geopandas/geopandas/releases/tag/v0.6.2), so if you upgrade geopandas, it should be solved.</p>

Body:
I'm using geopandas 0.6.1 and pandas 1.0.0 in a VS Code notebook. While working today, I was surprised calling the geopandas function head() on a seemingly valid geopandas data frame caused the below error.

Methods such as gpd.columns and gpd.shape work normally and return the expected results. .iloc returns the expected record. For example:

for item in new_west_df.columns.values.tolist():
    print(item)

TYPE
NWID
LICENCE
TRADE_NAME
LICENCEE_NAME
CIVIC_ADDRESS
LICENCE_DESCRIPTION
YEAR_OPENED
APPROVED_DATE
SIC
SIC_GROUP
CIVIC_POSTAL_CODE
geometry

However, columns() and .geometry cause the below error. In my research of the problem, none of the scenarios were similar to these conditions, and reading the error I can't understand the root cause.

IndexError                                Traceback (most recent call last)
/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, obj)
    700                 type_pprinters=self.type_printers,
    701                 deferred_pprinters=self.deferred_printers)
--> 702             printer.pretty(obj)
    703             printer.flush()
    704             return stream.getvalue()

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/IPython/lib/pretty.py in pretty(self, obj)
    397                         if cls is not object \
    398                                 and callable(cls.__dict__.get('__repr__')):
--> 399                             return _repr_pprint(obj, self, cycle)
    400
    401             return _default_pprint(obj, self, cycle)

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/IPython/lib/pretty.py in _repr_pprint(obj, p, cycle)
    687     """A pprint that just redirects to the normal repr function."""
    688     # Find newlines and replace them with p.break_()
--> 689     output = repr(obj)
    690     for idx,output_line in enumerate(output.splitlines()):
    691         if idx:

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/core/series.py in __repr__(self)
   1370             min_rows=min_rows,
   1371             max_rows=max_rows,
-> 1372             length=show_dimensions,
   1373         )
   1374         result = buf.getvalue()

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/core/series.py in to_string(self, buf, na_rep, float_format, header, index, length, dtype, name, max_rows, min_rows)
   1436             max_rows=max_rows,
   1437         )
-> 1438         result = formatter.to_string()
   1439
   1440         # catch contract violations

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/io/formats/format.py in to_string(self)
    359
    360         fmt_index, have_header = self._get_formatted_index()
--> 361         fmt_values = self._get_formatted_values()
    362
    363         if self.truncate_v:

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/io/formats/format.py in _get_formatted_values(self)
    346             None,
    347             float_format=self.float_format,
--> 348             na_rep=self.na_rep,
    349         )
    350

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/io/formats/format.py in format_array(values, formatter, float_format, na_rep, digits, space, justify, decimal, leading_space)
   1172     )
   1173
-> 1174     return fmt_obj.get_result()
   1175
   1176

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/io/formats/format.py in get_result(self)
   1203
   1204     def get_result(self) -> List[str]:
-> 1205         fmt_values = self._format_strings()
   1206         return _make_fixed_width(fmt_values, self.justify)
   1207

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/pandas/io/formats/format.py in _format_strings(self)
   1483             values = values._values
   1484
-> 1485         formatter = values._formatter(boxed=True)
   1486
   1487         if is_categorical_dtype(values.dtype):

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/geopandas/array.py in _formatter(self, boxed)
   1009                 # dummy heuristic based on 10 first geometries that should
   1010                 # work in most cases
-> 1011                 xmin, ymin, xmax, ymax = self[~self.isna()][:10].total_bounds
   1012                 if (
   1013                     (-180 <= xmin <= 180)

/Library/Frameworks/anaconda3/envs/vm/lib/python3.7/site-packages/geopandas/array.py in total_bounds(self)
    750         return np.array(
    751             (
--> 752                 b[:, 0].min(),  # minx
    753                 b[:, 1].min(),  # miny
    754                 b[:, 2].max(),  # maxx

IndexError: too many indices for array


问:
GtkTreeView alternate row color
I can't set the alternate row color of a TreeView, I don't know why doesn't works.

This the code

```<code>MainWindow::MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade) :
    Gtk::ApplicationWindow(cobject), refBuilder(refGlade){

    Glib::RefPtr<Gtk::CssProvider> cssProvider = Gtk::CssProvider::create();
    cssProvider->load_from_path("style.css");
    Glib::RefPtr<Gtk::StyleContext> styleContext = Gtk::StyleContext::create();
    Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();
    styleContext->add_provider_for_screen(screen, cssProvider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    const char* user = "user";
    const char* passwd = "passwd";
    const char* database = "dbname";
    const char* dbhost = "192.168.1.5";

    connection = mysql_init(NULL);

    mysql_real_connect(connection, dbhost, user, passwd, database, 3307, NULL, 0);

    refBuilder->get_widget("m_TreeView1", m_TreeView1);

    m_refTreeModel = Gtk::ListStore::create(m_Columns);
    m_TreeView1->set_model(m_refTreeModel);

    /*Glib::RefPtr<Gtk::StyleContext> context = m_TreeView1->get_style_context();
context->add_class("treeview");
*/

    Affitto* affitti = new Affitto(connection);
    MYSQL_RES* res = affitti->getAll();
    MYSQL_ROW riga;
    Gtk::TreeModel::Row row;

    while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);
        row[m_Columns.m_col_cognomenome] = riga[1];
        row[m_Columns.m_col_stabile] = riga[2];
        row[m_Columns.m_col_mese] = std::stoi(riga[3]);
        row[m_Columns.m_col_anno] = std::stoi(riga[4]);
        row[m_Columns.m_col_posteggiopagato] = std::stod(riga[5]);
        row[m_Columns.m_col_affittopagato] = std::stod(riga[6]);
        row[m_Columns.m_col_riscaldamentopagato] = std::stod(riga[7]);
        row[m_Columns.m_col_pagatoil] = riga[8];
        row[m_Columns.m_col_stato] = riga[9];
        row[m_Columns.m_col_osservazioni] = riga[10];
        row[m_Columns.m_col_traslocato] = riga[11];
        row[m_Columns.m_col_diversi] = std::stod(riga[12]);
        row[m_Columns.m_col_affitto] = std::stod(riga[13]);
        row[m_Columns.m_col_posteggio] = std::stod(riga[14]);
        row[m_Columns.m_col_riscaldamento] = std::stod(riga[15]);

    }

    m_TreeView1->append_column("InqID", m_Columns.m_col_inqid);
    m_TreeView1->append_column("Cognome e nome", m_Columns.m_col_cognomenome);
    //m_TreeView1->get_column(1)->set_expand(true);
    m_TreeView1->append_column("Stabile", m_Columns.m_col_stabile);
    m_TreeView1->append_column("Mese", m_Columns.m_col_mese);
    m_TreeView1->append_column("Anno", m_Columns.m_col_anno);
    m_TreeView1->append_column("Posteggio pagato", m_Columns.m_col_posteggiopagato);
    m_TreeView1->append_column("Affitto pagato", m_Columns.m_col_affittopagato);
    m_TreeView1->append_column("Riscaldamento pagato", m_Columns.m_col_riscaldamentopagato);
    m_TreeView1->append_column("Pagato il", m_Columns.m_col_pagatoil);
    m_TreeView1->append_column("Stato", m_Columns.m_col_stato);
    m_TreeView1->append_column("Osservazioni", m_Columns.m_col_osservazioni);
    m_TreeView1->append_column("Traslocato", m_Columns.m_col_traslocato);
    m_TreeView1->append_column("Diversi", m_Columns.m_col_diversi);
    m_TreeView1->append_column("Affitto", m_Columns.m_col_affitto);
    m_TreeView1->append_column("Posteggio", m_Columns.m_col_posteggio);
    m_TreeView1->append_column("Riscaldamento", m_Columns.m_col_riscaldamento);

    mysql_free_result(res);
    mysql_close(connection);

}
</code>```

And this the css, that is correctly loaded. I set the style class of the TreeView (treeview) in glade file.

```<code>.treeview row:nth-child(even)
{
    background-color: #ff0000;
}
.treeview row:nth-child(odd)
{
    background-color: #000000;
}
</code>```

What's wrong? I tried too to set the style class by code (commented rows) but does't change.
Thanks in advance for an help!

update

I put my updated code, what's I'm wrong?

```<code>Gtk::CellRendererText* textRenderer = manage(new Gtk::CellRendererText());
    textRenderer->property_editable() = false;
    Gtk::TreeViewColumn *col = manage(new Gtk::TreeViewColumn("InqId", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_col_inqid);
    m_TreeView1->append_column(*col);
while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);

        row[m_Columns.m_col_inqid] = Gdk::Color("#CCCCCC");

    }
</code>```

thanks in advance!

答:
so, now it works...this is the complete code in case of somebody have the same problem.
Thanks a lot for those help me!

the model:

```<code>class MainWindow : public Gtk::ApplicationWindow
{
    public:
        MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade);
        virtual ~MainWindow();
        MYSQL* connection;
    protected:
        Glib::RefPtr<Gtk::Builder> refBuilder;

        class ModelColumns : public Gtk::TreeModel::ColumnRecord
        {
            public:

            ModelColumns()
            {
                add(m_col_inqid);
                add(m_col_cognomenome);
                add(m_col_stabile);
                add(m_col_mese);
                add(m_col_anno);
                add(m_col_posteggiopagato);
                add(m_col_affittopagato);
                add(m_col_riscaldamentopagato);
                add(m_col_pagatoil);
                add(m_col_stato);
                add(m_col_osservazioni);
                add(m_col_traslocato);
                add(m_col_diversi);
                add(m_col_affitto);
                add(m_col_posteggio);
                add(m_col_riscaldamento);
                add(m_coloreriga);
            }

            Gtk::TreeModelColumn<int> m_col_inqid;
            Gtk::TreeModelColumn<std::string> m_col_cognomenome;
            Gtk::TreeModelColumn<std::string> m_col_stabile;
            Gtk::TreeModelColumn<int> m_col_mese;
            Gtk::TreeModelColumn<int> m_col_anno;
            Gtk::TreeModelColumn<double> m_col_posteggiopagato;
            Gtk::TreeModelColumn<double> m_col_affittopagato;
            Gtk::TreeModelColumn<double> m_col_riscaldamentopagato;
            Gtk::TreeModelColumn<std::string> m_col_pagatoil;
            Gtk::TreeModelColumn<std::string> m_col_stato;
            Gtk::TreeModelColumn<std::string> m_col_osservazioni;
            Gtk::TreeModelColumn<std::string> m_col_traslocato;
            Gtk::TreeModelColumn<double> m_col_diversi;
            Gtk::TreeModelColumn<double> m_col_affitto;
            Gtk::TreeModelColumn<double> m_col_posteggio;
            Gtk::TreeModelColumn<double> m_col_riscaldamento;
            Gtk::TreeModelColumn<Gdk::RGBA> m_coloreriga;

        };

        ModelColumns m_Columns;
        Gtk::TreeView* m_TreeView1;
        Glib::RefPtr<Gtk::ListStore> m_refTreeModel;

};
</code>```

the main:

```<code>MainWindow::MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade) :
    Gtk::ApplicationWindow(cobject), refBuilder(refGlade){

    Glib::RefPtr<Gtk::CssProvider> cssProvider = Gtk::CssProvider::create();
    cssProvider->load_from_path("style.css");
    //cssProvider->load_from_data(cssProvider, ".treeview row:nth-child(even){  background-color: #ff0000; } .treeview row:nth-child(odd){ background-color: #000000; }", -1, NULL);
    Glib::RefPtr<Gtk::StyleContext> styleContext = Gtk::StyleContext::create();
    Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();
    styleContext->add_provider_for_screen(screen, cssProvider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    const char* user = "root";
    const char* passwd = "";
    const char* database = "";
    const char* dbhost = "192.168.1.5";

    connection = mysql_init(NULL);

    mysql_real_connect(connection, dbhost, user, passwd, database, 3307, NULL, 0);

    refBuilder->get_widget("m_TreeView1", m_TreeView1);

    //m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this, &MainWindow::on_button_quit) );

    m_refTreeModel = Gtk::ListStore::create(m_Columns);
    m_TreeView1->set_model(m_refTreeModel);
Affitto* affitti = new Affitto(connection);
    MYSQL_RES* res = affitti->getAll();
    MYSQL_ROW riga;
    Gtk::TreeModel::Row row;
Gtk::CellRendererText* textRenderer = manage(new Gtk::CellRendererText());
    Gtk::TreeViewColumn *col = manage(new Gtk::TreeViewColumn("InqId", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_coloreriga);
    m_TreeView1->append_column(*col);

    textRenderer = manage(new Gtk::CellRendererText());
    col = manage(new Gtk::TreeViewColumn("Cognome e nome", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_coloreriga);
    m_TreeView1->append_column(*col);
m_TreeView1->append_column("Stabile", m_Columns.m_col_stabile);
    m_TreeView1->append_column("Mese", m_Columns.m_col_mese);
    m_TreeView1->append_column("Anno", m_Columns.m_col_anno);
    m_TreeView1->append_column("Posteggio pagato", m_Columns.m_col_posteggiopagato);
    m_TreeView1->append_column("Affitto pagato", m_Columns.m_col_affittopagato);
    m_TreeView1->append_column("Riscaldamento pagato", m_Columns.m_col_riscaldamentopagato);
    m_TreeView1->append_column("Pagato il", m_Columns.m_col_pagatoil);
    m_TreeView1->append_column("Stato", m_Columns.m_col_stato);
    m_TreeView1->append_column("Osservazioni", m_Columns.m_col_osservazioni);
    m_TreeView1->append_column("Traslocato", m_Columns.m_col_traslocato);
    m_TreeView1->append_column("Diversi", m_Columns.m_col_diversi);
    m_TreeView1->append_column("Affitto", m_Columns.m_col_affitto);
    m_TreeView1->append_column("Posteggio", m_Columns.m_col_posteggio);
    m_TreeView1->append_column("Riscaldamento", m_Columns.m_col_riscaldamento);

 int i=0;
    while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);
        row[m_Columns.m_col_cognomenome] = riga[1];
        row[m_Columns.m_col_stabile] = riga[2];
        row[m_Columns.m_col_mese] = std::stoi(riga[3]);
        row[m_Columns.m_col_anno] = std::stoi(riga[4]);
        row[m_Columns.m_col_posteggiopagato] = std::stod(riga[5]);
        row[m_Columns.m_col_affittopagato] = std::stod(riga[6]);
        row[m_Columns.m_col_riscaldamentopagato] = std::stod(riga[7]);
        row[m_Columns.m_col_pagatoil] = riga[8];
        row[m_Columns.m_col_stato] = riga[9];
        row[m_Columns.m_col_osservazioni] = riga[10];
        row[m_Columns.m_col_traslocato] = riga[11];
        row[m_Columns.m_col_diversi] = std::stod(riga[12]);
        row[m_Columns.m_col_affitto] = std::stod(riga[13]);
        row[m_Columns.m_col_posteggio] = std::stod(riga[14]);
        row[m_Columns.m_col_riscaldamento] = std::stod(riga[15]);

        if(i%2 == 0)
            row[m_Columns.m_coloreriga] = Gdk::RGBA("#ff0000");
        else
            row[m_Columns.m_coloreriga] = Gdk::RGBA("#cccccc");
        i++;
    }

    mysql_free_result(res);
    mysql_close(connection);

}
</code>```

Title: GtkTreeView alternate row color

Body:
I can't set the alternate row color of a TreeView, I don't know why doesn't works.

This the code

MainWindow::MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade) :
    Gtk::ApplicationWindow(cobject), refBuilder(refGlade){

    Glib::RefPtr<Gtk::CssProvider> cssProvider = Gtk::CssProvider::create();
    cssProvider->load_from_path("style.css");
    Glib::RefPtr<Gtk::StyleContext> styleContext = Gtk::StyleContext::create();
    Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();
    styleContext->add_provider_for_screen(screen, cssProvider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    const char* user = "user";
    const char* passwd = "passwd";
    const char* database = "dbname";
    const char* dbhost = "192.168.1.5";

    connection = mysql_init(NULL);

    mysql_real_connect(connection, dbhost, user, passwd, database, 3307, NULL, 0);

    refBuilder->get_widget("m_TreeView1", m_TreeView1);

    m_refTreeModel = Gtk::ListStore::create(m_Columns);
    m_TreeView1->set_model(m_refTreeModel);

    /*Glib::RefPtr<Gtk::StyleContext> context = m_TreeView1->get_style_context();
context->add_class("treeview");
*/

    Affitto* affitti = new Affitto(connection);
    MYSQL_RES* res = affitti->getAll();
    MYSQL_ROW riga;
    Gtk::TreeModel::Row row;

    while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);
        row[m_Columns.m_col_cognomenome] = riga[1];
        row[m_Columns.m_col_stabile] = riga[2];
        row[m_Columns.m_col_mese] = std::stoi(riga[3]);
        row[m_Columns.m_col_anno] = std::stoi(riga[4]);
        row[m_Columns.m_col_posteggiopagato] = std::stod(riga[5]);
        row[m_Columns.m_col_affittopagato] = std::stod(riga[6]);
        row[m_Columns.m_col_riscaldamentopagato] = std::stod(riga[7]);
        row[m_Columns.m_col_pagatoil] = riga[8];
        row[m_Columns.m_col_stato] = riga[9];
        row[m_Columns.m_col_osservazioni] = riga[10];
        row[m_Columns.m_col_traslocato] = riga[11];
        row[m_Columns.m_col_diversi] = std::stod(riga[12]);
        row[m_Columns.m_col_affitto] = std::stod(riga[13]);
        row[m_Columns.m_col_posteggio] = std::stod(riga[14]);
        row[m_Columns.m_col_riscaldamento] = std::stod(riga[15]);

    }

    m_TreeView1->append_column("InqID", m_Columns.m_col_inqid);
    m_TreeView1->append_column("Cognome e nome", m_Columns.m_col_cognomenome);
    //m_TreeView1->get_column(1)->set_expand(true);
    m_TreeView1->append_column("Stabile", m_Columns.m_col_stabile);
    m_TreeView1->append_column("Mese", m_Columns.m_col_mese);
    m_TreeView1->append_column("Anno", m_Columns.m_col_anno);
    m_TreeView1->append_column("Posteggio pagato", m_Columns.m_col_posteggiopagato);
    m_TreeView1->append_column("Affitto pagato", m_Columns.m_col_affittopagato);
    m_TreeView1->append_column("Riscaldamento pagato", m_Columns.m_col_riscaldamentopagato);
    m_TreeView1->append_column("Pagato il", m_Columns.m_col_pagatoil);
    m_TreeView1->append_column("Stato", m_Columns.m_col_stato);
    m_TreeView1->append_column("Osservazioni", m_Columns.m_col_osservazioni);
    m_TreeView1->append_column("Traslocato", m_Columns.m_col_traslocato);
    m_TreeView1->append_column("Diversi", m_Columns.m_col_diversi);
    m_TreeView1->append_column("Affitto", m_Columns.m_col_affitto);
    m_TreeView1->append_column("Posteggio", m_Columns.m_col_posteggio);
    m_TreeView1->append_column("Riscaldamento", m_Columns.m_col_riscaldamento);

    mysql_free_result(res);
    mysql_close(connection);

}

And this the css, that is correctly loaded. I set the style class of the TreeView (treeview) in glade file.

.treeview row:nth-child(even)
{
    background-color: #ff0000;
}
.treeview row:nth-child(odd)
{
    background-color: #000000;
}

What's wrong? I tried too to set the style class by code (commented rows) but does't change.
Thanks in advance for an help!

update

I put my updated code, what's I'm wrong?

Gtk::CellRendererText* textRenderer = manage(new Gtk::CellRendererText());
    textRenderer->property_editable() = false;
    Gtk::TreeViewColumn *col = manage(new Gtk::TreeViewColumn("InqId", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_col_inqid);
    m_TreeView1->append_column(*col);
while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);

        row[m_Columns.m_col_inqid] = Gdk::Color("#CCCCCC");

    }

thanks in advance!

Body:
so, now it works...this is the complete code in case of somebody have the same problem.
Thanks a lot for those help me!

the model:

class MainWindow : public Gtk::ApplicationWindow
{
    public:
        MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade);
        virtual ~MainWindow();
        MYSQL* connection;
    protected:
        Glib::RefPtr<Gtk::Builder> refBuilder;

        class ModelColumns : public Gtk::TreeModel::ColumnRecord
        {
            public:

            ModelColumns()
            {
                add(m_col_inqid);
                add(m_col_cognomenome);
                add(m_col_stabile);
                add(m_col_mese);
                add(m_col_anno);
                add(m_col_posteggiopagato);
                add(m_col_affittopagato);
                add(m_col_riscaldamentopagato);
                add(m_col_pagatoil);
                add(m_col_stato);
                add(m_col_osservazioni);
                add(m_col_traslocato);
                add(m_col_diversi);
                add(m_col_affitto);
                add(m_col_posteggio);
                add(m_col_riscaldamento);
                add(m_coloreriga);
            }

            Gtk::TreeModelColumn<int> m_col_inqid;
            Gtk::TreeModelColumn<std::string> m_col_cognomenome;
            Gtk::TreeModelColumn<std::string> m_col_stabile;
            Gtk::TreeModelColumn<int> m_col_mese;
            Gtk::TreeModelColumn<int> m_col_anno;
            Gtk::TreeModelColumn<double> m_col_posteggiopagato;
            Gtk::TreeModelColumn<double> m_col_affittopagato;
            Gtk::TreeModelColumn<double> m_col_riscaldamentopagato;
            Gtk::TreeModelColumn<std::string> m_col_pagatoil;
            Gtk::TreeModelColumn<std::string> m_col_stato;
            Gtk::TreeModelColumn<std::string> m_col_osservazioni;
            Gtk::TreeModelColumn<std::string> m_col_traslocato;
            Gtk::TreeModelColumn<double> m_col_diversi;
            Gtk::TreeModelColumn<double> m_col_affitto;
            Gtk::TreeModelColumn<double> m_col_posteggio;
            Gtk::TreeModelColumn<double> m_col_riscaldamento;
            Gtk::TreeModelColumn<Gdk::RGBA> m_coloreriga;

        };

        ModelColumns m_Columns;
        Gtk::TreeView* m_TreeView1;
        Glib::RefPtr<Gtk::ListStore> m_refTreeModel;

};

the main:

MainWindow::MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade) :
    Gtk::ApplicationWindow(cobject), refBuilder(refGlade){

    Glib::RefPtr<Gtk::CssProvider> cssProvider = Gtk::CssProvider::create();
    cssProvider->load_from_path("style.css");
    //cssProvider->load_from_data(cssProvider, ".treeview row:nth-child(even){  background-color: #ff0000; } .treeview row:nth-child(odd){ background-color: #000000; }", -1, NULL);
    Glib::RefPtr<Gtk::StyleContext> styleContext = Gtk::StyleContext::create();
    Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();
    styleContext->add_provider_for_screen(screen, cssProvider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    const char* user = "root";
    const char* passwd = "";
    const char* database = "";
    const char* dbhost = "192.168.1.5";

    connection = mysql_init(NULL);

    mysql_real_connect(connection, dbhost, user, passwd, database, 3307, NULL, 0);

    refBuilder->get_widget("m_TreeView1", m_TreeView1);

    //m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this, &MainWindow::on_button_quit) );

    m_refTreeModel = Gtk::ListStore::create(m_Columns);
    m_TreeView1->set_model(m_refTreeModel);
Affitto* affitti = new Affitto(connection);
    MYSQL_RES* res = affitti->getAll();
    MYSQL_ROW riga;
    Gtk::TreeModel::Row row;
Gtk::CellRendererText* textRenderer = manage(new Gtk::CellRendererText());
    Gtk::TreeViewColumn *col = manage(new Gtk::TreeViewColumn("InqId", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_coloreriga);
    m_TreeView1->append_column(*col);

    textRenderer = manage(new Gtk::CellRendererText());
    col = manage(new Gtk::TreeViewColumn("Cognome e nome", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_coloreriga);
    m_TreeView1->append_column(*col);
m_TreeView1->append_column("Stabile", m_Columns.m_col_stabile);
    m_TreeView1->append_column("Mese", m_Columns.m_col_mese);
    m_TreeView1->append_column("Anno", m_Columns.m_col_anno);
    m_TreeView1->append_column("Posteggio pagato", m_Columns.m_col_posteggiopagato);
    m_TreeView1->append_column("Affitto pagato", m_Columns.m_col_affittopagato);
    m_TreeView1->append_column("Riscaldamento pagato", m_Columns.m_col_riscaldamentopagato);
    m_TreeView1->append_column("Pagato il", m_Columns.m_col_pagatoil);
    m_TreeView1->append_column("Stato", m_Columns.m_col_stato);
    m_TreeView1->append_column("Osservazioni", m_Columns.m_col_osservazioni);
    m_TreeView1->append_column("Traslocato", m_Columns.m_col_traslocato);
    m_TreeView1->append_column("Diversi", m_Columns.m_col_diversi);
    m_TreeView1->append_column("Affitto", m_Columns.m_col_affitto);
    m_TreeView1->append_column("Posteggio", m_Columns.m_col_posteggio);
    m_TreeView1->append_column("Riscaldamento", m_Columns.m_col_riscaldamento);

 int i=0;
    while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);
        row[m_Columns.m_col_cognomenome] = riga[1];
        row[m_Columns.m_col_stabile] = riga[2];
        row[m_Columns.m_col_mese] = std::stoi(riga[3]);
        row[m_Columns.m_col_anno] = std::stoi(riga[4]);
        row[m_Columns.m_col_posteggiopagato] = std::stod(riga[5]);
        row[m_Columns.m_col_affittopagato] = std::stod(riga[6]);
        row[m_Columns.m_col_riscaldamentopagato] = std::stod(riga[7]);
        row[m_Columns.m_col_pagatoil] = riga[8];
        row[m_Columns.m_col_stato] = riga[9];
        row[m_Columns.m_col_osservazioni] = riga[10];
        row[m_Columns.m_col_traslocato] = riga[11];
        row[m_Columns.m_col_diversi] = std::stod(riga[12]);
        row[m_Columns.m_col_affitto] = std::stod(riga[13]);
        row[m_Columns.m_col_posteggio] = std::stod(riga[14]);
        row[m_Columns.m_col_riscaldamento] = std::stod(riga[15]);

        if(i%2 == 0)
            row[m_Columns.m_coloreriga] = Gdk::RGBA("#ff0000");
        else
            row[m_Columns.m_coloreriga] = Gdk::RGBA("#cccccc");
        i++;
    }

    mysql_free_result(res);
    mysql_close(connection);

}


问:
EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging
I'm trying to run npm install on my project but its showing EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules.staging

I don't have root administrative access. I'am using as local user in my system and my system is windows 10

node v10.16.3
npm  v6.11.3

Can any one please help me to resolve this issue. I'am requesting you guys please.

```<code>3235 error code EPERM
3236 error syscall mkdir
3237 error path C:\Program Files\nodejs\node_modules\.staging
3238 error errno -4048
3239 error Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging'
3239 error  { [Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging']
3239 error   cause:
3239 error    { Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging'
3239 error      errno: -4048,
3239 error      code: 'EPERM',
3239 error      syscall: 'mkdir',
3239 error      path: 'C:\\Program Files\\nodejs\\node_modules\\.staging' },
3239 error   stack:
3239 error    'Error: EPERM: operation not permitted, mkdir \'C:\\Program Files\\nodejs\\node_modules\\.staging\'',
3239 error   errno: -4048,
3239 error   code: 'EPERM',
3239 error   syscall: 'mkdir',
3239 error   path: 'C:\\Program Files\\nodejs\\node_modules\\.staging',
3239 error   parent: 'nodemon' }
3240 error The operation was rejected by your operating system.
3240 error It's possible that the file was already in use (by a text editor or antivirus),
3240 error or that you lack permissions to access it.
3240 error
3240 error If you believe this might be a permissions issue, please double-check the
3240 error permissions of the file and its containing directories, or try running
3240 error the command again as root/Administrator.
3241 verbose exit [ -4048, true ]
</code>```

答:
run these commands:

```<code>npm uninstall -g create-react-app

npm install -g create-react-app
</code>```

that's will upgrade your npx, then run

```<code>npx create-react-app my-app
</code>```

Body:
I'm trying to run npm install on my project but its showing EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules.staging

I don't have root administrative access. I'am using as local user in my system and my system is windows 10

node v10.16.3
npm  v6.11.3

Can any one please help me to resolve this issue. I'am requesting you guys please.

3235 error code EPERM
3236 error syscall mkdir
3237 error path C:\Program Files\nodejs\node_modules\.staging
3238 error errno -4048
3239 error Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging'
3239 error  { [Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging']
3239 error   cause:
3239 error    { Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging'
3239 error      errno: -4048,
3239 error      code: 'EPERM',
3239 error      syscall: 'mkdir',
3239 error      path: 'C:\\Program Files\\nodejs\\node_modules\\.staging' },
3239 error   stack:
3239 error    'Error: EPERM: operation not permitted, mkdir \'C:\\Program Files\\nodejs\\node_modules\\.staging\'',
3239 error   errno: -4048,
3239 error   code: 'EPERM',
3239 error   syscall: 'mkdir',
3239 error   path: 'C:\\Program Files\\nodejs\\node_modules\\.staging',
3239 error   parent: 'nodemon' }
3240 error The operation was rejected by your operating system.
3240 error It's possible that the file was already in use (by a text editor or antivirus),
3240 error or that you lack permissions to access it.
3240 error
3240 error If you believe this might be a permissions issue, please double-check the
3240 error permissions of the file and its containing directories, or try running
3240 error the command again as root/Administrator.
3241 verbose exit [ -4048, true ]

Body:
run these commands:

npm uninstall -g create-react-app

npm install -g create-react-app

that's will upgrade your npx, then run

npx create-react-app my-app


问:
Start background process/daemon from CGI script
I'm trying to launch a background process from a CGI scripts.  Basically, when a form is submitted the CGI script will indicate to the user that his or her request is being processed, while the background script does the actual processing (because the processing tends to take a long time.)  The problem I'm facing is that Apache won't send the output of the parent CGI script to the browser until the child script terminates.

I've been told by a colleague that what I want to do is impossible because there is no way to prevent Apache from waiting for the entire process tree of a CGI script to die.  However, I've also seen numerous references around the web to a "double fork" trick which is supposed to do the job.  The trick is described succinctly in this Stack Overflow answer, but I've seen similar code elsewhere.

Here's a short script I wrote to test the double-fork trick in Python:

```<code>import os
import sys

if os.fork():
    print 'Content-type: text/html\n\n Done'
    sys.exit(0)

if os.fork():
    os.setsid()
    sys.exit(0)

# Second child
os.chdir("/")
sys.stdout.close()
sys.stderr.close()
sys.stdin.close()

f = open('/tmp/lol.txt', 'w')

while 1:
     f.write('test\n')
</code>```

If I run this from the shell, it does exactly what I'd expect: the original script and first descendant die, and the second descendant keeps running until it's killed manually.  But if I access it through CGI, the page won't load until I kill the second descendant or Apache kills it because of the CGI timeout.  I've also tried replacing the second sys.exit(0) with os._exit(0), but there is no difference.

What am I doing wrong?

答:
I haven't tried using fork but I have accomplished what you're asking by executing a sys.stdout.flush() after the original message, before calling the background process.

i.e.

```<code>print "Please wait..."
sys.stdout.flush()

output = some_processing() # put what you want to accomplish here
print output               # in my case output was a redirect to a results page
</code>```

Body:
I'm trying to launch a background process from a CGI scripts.  Basically, when a form is submitted the CGI script will indicate to the user that his or her request is being processed, while the background script does the actual processing (because the processing tends to take a long time.)  The problem I'm facing is that Apache won't send the output of the parent CGI script to the browser until the child script terminates.

I've been told by a colleague that what I want to do is impossible because there is no way to prevent Apache from waiting for the entire process tree of a CGI script to die.  However, I've also seen numerous references around the web to a "double fork" trick which is supposed to do the job.  The trick is described succinctly in this Stack Overflow answer, but I've seen similar code elsewhere.

Here's a short script I wrote to test the double-fork trick in Python:

import os
import sys

if os.fork():
    print 'Content-type: text/html\n\n Done'
    sys.exit(0)

if os.fork():
    os.setsid()
    sys.exit(0)

# Second child
os.chdir("/")
sys.stdout.close()
sys.stderr.close()
sys.stdin.close()

f = open('/tmp/lol.txt', 'w')

while 1:
     f.write('test\n')

If I run this from the shell, it does exactly what I'd expect: the original script and first descendant die, and the second descendant keeps running until it's killed manually.  But if I access it through CGI, the page won't load until I kill the second descendant or Apache kills it because of the CGI timeout.  I've also tried replacing the second sys.exit(0) with os._exit(0), but there is no difference.

What am I doing wrong?

Body:
I haven't tried using fork but I have accomplished what you're asking by executing a sys.stdout.flush() after the original message, before calling the background process.

i.e.

print "Please wait..."
sys.stdout.flush()

output = some_processing() # put what you want to accomplish here
print output               # in my case output was a redirect to a results page


问:
OSGi tests no longer working after upgrading from Groovy 2.5 to Groovy 3.0
I have a pax-exam test that looks like this:

@RunWith(PaxExam.class)
public class XmlPathOSGiITest {

    @Configuration
    public static Option[] configure() {
        return new Option[]
                {
                        /* System Properties */
                        systemProperty(EXAM_FAIL_ON_UNRESOLVED_KEY).value("true"),
                        systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),

                        /* Hamcrest & JUnit bundles */
                        restAssuredJunitBundles(),

                        /* Transitive dependencies needed in the Pax Exam container.
                        Some of these need to be wrapped because they are not available as OSGi bundles */
                        mavenBundle().groupId("org.apache.aries.spifly").artifactId("org.apache.aries.spifly.dynamic.bundle").version("1.2.1"),
                        mavenBundle().groupId("org.hamcrest").artifactId("hamcrest").versionAsInProject(),
                        mavenBundle().groupId("org.apache.commons").artifactId("commons-lang3").versionAsInProject(),
                        mavenBundle().groupId("org.codehaus.groovy").artifactId("groovy-json").versionAsInProject().noStart(),
                        mavenBundle().groupId("org.codehaus.groovy").artifactId("groovy-xml").versionAsInProject().noStart(),
                        mavenBundle().groupId("org.codehaus.groovy").artifactId("groovy").versionAsInProject(),

                        wrappedBundle(mavenBundle().groupId("org.ccil.cowan.tagsoup").artifactId("tagsoup").versionAsInProject()),
                        wrappedBundle(mavenBundle("jakarta.xml.bind", "jakarta.xml.bind-api").versionAsInProject()),
                        wrappedBundle(mavenBundle("javax.activation", "activation").version("1.1.1")),
                        wrappedBundle(mavenBundle("org.apache.httpcomponents", "httpclient").versionAsInProject()),
                        wrappedBundle(mavenBundle("org.apache.httpcomponents", "httpmime").versionAsInProject()),
                        wrappedBundle(mavenBundle("org.apache.httpcomponents", "httpcore").versionAsInProject()),

                        /* Rest Assured dependencies needed in the Pax Exam container to be able to execute the tests below */
                        mavenBundle("io.rest-assured", "json-path").versionAsInProject(),
                        mavenBundle("io.rest-assured", "xml-path").versionAsInProject(),
                        mavenBundle("io.rest-assured", "rest-assured").versionAsInProject(),
                        mavenBundle("io.rest-assured", "rest-assured-common").versionAsInProject()
                };
    }

    @Test
    public void getUUIDParsesAStringResultToUUID() {
        final String UUID_XML = "<some>\n" +
                "  <thing id=\"1\">db24eeeb-7fe5-41d3-8f06-986b793ecc91</thing>\n" +
                "  <thing id=\"2\">d69ded28-d75c-460f-9cbe-1412c60ed4cc</thing>\n" +
                "</some>";

        final UUID uuid = from(UUID_XML).getUUID("some.thing[0]");

        assertThat(uuid, Matchers.equalTo(UUID.fromString("db24eeeb-7fe5-41d3-8f06-986b793ecc91")));
    }
}
```

<p>This used to work fine with Groovy 2.5 but after upgrading to Groovy 3.0 I get the following error:</p>

```java.lang.ClassNotFoundException: org.codehaus.groovy.runtime.ScriptBytecodeAdapter not found by groovy-xml [20]

    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1597)
    at org.apache.felix.framework.BundleWiringImpl.access$300(BundleWiringImpl.java:79)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1982)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at org.apache.felix.framework.BundleWiringImpl.getClassByDelegation(BundleWiringImpl.java:1375)
    at org.apache.felix.framework.BundleWiringImpl.searchImports(BundleWiringImpl.java:1618)
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1548)
    at org.apache.felix.framework.BundleWiringImpl.access$300(BundleWiringImpl.java:79)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1982)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at io.restassured.internal.common.assertion.AssertParameter.notNull(AssertParameter.groovy:25)
    at io.restassured.path.xml.XmlPath.get(XmlPath.java:316)
    at io.restassured.path.xml.XmlPath.getUUID(XmlPath.java:584)
    at io.restassured.test.osgi.XmlPathOSGiITest.getUUIDParsesAStringResultToUUID(XmlPathOSGiITest.java:84)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runLeafWithRetry(ContainerTestRunner.java:97)
    at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runChildWithRetry(ContainerTestRunner.java:84)
    at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runChild(ContainerTestRunner.java:75)
    at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runChild(ContainerTestRunner.java:43)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.invokeViaJUnit(JUnitProbeInvoker.java:124)
    at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.findAndInvoke(JUnitProbeInvoker.java:97)
    at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.call(JUnitProbeInvoker.java:73)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:566)
    at org.ops4j.pax.swissbox.framework.RemoteFrameworkImpl.invokeMethodOnService(RemoteFrameworkImpl.java:435)
    at org.ops4j.pax.swissbox.framework.RemoteFrameworkImpl.invokeMethodOnService(RemoteFrameworkImpl.java:408)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:566)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.lang.Thread.run(Thread.java:834)
```

I've checked mvn dependency:tree to make sure that I have no remnants of Groovy 2.5.x still in the classpath.

What could be the cause of this and how do I fix it? Note that you can find the project on github here.

答:
I think this might be caused by the groovy internal class loading. Likely groovy uses the class loader of the user bundle to load its own class ScriptBytecodeAdapter. It should use its own class loader for this. Btw. The easiest way to get such class loaders is to get the class loader of a known class.

In OSGi the class loader of a class is always the class loader of the bundle the class resides in.

Body:
I have a pax-exam test that looks like this:

@RunWith(PaxExam.class)
public class XmlPathOSGiITest {

    @Configuration
    public static Option[] configure() {
        return new Option[]
                {
                        /* System Properties */
                        systemProperty(EXAM_FAIL_ON_UNRESOLVED_KEY).value("true"),
                        systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),

                        /* Hamcrest & JUnit bundles */
                        restAssuredJunitBundles(),

                        /* Transitive dependencies needed in the Pax Exam container.
                        Some of these need to be wrapped because they are not available as OSGi bundles */
                        mavenBundle().groupId("org.apache.aries.spifly").artifactId("org.apache.aries.spifly.dynamic.bundle").version("1.2.1"),
                        mavenBundle().groupId("org.hamcrest").artifactId("hamcrest").versionAsInProject(),
                        mavenBundle().groupId("org.apache.commons").artifactId("commons-lang3").versionAsInProject(),
                        mavenBundle().groupId("org.codehaus.groovy").artifactId("groovy-json").versionAsInProject().noStart(),
                        mavenBundle().groupId("org.codehaus.groovy").artifactId("groovy-xml").versionAsInProject().noStart(),
                        mavenBundle().groupId("org.codehaus.groovy").artifactId("groovy").versionAsInProject(),

                        wrappedBundle(mavenBundle().groupId("org.ccil.cowan.tagsoup").artifactId("tagsoup").versionAsInProject()),
                        wrappedBundle(mavenBundle("jakarta.xml.bind", "jakarta.xml.bind-api").versionAsInProject()),
                        wrappedBundle(mavenBundle("javax.activation", "activation").version("1.1.1")),
                        wrappedBundle(mavenBundle("org.apache.httpcomponents", "httpclient").versionAsInProject()),
                        wrappedBundle(mavenBundle("org.apache.httpcomponents", "httpmime").versionAsInProject()),
                        wrappedBundle(mavenBundle("org.apache.httpcomponents", "httpcore").versionAsInProject()),

                        /* Rest Assured dependencies needed in the Pax Exam container to be able to execute the tests below */
                        mavenBundle("io.rest-assured", "json-path").versionAsInProject(),
                        mavenBundle("io.rest-assured", "xml-path").versionAsInProject(),
                        mavenBundle("io.rest-assured", "rest-assured").versionAsInProject(),
                        mavenBundle("io.rest-assured", "rest-assured-common").versionAsInProject()
                };
    }

    @Test
    public void getUUIDParsesAStringResultToUUID() {
        final String UUID_XML = "<some>\n" +
                "  <thing id=\"1\">db24eeeb-7fe5-41d3-8f06-986b793ecc91</thing>\n" +
                "  <thing id=\"2\">d69ded28-d75c-460f-9cbe-1412c60ed4cc</thing>\n" +
                "</some>";

        final UUID uuid = from(UUID_XML).getUUID("some.thing[0]");

        assertThat(uuid, Matchers.equalTo(UUID.fromString("db24eeeb-7fe5-41d3-8f06-986b793ecc91")));
    }
}

This used to work fine with Groovy 2.5 but after upgrading to Groovy 3.0 I get the following error:

java.lang.ClassNotFoundException: org.codehaus.groovy.runtime.ScriptBytecodeAdapter not found by groovy-xml [20]

    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1597)
    at org.apache.felix.framework.BundleWiringImpl.access$300(BundleWiringImpl.java:79)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1982)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at org.apache.felix.framework.BundleWiringImpl.getClassByDelegation(BundleWiringImpl.java:1375)
    at org.apache.felix.framework.BundleWiringImpl.searchImports(BundleWiringImpl.java:1618)
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1548)
    at org.apache.felix.framework.BundleWiringImpl.access$300(BundleWiringImpl.java:79)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1982)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at io.restassured.internal.common.assertion.AssertParameter.notNull(AssertParameter.groovy:25)
    at io.restassured.path.xml.XmlPath.get(XmlPath.java:316)
    at io.restassured.path.xml.XmlPath.getUUID(XmlPath.java:584)
    at io.restassured.test.osgi.XmlPathOSGiITest.getUUIDParsesAStringResultToUUID(XmlPathOSGiITest.java:84)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runLeafWithRetry(ContainerTestRunner.java:97)
    at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runChildWithRetry(ContainerTestRunner.java:84)
    at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runChild(ContainerTestRunner.java:75)
    at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runChild(ContainerTestRunner.java:43)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.invokeViaJUnit(JUnitProbeInvoker.java:124)
    at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.findAndInvoke(JUnitProbeInvoker.java:97)
    at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.call(JUnitProbeInvoker.java:73)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:566)
    at org.ops4j.pax.swissbox.framework.RemoteFrameworkImpl.invokeMethodOnService(RemoteFrameworkImpl.java:435)
    at org.ops4j.pax.swissbox.framework.RemoteFrameworkImpl.invokeMethodOnService(RemoteFrameworkImpl.java:408)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:566)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.lang.Thread.run(Thread.java:834)

I've checked mvn dependency:tree to make sure that I have no remnants of Groovy 2.5.x still in the classpath.

What could be the cause of this and how do I fix it? Note that you can find the project on github here.