问:
Initializing Firebase auth object error
I am getting an error whenever I try to run the app:

Here is .java class:

```<code>package com.safariagaming.flix;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class SignUpScreen extends AppCompatActivity implements View.OnClickListener{

    //defining view objects
    private EditText editTextEmail;
    private EditText editTextPassword;
    private Button buttonSignup;
    private ProgressDialog progressDialog;

    //defining firebaseauth object
    private FirebaseAuth firebaseAuth;

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

        //initializing firebase auth object
        firebaseAuth = FirebaseAuth.getInstance();

        //initializing views
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        buttonSignup = (Button) findViewById(R.id.buttonSignup);

        progressDialog = new ProgressDialog(this);

        //attaching listener to button
        buttonSignup.setOnClickListener(this);
    }

    private void registerUser(){

        //getting email and password from edit texts
        String email = editTextEmail.getText().toString().trim();
        String password  = editTextPassword.getText().toString().trim();

        //checking if email and passwords are empty
        if(TextUtils.isEmpty(email)){
            Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show();
            return;
        }

        if(TextUtils.isEmpty(password)){
            Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show();
            return;
        }

        //if the email and password are not empty
        //displaying a progress dialog

        progressDialog.setMessage("Registering Please Wait...");

        //creating a new user
        firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        //checking if success
                        if(task.isSuccessful()){
                            //display some message here
                            Toast.makeText(SignUpScreen.this,"Successfully registered",Toast.LENGTH_LONG).show();
                        }else{
                            //display some message here
                            Toast.makeText(SignUpScreen.this,"Registration Error",Toast.LENGTH_LONG).show();
                        }
                        progressDialog.dismiss();
                    }
                });

    }

    @Override
    public void onClick(View view) {
        //calling register method on click
        registerUser();
    }
}
</code>```

(I think that the error happens because I am not initializing firebase auth object correctly)

Here is my XML class

```<code>android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>

<LinearLayout
    android:layout_centerVertical="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:hint="Enter email"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:hint="Enter password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/buttonSignup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:text="Signup" />

</LinearLayout>
</code>```

Here is my error message that I am encountering

```<code>03-29 18:14:49.700 9230-9230/com.safariagaming.flix E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.safariagaming.flix, PID: 9230
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(java.lang.String, java.lang.String)' on a null object reference
                                                                      at com.safariagaming.flix.SignUpScreen.registerUser(SignUpScreen.java:72)
                                                                      at com.safariagaming.flix.SignUpScreen.onClick(SignUpScreen.java:93)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22429)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答:
java.lang.NullPointerException: Attempt to invoke virtual method
  'com.google.android.gms.tasks.Task
  com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(java.lang.String,
  java.lang.String)' on a null object reference

This means your mAuth member variable is null.  You probably never assigned a value to it.  Assign it with mAuth = FirebaseAuth.getInstance() during onCreate() or at least some time before you call createUserWithEmailAndPassword on it.

Title: Initializing Firebase auth object error

Body:
I am getting an error whenever I try to run the app:

Here is .java class:

package com.safariagaming.flix;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class SignUpScreen extends AppCompatActivity implements View.OnClickListener{

    //defining view objects
    private EditText editTextEmail;
    private EditText editTextPassword;
    private Button buttonSignup;
    private ProgressDialog progressDialog;

    //defining firebaseauth object
    private FirebaseAuth firebaseAuth;

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

        //initializing firebase auth object
        firebaseAuth = FirebaseAuth.getInstance();

        //initializing views
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        buttonSignup = (Button) findViewById(R.id.buttonSignup);

        progressDialog = new ProgressDialog(this);

        //attaching listener to button
        buttonSignup.setOnClickListener(this);
    }

    private void registerUser(){

        //getting email and password from edit texts
        String email = editTextEmail.getText().toString().trim();
        String password  = editTextPassword.getText().toString().trim();

        //checking if email and passwords are empty
        if(TextUtils.isEmpty(email)){
            Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show();
            return;
        }

        if(TextUtils.isEmpty(password)){
            Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show();
            return;
        }

        //if the email and password are not empty
        //displaying a progress dialog

        progressDialog.setMessage("Registering Please Wait...");

        //creating a new user
        firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        //checking if success
                        if(task.isSuccessful()){
                            //display some message here
                            Toast.makeText(SignUpScreen.this,"Successfully registered",Toast.LENGTH_LONG).show();
                        }else{
                            //display some message here
                            Toast.makeText(SignUpScreen.this,"Registration Error",Toast.LENGTH_LONG).show();
                        }
                        progressDialog.dismiss();
                    }
                });

    }

    @Override
    public void onClick(View view) {
        //calling register method on click
        registerUser();
    }
}

(I think that the error happens because I am not initializing firebase auth object correctly)

Here is my XML class

android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>

<LinearLayout
    android:layout_centerVertical="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:hint="Enter email"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:hint="Enter password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/buttonSignup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:text="Signup" />

</LinearLayout>

Here is my error message that I am encountering

03-29 18:14:49.700 9230-9230/com.safariagaming.flix E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.safariagaming.flix, PID: 9230
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(java.lang.String, java.lang.String)' on a null object reference
                                                                      at com.safariagaming.flix.SignUpScreen.registerUser(SignUpScreen.java:72)
                                                                      at com.safariagaming.flix.SignUpScreen.onClick(SignUpScreen.java:93)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22429)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)


来源: stackexchange

问:
How to subtract days from a plain Date?
Is there an easy way of taking a olain JavaScript Date (e.g. today) and going back X days?

So, for example, if I want to calculate the date 5 days before today.

答:
for me all the combinations worked fine with below code snipplet ,
 the snippet is for Angular-2 implementation ,
if you need to add days , pass positive numberofDays , if you need to substract pass negative numberofDays</p>

```<code>function addSubstractDays(date: Date, numberofDays: number): Date {
let d = new Date(date);
return new Date(
    d.getFullYear(),
    d.getMonth(),
    (d.getDate() + numberofDays)
);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to subtract days from a plain Date?

Body:
for me all the combinations worked fine with below code snipplet ,
 the snippet is for Angular-2 implementation ,
if you need to add days , pass positive numberofDays , if you need to substract pass negative numberofDays

function addSubstractDays(date: Date, numberofDays: number): Date {
let d = new Date(date);
return new Date(
    d.getFullYear(),
    d.getMonth(),
    (d.getDate() + numberofDays)
);
}

ContentLicense: CC BY-SA 3.0


问:
Strong Loopback group_by aggregation
I have searched a lot to find a way for aggregation using loopback mongodb, unfortunately no perfect solution found. One of them is here
But can't implement this, any one to help me solve this problem, with any new solution, or describing above link. </p>

答:
Loopback doesn't provide a way to do an aggregation query, but you can find another solution in: https://github.com/strongloop/loopback/issues/890</p>

```<code>//Using the datasource we are making a direct request to MongoDB instead of use the PersistedModel of Loopback
var bookCollection = Book.getDataSource().connector.collection(Book.modelName);

bookCollection.aggregate({
    $group: {
        _id: { category: "$category", author: "$author" },
        total: { $sum: 1 }
    }
}, function(err, groupByRecords) {
    if(err) {
        next(err);
    } else {
        next();
    }
});
</code>```

Title: Strong Loopback group_by aggregation

Body:
Loopback doesn't provide a way to do an aggregation query, but you can find another solution in: https://github.com/strongloop/loopback/issues/890

//Using the datasource we are making a direct request to MongoDB instead of use the PersistedModel of Loopback
var bookCollection = Book.getDataSource().connector.collection(Book.modelName);

bookCollection.aggregate({
    $group: {
        _id: { category: "$category", author: "$author" },
        total: { $sum: 1 }
    }
}, function(err, groupByRecords) {
    if(err) {
        next(err);
    } else {
        next();
    }
});


问:
mysql add variable value to result set inside stored procedure
I have this scenario (that work OK):

```<code>CREATE PROCEDURE `my_sp`(
  IN in_var VARCHAR(32),
  OUT out_var VARCHAR(255)
)
BEGIN

  DECLARE mysql_query VARCHAR(255);
  DECLARE mysql_result VARCHAR(32);

  SET @mysql_query = CONCAT("
    CALL other_BD.other_Stored_Procedure( '",in_var,"', @other_sp_result );
  ");

  PREPARE stmt FROM @mysql_query;
  EXECUTE stmt;
  SELECT @other_sp_result INTO @mysql_result;
  DEALLOCATE PREPARE stmt;

  IF (@mysql_result = 'OK')
  THEN
    SELECT * FROM my_table WHERE my_column = 'my_value' LIMIT 1;
    SET out_var = 'whatever';
  ELSE
    SET out_var = 'NOT OK';
  END IF;
END;
</code>```

PHP:

```<code>$dbh = new PDO( $connection_params );

$sql = "CALL my_sp( :in_var , @outvar )";

$stmt = $dbh->prepare( $sql );
$stmt->execute( array( ':in_var' => $_POST['in_var'] ) );

//that return the result from SELECT * FROM my_table ... (from my_sp)
$result1 = $stmt->fetchAll( PDO::FETCH_ASSOC );

//That avoid error: Cannot execute queries while other unbuffered queries are active ...
$stmt->closeCursor();

$sql = "SELECT @outvar";
$query = $dbh->query( $sql );
//that return the out_var result ("whatever" for this case);
$result2 = $query->fetchAll( PDO::FETCH_ASSOC );
</code>```

And the question is:

Is there any way to add

SET out_var = 'whatever'

To the result of this

SELECT * FROM my_table WHERE my_column = 'my_value' LIMIT 1;

And thus make only one query in php to get all data together like:

col_1 => 'val', ... col_n => 'val' ... my_out_var => 'whatever_value'

答:
Finally I solved myself using this:

```<code>SELECT * , @out_var as new_column FROM my_table WHERE my_column = 'my_value' LIMIT 1;
</code>```

So now I have the 'new_column' added to mi recordset as espected

col_1 => 'val', ... col_n => 'val' ... new_column => 'out_var_value'

Body:
I have this scenario (that work OK):

CREATE PROCEDURE `my_sp`(
  IN in_var VARCHAR(32),
  OUT out_var VARCHAR(255)
)
BEGIN

  DECLARE mysql_query VARCHAR(255);
  DECLARE mysql_result VARCHAR(32);

  SET @mysql_query = CONCAT("
    CALL other_BD.other_Stored_Procedure( '",in_var,"', @other_sp_result );
  ");

  PREPARE stmt FROM @mysql_query;
  EXECUTE stmt;
  SELECT @other_sp_result INTO @mysql_result;
  DEALLOCATE PREPARE stmt;

  IF (@mysql_result = 'OK')
  THEN
    SELECT * FROM my_table WHERE my_column = 'my_value' LIMIT 1;
    SET out_var = 'whatever';
  ELSE
    SET out_var = 'NOT OK';
  END IF;
END;

PHP:

$dbh = new PDO( $connection_params );

$sql = "CALL my_sp( :in_var , @outvar )";

$stmt = $dbh->prepare( $sql );
$stmt->execute( array( ':in_var' => $_POST['in_var'] ) );

//that return the result from SELECT * FROM my_table ... (from my_sp)
$result1 = $stmt->fetchAll( PDO::FETCH_ASSOC );

//That avoid error: Cannot execute queries while other unbuffered queries are active ...
$stmt->closeCursor();

$sql = "SELECT @outvar";
$query = $dbh->query( $sql );
//that return the out_var result ("whatever" for this case);
$result2 = $query->fetchAll( PDO::FETCH_ASSOC );

And the question is:

Is there any way to add

SET out_var = 'whatever'

To the result of this

SELECT * FROM my_table WHERE my_column = 'my_value' LIMIT 1;

And thus make only one query in php to get all data together like:

col_1 => 'val', ... col_n => 'val' ... my_out_var => 'whatever_value'

Body:
Finally I solved myself using this:

SELECT * , @out_var as new_column FROM my_table WHERE my_column = 'my_value' LIMIT 1;

So now I have the 'new_column' added to mi recordset as espected

col_1 => 'val', ... col_n => 'val' ... new_column => 'out_var_value'


问:
What would be the best way to make a sort of drop-down-more-info div?
I have 4 divs with a more-info button on the bottom of each, like so:

http://codepen.io/anon/pen/VpVbPq

And when a user presses ' more info ' I would like for it to extend to the bottom and show extra info, obviously.

The problem is under the more-info div, text is seen, but what if I want to hide whats under it, even if its opacity is 0.6 ?

I thought it would've been the best if I draw what I need, so here:

Codepen code below:

html

```<code><body>
  <div class="wrapper">
  <div class="info">
      <p>
          dummy text
      </p>
        <div class="more-info">more info</div>
      </div>
      <div class="info"><div class="more-info">more info</div></div>
      <div class="info"><div class="more-info">more info</div></div>
      <div class="info"><div class="more-info">more info</div></div>
    </div>
</body>
</code>```

css

```<code>.wrapper  {
  width: 1045px;
  margin: 0 auto;
}
.info  {
  width: 500px; height: 200px;
  background-color: #1A5AB6;
  display: inline-block;
  margin: 10px;
  position: relative;
  font-size: 20px;
  overflow: hidden;
}
.more-info {
  width: 100%; height: 40px;
  background-color: #0C1B44;
  bottom: 0; left: 0;
  display: inline-block;
  position: absolute;
  font-size: 20px;
  color: white;
  line-height: 35px;
  text-align: center;
  opacity: 0.6;
}
.more-info:hover  {background-color: #010716;}
</code>```

答:
change your class selector definition as shown below:

```<code>.more-info {
    width: 100%; height: 20%;
    background-color: #0C1B44;
    font-size: 20px;
    color: white;
    display: block;
    text-align: center;
    opacity: 0.6;
 }
</code>```

Then add this css for your paragraph element:

```<code>p {
  height: 75%;
  overflow: hidden;
  margin: 5px;
}
</code>```

Body:
I have 4 divs with a more-info button on the bottom of each, like so:

http://codepen.io/anon/pen/VpVbPq

And when a user presses ' more info ' I would like for it to extend to the bottom and show extra info, obviously.

The problem is under the more-info div, text is seen, but what if I want to hide whats under it, even if its opacity is 0.6 ?

I thought it would've been the best if I draw what I need, so here:

Codepen code below:

html

          dummy text

more info

more info

more info

more info

css

.wrapper  {
  width: 1045px;
  margin: 0 auto;
}
.info  {
  width: 500px; height: 200px;
  background-color: #1A5AB6;
  display: inline-block;
  margin: 10px;
  position: relative;
  font-size: 20px;
  overflow: hidden;
}
.more-info {
  width: 100%; height: 40px;
  background-color: #0C1B44;
  bottom: 0; left: 0;
  display: inline-block;
  position: absolute;
  font-size: 20px;
  color: white;
  line-height: 35px;
  text-align: center;
  opacity: 0.6;
}
.more-info:hover  {background-color: #010716;}

Body:
change your class selector definition as shown below:

.more-info {
    width: 100%; height: 20%;
    background-color: #0C1B44;
    font-size: 20px;
    color: white;
    display: block;
    text-align: center;
    opacity: 0.6;
 }

Then add this css for your paragraph element:

p {
  height: 75%;
  overflow: hidden;
  margin: 5px;
}


问:
Print Binary Tree with Empty Nodes
Is there a way for me to print a binary tree level by level while displaying a NULL every time there is an empty node?

For example, let's say we have this tree:

And the output should look like this:

```<code>A
B C
D NULL E F
</code>```

How should I go about writing the code to produce said output with the tree? Thanks in advance. This is my first post here. Sorry if the formatting and syntax is off.

答:
The ideas and algorithmic concepts exposed are more important here, than what technology you apply. That being said:

C++ Answer (easily portable to C#):

Assuming a classical Binary Tree structure similar to this:

```<code>struct node {
   char data;
   node* left;
   node* right;
}

// Function to print each level in the tree*
void printByLevel(node* root) { // Copy root node, pass by value.
   int height = height(root); // Get tree height. Total amount of levels to print.
   for (int i = 1; i <= h; i++) {
       printLevel(root, i);
       std::cout << std::endl; // A line after each level is printed.
   }
}
</code>```

You will need the auxiliary function below, as well as function for computing your tree height to be able to execute the function above.

```<code>// Print nodes at ONE specific level
void printLevel(node* root, int level) { // Copy root node, pass by value.
    if (root != nullptr) {
       if (level == 1)
          std::cout << root->data << ' ';
       else if (level > 1) {
          printLevel(root->left, level-1);
          printLevel(root->right, level-1);
       }
    }
    std::cout << "NULL" << ' '; // No value, print "NULL"
}
</code>```

Title: Print Binary Tree with Empty Nodes

Body:
Is there a way for me to print a binary tree level by level while displaying a NULL every time there is an empty node?

For example, let's say we have this tree:

And the output should look like this:

A
B C
D NULL E F

How should I go about writing the code to produce said output with the tree? Thanks in advance. This is my first post here. Sorry if the formatting and syntax is off.

Body:
The ideas and algorithmic concepts exposed are more important here, than what technology you apply. That being said:

C++ Answer (easily portable to C#):

Assuming a classical Binary Tree structure similar to this:

struct node {
   char data;
   node* left;
   node* right;
}

// Function to print each level in the tree*
void printByLevel(node* root) { // Copy root node, pass by value.
   int height = height(root); // Get tree height. Total amount of levels to print.
   for (int i = 1; i <= h; i++) {
       printLevel(root, i);
       std::cout << std::endl; // A line after each level is printed.
   }
}

You will need the auxiliary function below, as well as function for computing your tree height to be able to execute the function above.

// Print nodes at ONE specific level
void printLevel(node* root, int level) { // Copy root node, pass by value.
    if (root != nullptr) {
       if (level == 1)
          std::cout << root->data << ' ';
       else if (level > 1) {
          printLevel(root->left, level-1);
          printLevel(root->right, level-1);
       }
    }
    std::cout << "NULL" << ' '; // No value, print "NULL"
}


问:
Flashing listBox in c#
i want to know if it's possible to flash listbox.
I'm creating a chat application (client-server) with c# and winform and i want to make my listbox flash when i receive a new message.
It's possible ? thank you</p>

答:
Do you mean something like this?</p>

```<code>var originalColor = listBox1.BackgroundColor;
listBox1.BackgroundColor = Color.LightYellow;
await Task.Delay(new TimeSpan(0, 0, 0, 0, 100));
listBox1.BackgroundColor = originalColor;
</code>```

Title: Flashing listBox in c#

Body:
Do you mean something like this?

var originalColor = listBox1.BackgroundColor;
listBox1.BackgroundColor = Color.LightYellow;
await Task.Delay(new TimeSpan(0, 0, 0, 0, 100));
listBox1.BackgroundColor = originalColor;


问:
Can't remove invalid item from IntelliJ maven project with nested modules
In a maven project, I have a primary module A with several nested modules B, C, etc...

One of the nested modules has several references to dependencies I added to its POM and then removed. Each of these is listed as a Problem of the form: "Module B: invalid item 'opensaml-2.x.x' in the dependencies list.

I want to remove these old references and manually add a JAR file. However, for both these operations I get the same error:

Source root "...\A\B\src" cannot be defined in module "A" because it belongs to content of nested module "B"

I'm not trying to define any source root, though. I just want to delete a reference to a missing dependency and add a JAR file.

答:
Try right-clicking the parent module in the project panel and choosing "Maven->Reimport"

If that does not work then:

close the project

delete the .idea directory and all .iml files

Use "File/New/Project from existing sources..." to recreate the project

"Import project from external model"

select "Maven"

For one reason or another Idea's module structure can become messed up and it's easier to just reimport it. This generally happens when you have renamed a module or module directory.


问:
MSDN Licensing?
Simple question, but one I can't find an answer to on the MSDN subscriber site: As an MSDN Professional Subscriber, can I install the same copy of Windows 2008 in multiple VMs at the same time?

The MSDN keys state that they can be used for "multiple activations", but they don't state whether these are sequential or concurrent. I seem to recall that Windows 2008 Enterprise has its own "you can run multiple instances in VMs" terms. Did I remember that right, and does that apply to MSDN subscriptions?

答:
Yes - as long as you use them acording to msdn licence (developing, testing, presentation).

Your key will be valid for 10 activations, but you can ask for another key.

OwnerDisplayName: Roger Lipscombe

ContentLicense: CC BY-SA 2.5

Title: MSDN Licensing?

LastEditorDisplayName: moocha

OwnerDisplayName: dmajkic


问:
Documenting a method that just returns something
I'm writing some javadocs (actually they are jsdocs but it doesn't make a difference for this question) and found this repeating pattern:

Imagine a method that just returns a value, maybe product of some calculation. For example, let say it is the time in milliseconds since the unix epoch.

```<code>public long getTimeSinceTheEpoch(){

  //calculate time

  return time;
}
</code>```

So far, so good. Now when the time comes to add javadocs (or jsdocs, or rdocs, whatever), I've been writing something like this:

```<code>/**
* Gets the time in milliseconds since the unix epoch
*
* @returns the time in milliseconds since the unix epoch
*/
public long getTimeSinceTheEpoch(){
</code>```

Here, the problem is obvious.

My question is, what do you put in the body of the comment, and what do you choose for the @returns attribute of the comment?

IMPORTANT

I'm not a fan of these kind of comments, if it depended on me I would rename the method to something like getTimeInMillisecondsSinceTheEpoch and avoid the comments at all.

I cannot do that (avoid the comments), so I'm striving to make them as useful as possible.

答:
Best is to provide only the @return description as you need to document what you are returning for sure.

In the comment section, you could also throw in that same one-liner but also add how you are going to go about returning what you return, for e.g.

```<code>/**
* Gets the time in milliseconds since the unix epoch
* by doing something incredible.
* http://stackoverflow.com/questions/4307142/documenting-a-method-that-just-returns-something
*
* @note thank you stackoverflow
*
* @returns the time in milliseconds since the unix epoch
*/
public long getTimeSinceTheEpoch(){
</code>```

Body:
I'm writing some javadocs (actually they are jsdocs but it doesn't make a difference for this question) and found this repeating pattern:

Imagine a method that just returns a value, maybe product of some calculation. For example, let say it is the time in milliseconds since the unix epoch.

public long getTimeSinceTheEpoch(){

  //calculate time

  return time;
}

So far, so good. Now when the time comes to add javadocs (or jsdocs, or rdocs, whatever), I've been writing something like this:

/**
* Gets the time in milliseconds since the unix epoch
*
* @returns the time in milliseconds since the unix epoch
*/
public long getTimeSinceTheEpoch(){

Here, the problem is obvious.

My question is, what do you put in the body of the comment, and what do you choose for the @returns attribute of the comment?

IMPORTANT

I'm not a fan of these kind of comments, if it depended on me I would rename the method to something like getTimeInMillisecondsSinceTheEpoch and avoid the comments at all.

I cannot do that (avoid the comments), so I'm striving to make them as useful as possible.

Body:
Best is to provide only the @return description as you need to document what you are returning for sure.

In the comment section, you could also throw in that same one-liner but also add how you are going to go about returning what you return, for e.g.

/**
* Gets the time in milliseconds since the unix epoch
* by doing something incredible.
* http://stackoverflow.com/questions/4307142/documenting-a-method-that-just-returns-something
*
* @note thank you stackoverflow
*
* @returns the time in milliseconds since the unix epoch
*/
public long getTimeSinceTheEpoch(){


问:
To what extent do the Google OAuth 2.0 APIs support RFC7636?
I am looking for concrete information regarding the state of RFC7636 (proof key for OAuth token exchanges) in Google's OAuth2 APIs.

Google exposes an OAuth 2.0 and OIDC provider API where access tokens can be obtained. There is a proposed standard described in RFC7636 for using proof keys in token exchanges which we have started using in our integrations with major identity providers. Some accept the proof key, others ignore it; Google seems to be aware of it but fails to validate the proof key. I have not been able to find any mention of this wrt Google.

In concrete terms, when following the authorization code flow of OAuth 2.0 with Google as the provider we generate a random number, hash it using SHA256, base64 URL encode it, and then pass it to https://accounts.google.com/o/oauth2/v2/auth as parameter "code_challenge" and "code_challenge_method" as per the spec.

The endpoint accepts the parameters and issues an authorization token as usual. When obtaining the access token we call https://www.googleapis.com/oauth2/v4/token with the code_verifier; the endpoint returns the following HTTP 400 error which suggests that there is some awareness of code verifiers:
     {
       "error": "invalid_grant",
       "error_description": "Missing code verifier."
     }

Google's OAuth documentation at developers.google.com/identity/protocols/OAuth2 does not mention any of these parameters; the API playground does not extend to playing with the OAuth2 auth and token endpoints. Any insight would be greatly appreciated.

答: I was having this same problem using AppAuth and an Android clientId. In order to fix it I had to set a matching 'code_verifier' field on both the authorization and token requests.  You can find a more in depth description in this post: invalid_grant trying to get oAuth token from google</p>


问:
Is an OAuth refresh token a valid / secure alternative for a mobile device identifier
Asking as a relative n00b on mobile applications here as I'm primarily a backend developer.

We are building a mobile app and have a business requirement for users' devices to be uniquely identified and registered with the backend (i.e. users can install app but to access services they need to register that device with our backend services and there is a limit of X devices that can be registered simultaneously).

The front end team currently have created a function to extract a unique device ID from the mobile device but we were also told by the security team that device IDs are considered sensitive information and we should not be transmitting this information over the wire.

Putting aside that encryption can be applied to the device ID, I was mulling about alternatives to the device ID altogether. We are using OAuth for authentication and at the end of a valid registration, an OAuth access and refresh token is generated. Since the refresh token is supposed to be long-lived and is stored securely (assumed) client-side, can the refresh token be used as a replacement for the device ID? Would there be any known holes in this strategy? Refresh tokens are supposed to be "long-lived" per the documentation, but how long-lived exactly?

答: You should use SHA256 to hash the Device ID.  OAuth tokens are volatile, even refresh tokens at some point.</p>


问:
parse error on input `if' in catch clause for readFile
I'm trying handling an exception when I read a file but I'm receiving the message

parse error on input `if'

```<code>readTxt = do
            {catch (read_file) fix_error;}
            where
                read_file = do
                {
                    f <- openFile "file.txt" ReadMode;
                    content <- hGetContents f;
                    putStrLn content;
                    hClose f;
                }
                fix_error erro if = isDoesNotExistError erro
                    then do
                    {
                        putStr "Exception: file doesn't exists";
                        writeFile "file.txt" "First Line"
                    }
                else ioError erro
</code>```

I read that when I have an if I need that the then and else clauses return the same type. I believe that I'm doing this, so I don't know why I'm receiving the error message

答:
You swapped = and if in the definition of fix_error.

The syntax for a definition is:

```<code>name args = body
</code>```

The syntax for an if expression is:

```<code>if condition then true_branch else false_branch
</code>```

You simply need to combine these:

```<code>fix_error erro = if isDoesNotExistError erro
               ----
  then do
    putStr "Exception: file doesn't exist"
    ...
  else ioError erro
</code>```

Or use a guard:

```<code>fix_error erro
  | isDoesNotExistError erro = do
    putStr "Exception: file doesn't exist"
    ...
  | otherwise = ioError erro
</code>```

I’ve omitted the curly braces and semicolons, but you can include them if you prefer.

Body:
I'm trying handling an exception when I read a file but I'm receiving the message

parse error on input `if'

readTxt = do
            {catch (read_file) fix_error;}
            where
                read_file = do
                {
                    f <- openFile "file.txt" ReadMode;
                    content <- hGetContents f;
                    putStrLn content;
                    hClose f;
                }
                fix_error erro if = isDoesNotExistError erro
                    then do
                    {
                        putStr "Exception: file doesn't exists";
                        writeFile "file.txt" "First Line"
                    }
                else ioError erro

I read that when I have an if I need that the then and else clauses return the same type. I believe that I'm doing this, so I don't know why I'm receiving the error message

Body:
You swapped = and if in the definition of fix_error.

The syntax for a definition is:

name args = body

The syntax for an if expression is:

if condition then true_branch else false_branch

You simply need to combine these:

fix_error erro = if isDoesNotExistError erro
               ----
  then do
    putStr "Exception: file doesn't exist"
    ...
  else ioError erro

Or use a guard:

fix_error erro
  | isDoesNotExistError erro = do
    putStr "Exception: file doesn't exist"
    ...
  | otherwise = ioError erro

I’ve omitted the curly braces and semicolons, but you can include them if you prefer.


问:
I'm trying to call a row from an HTML table into a JS function
I started last night so i'm a) sure there is an easy solution and b) not oblivious to the fact that my code is very crappy.
So i pulled this Stat table from a website and I already have a function running so that when I type a team name into the website it returns a number. However, what I'm trying to do is have it so that when i type a team name in it won't return a number, but rather it's respective row on the table. The numbers that are currently called in the function are just placeholders for now. As you can see i tried to call a row at the end of the function using an ID I assigned to the Celtics row but what it returns is [object HTMLTableRowElement].
Any help is appreciated, Thanks!!</p>

```<code> <html>
<canvas id = 'gCanvas' width = '400' height = '600'></canvas>
<script>
var groceryItem = "";

window.onload = function() {
    canvas = document.getElementById('gCanvas');
    ctx = canvas.getContext('2d');
    window.addEventListener('keydown', keyPressed, false);
};

function keyPressed(e) {
    if (e.keyCode != '13') {
        var letter = String.fromCharCode(parseInt(e.keyCode));
        groceryItem += letter;
        console.log(groceryItem);
    }

    if (e.keyCode == '13') {
        grocery();
        groceryItem = "";
    }

}

function grocery() {
    ctx.clearRect(0,0,canvas.width, canvas.height);
    drawBackground();
    ctx.fillStyle = 'black';
    ctx.font="40px Arial";

    switch (groceryItem) {
case 'CELTICS':
    ctx.fillText("1", 50, 50);
    break;
  case 'CAVALIERS':
  case 'CAVS':
    ctx.fillText('2', 50, 50);
    break;
  case 'WIZARDS':
    ctx.fillText('3', 50, 50);
    break;
  case 'RAPTORS':
    ctx.fillText('4', 50, 50);
    break;
  case 'HAWKS':
    ctx.fillText('5', 50, 50);
    break;
    case 'BUCKS':
    ctx.fillText('6', 50, 50);
    break;
     case 'PACERS':
    ctx.fillText('7', 50, 50);
    break;
     case 'HEAT':
    ctx.fillText('8', 50, 50);
    break;
     case 'BULLS':
    ctx.fillText('9', 50, 50);
    break;
     case 'PISTONS':
    ctx.fillText('10', 50, 50);
    break;
     case 'HORNETS':
    ctx.fillText('11', 50, 50);
    break;
     case '76ERS':
    ctx.fillText('12', 50, 50);
    break;
     case 'KNICKS':
    ctx.fillText('13', 50, 50);
    break;
     case 'MAGIC':
    ctx.fillText('14', 50, 50);
    break;
     case 'NETS':
    ctx.fillText('15', 50, 50);
    break;
     case 'WARRIORS':
    ctx.fillText('16', 50, 50);
    break;
     case 'SPURS':
    ctx.fillText(index('23'), 100, 100);
    break;
     case 'ROCKETS':
    ctx.fillText('18', 50, 50);
    break;
     case 'JAZZ':
    ctx.fillText('19', 50, 50);
    break;
     case 'CLIPPERS':
    ctx.fillText('20', 50, 50);
    break;
     case 'THUNDER':
    ctx.fillText('21', 50, 50);
    break;
     case 'GRIZZLIES':
    ctx.fillText('22', 50, 50);
    break;
     case 'TRAILBLAZERS':
    ctx.fillText('23', 50, 50);
    break;
     case 'NUGGETS':
    ctx.fillText('24', 50, 50);
    break;
     case 'MAVERICKS':
    ctx.fillText('25', 50, 50);
    break;
     case 'PELICANS':
    ctx.fillText('26', 50, 50);
    break;
     case 'TIMBERWOLVES':
    ctx.fillText('27', 50, 50);
    break;
     case 'KINGS':
    ctx.fillText('28', 50, 50);
    break;
     case 'SUNS':
    ctx.fillText('29', 50, 50);
    break;
     case 'LAKERS':
    ctx.fillText('30', 50, 50);
    break;
  default:
    ctx.fillText('Invalid Team', 50, 50);
    break;

    }
}
function drawBackground() {
    ctx.fillStyle = 'white';
    ctx.fillRect(0,0,canvas.width, canvas.height);

}
</script>

<div class="nba-stat-table">
  <div class="nba-stat-table__overflow" data-fixed="2" role="grid">
      <table class="table">
        <thead>
          <tr>
            <th></th>
            <th sort="" cf="" data-field="TEAM_NAME" class="text sorted desc" ripple=""><br>TEAM</th>
            <th sort="" cf="" data-field="GP" data-rank="" data-dir="-1" ripple="">GP</th>
            <th sort="" cf="" data-field="W" data-rank="" data-dir="-1" ripple="">W</th>
            <th sort="" cf="" data-field="L" data-rank="" data-dir="-1" ripple="">L</th>
            <th sort="" cf="" data-field="W_PCT" data-rank="" data-dir="-1" ripple="" class="asc">WIN%</th>
            <th sort="" cf="" data-field="MIN" data-rank="" data-dir="-1" ripple="">MIN</th>
            <th sort="" cf="" data-field="EFG_PCT" data-rank="" data-dir="-1" ripple="">eFG%</th>
            <th sort="" cf="" data-field="FTA_RATE" data-rank="" data-dir="-1" ripple="">FTA<br>Rate</th>
            <th sort="" cf="" data-field="TM_TOV_PCT" data-rank="" data-dir="-1" ripple="">TOV%</th>
            <th sort="" cf="" data-field="OREB_PCT" data-rank="" data-dir="-1" ripple="">OREB%</th>
            <th sort="" cf="" data-field="OPP_EFG_PCT" data-rank="" data-dir="-1" ripple="">Opp<br>eFG%</th>
            <th sort="" cf="" data-field="OPP_FTA_RATE" data-rank="" data-dir="-1" ripple="">Opp<br>FTA Rate</th>
            <th sort="" cf="" data-field="OPP_TOV_PCT" data-rank="" data-dir="-1" ripple="">Opp<br>TOV%</th>
            <th sort="" cf="" data-field="OPP_OREB_PCT" data-rank="" data-dir="-1" ripple="">Opp<br>OREB%</th>
            <th sort="" cf="" hidden="" data-field="GP_RANK" ripple="">GP RANK</th>
            <th sort="" cf="" hidden="" data-field="W_RANK" ripple="">W RANK</th>
            <th sort="" cf="" hidden="" data-field="L_RANK" ripple="">L RANK</th>
            <th sort="" cf="" hidden="" data-field="W_PCT_RANK" ripple="">WIN% RANK</th>
            <th sort="" cf="" hidden="" data-field="MIN_RANK" ripple="">MIN RANK</th>
            <th sort="" cf="" hidden="" data-field="EFG_PCT_RANK" ripple="">eFG% RANK</th>
            <th sort="" cf="" hidden="" data-field="FTA_RATE_RANK" ripple="">FTA<br>Rate RANK</th>
            <th sort="" cf="" hidden="" data-field="TM_TOV_PCT_RANK" ripple="">TO<br>Ratio RANK</th>
            <th sort="" cf="" hidden="" data-field="OREB_PCT_RANK" ripple="">OREB% RANK</th>
            <th sort="" cf="" hidden="" data-field="OPP_EFG_PCT_RANK" ripple="">Opp<br>eFG% RANK</th>
            <th sort="" cf="" hidden="" data-field="OPP_FTA_RATE_RANK" ripple="">Opp<br>FTA Rate RANK</th>
            <th sort="" cf="" hidden="" data-field="OPP_TOV_PCT_RANK" ripple="">Opp<br>To Ratio RANK</th>
            <th sort="" cf="" hidden="" data-field="OPP_OREB_PCT_RANK" ripple="">Opp<br>OREB% RANK</th>
          </tr>
        </thead>
        <tbody>
          <!-- ngRepeat: (i, row) in page track by row.$hash --><tr data-ng-repeat="(i, row) in page track by row.$hash" index="5" class="ng-scope">
            <td class="rank ng-binding"></td>
            <td class="team-name first sorted"><a href="/team/#!/1610612764/traditional/?" class="ng-binding">Washington Wizards</a></td>
            <td class="ng-binding">74</td>
            <td class="ng-binding">46</td>
            <td class="ng-binding">28</td>
            <td class="ng-binding">.622</td>
            <td class="ng-binding">3,587</td>
            <td class="ng-binding">52.7</td>
            <td class="ng-binding">0.255</td>
            <td class="ng-binding">14.0</td>
            <td class="ng-binding">24.0</td>
            <td class="ng-binding">52.1</td>
            <td class="ng-binding">0.284</td>
            <td class="ng-binding">15.4</td>
            <td class="ng-binding">24.5</td>
                  </tr><!-- end ngRepeat: (i, row) in page track by row.$hash --><tr data-ng-repeat="(i, row) in page track by row.$hash" index="3" class="ng-scope" id=1>
            <td class="rank ng-binding"></td>
            <td class="team-name first sorted"><a href="/team/#!/1610612738/traditional/?" class="ng-binding">Boston Celtics</a></td>
            <td class="ng-binding">74</td>
            <td class="ng-binding">48</td>
            <td class="ng-binding">26</td>
            <td class="ng-binding">.649</td>
            <td class="ng-binding">3,567</td>
            <td class="ng-binding">52.4</td>
            <td class="ng-binding">0.269</td>
            <td class="ng-binding">13.4</td>
            <td class="ng-binding">21.3</td>
            <td class="ng-binding">50.4</td>
            <td class="ng-binding">0.289</td>
            <td class="ng-binding">14.1</td>
            <td class="ng-binding">25.0</td>
          </tr><!-- end ngRepeat: (i, row) in page track by row.$hash --><tr data-ng-repeat="(i, row) in page track by row.$hash" index="12" class="ng-scope">
            <td class="rank ng-binding"></td>
            <td class="team-name first sorted"><a href="/team/#!/1610612737/traditional/?" class="ng-binding">Atlanta Hawks</a></td>
            <td class="ng-binding">74</td>
            <td class="ng-binding">38</td>
            <td class="ng-binding">36</td>
            <td class="ng-binding">.514</td>
            <td class="ng-binding">3,587</td>
            <td class="ng-binding">50.3</td>
            <td class="ng-binding">0.297</td>
            <td class="ng-binding">15.6</td>
            <td class="ng-binding">23.6</td>
            <td class="ng-binding">50.8</td>
            <td class="ng-binding">0.233</td>
            <td class="ng-binding">15.3</td>
            <td class="ng-binding">24.1</td>
          </tr><!-- end ngRepeat: (i, row) in page track by row.$hash -->
        </tbody>
      </table>
  </div> <!-- .stat-table__overflow -->
</div>
<script>
document.getElementById('1')
document.write(document.getElementById('1'))
</script>
</html>
</code>```

答:
Your best bet is

generate a unique id for each row

use an expression like document.querySelector(…) to fetch the row by its id

read the results from the fetched row

You can read the content of a row by iterating through the data cells.

The function document.querySelectorAll() will return a collection of elements which match a CSS-type pattern. We can then use a for loop to get the cell contents. I have used textContent, but if you need to support Legacy Browsers, you might use innerHTML.

```<code>var row=document.querySelectorAll('tr#id-1>td');
var data=[];
for(var i=0;i<row.length;i++) data.push(row[i].textContent);
</code>```

The data array will now have your content, and you can process that as you like.

Body:
I started last night so i'm a) sure there is an easy solution and b) not oblivious to the fact that my code is very crappy.
So i pulled this Stat table from a website and I already have a function running so that when I type a team name into the website it returns a number. However, what I'm trying to do is have it so that when i type a team name in it won't return a number, but rather it's respective row on the table. The numbers that are currently called in the function are just placeholders for now. As you can see i tried to call a row at the end of the function using an ID I assigned to the Celtics row but what it returns is [object HTMLTableRowElement].
Any help is appreciated, Thanks!!

<canvas id = 'gCanvas' width = '400' height = '600'></canvas>

TEAM
            GP
            W
            L
            WIN%
            MIN
            eFG%
            FTA
Rate
            TOV%
            OREB%
            Opp
eFG%
            Opp
FTA Rate
            Opp
TOV%
            Opp
OREB%
            GP RANK
            W RANK
            L RANK
            WIN% RANK
            MIN RANK
            eFG% RANK
            FTA
Rate RANK
            TO
Ratio RANK
            OREB% RANK
            Opp
eFG% RANK
            Opp
FTA Rate RANK
            Opp
To Ratio RANK
            Opp
OREB% RANK

            Washington Wizards
            74
            46
            28
            .622
            3,587
            52.7
            0.255
            14.0
            24.0
            52.1
            0.284
            15.4
            24.5

            Boston Celtics
            74
            48
            26
            .649
            3,567
            52.4
            0.269
            13.4
            21.3
            50.4
            0.289
            14.1
            25.0

            Atlanta Hawks
            74
            38
            36
            .514
            3,587
            50.3
            0.297
            15.6
            23.6
            50.8
            0.233
            15.3
            24.1

Body:
Your best bet is

generate a unique id for each row

use an expression like document.querySelector(…) to fetch the row by its id

read the results from the fetched row

You can read the content of a row by iterating through the data cells.

The function document.querySelectorAll() will return a collection of elements which match a CSS-type pattern. We can then use a for loop to get the cell contents. I have used textContent, but if you need to support Legacy Browsers, you might use innerHTML.

var row=document.querySelectorAll('tr#id-1>td');
var data=[];
for(var i=0;i<row.length;i++) data.push(row[i].textContent);

The data array will now have your content, and you can process that as you like.


问:
Linq query not returning records
```<code>public tblCustomerDetail GetCustomerDetailsByID(long ID)
        {
            var customer = from c in DataContext.GetTable<tblCustomerDetail>() where c.ID == ID select c;
            return customer as tblCustomerDetail;
        }
</code>```

DataContext.GetTable() has records in it and after filtering based on ID, there are no records in customer variable, although the record with the ID for which I am searching exists in the returned table.

Please help. I am new to LINQ.

答:
Your variable customer will be of type IEnumerable<tblCustomerDetail> so when you cast it with the as operator, the result will be null because the types are incompatible.

Try this instead:

```<code>public tblCustomerDetail GetCustomerDetailsByID(long ID)
{
    var customer = from c in DataContext.GetTable<tblCustomerDetail>() where c.ID == ID select c;
    return customer.First();
}
</code>```

Title: Linq query not returning records

Body:
public tblCustomerDetail GetCustomerDetailsByID(long ID)
        {
            var customer = from c in DataContext.GetTable<tblCustomerDetail>() where c.ID == ID select c;
            return customer as tblCustomerDetail;
        }

DataContext.GetTable() has records in it and after filtering based on ID, there are no records in customer variable, although the record with the ID for which I am searching exists in the returned table.

Please help. I am new to LINQ.

Body:
Your variable customer will be of type IEnumerable<tblCustomerDetail> so when you cast it with the as operator, the result will be null because the types are incompatible.

Try this instead:

public tblCustomerDetail GetCustomerDetailsByID(long ID)
{
    var customer = from c in DataContext.GetTable<tblCustomerDetail>() where c.ID == ID select c;
    return customer.First();
}


问:
:valid css shows even when $valid: false
so here is my code, I use a custom directive to determine if the two passwords match, here is my html

```<code><!-- confirm password -->
    <div class="row">
        <div class="col-xs-10 col-centered">
            <div class="col-md-5 col-xs-12 inputLabels">
                <b>Confirm Password:</b>
            </div>

            <div class="col-md-5 col-xs-12">
                <input type="password" name="confirmPassword" ng-model="boardingData.confirmPassword" class="form-control" required compare-to="boardingData.password">
            </div>
        </div>
    </div>
</code>```

and the directive to determine if the passwords match

```<code>app.directive('compareTo', function() {
return {
    require: "ngModel",
    scope: {
        otherModelValue: "=compareTo"
    },
    link: function(scope, element, attributes, ngModel) {

        ngModel.$validators.compareTo = function(modelValue) {
            return modelValue == scope.otherModelValue;
        };

        scope.$watch("otherModelValue", function() {
            ngModel.$validate();
        });
    }
};
</code>```

});

finally the css

```<code>input:valid {box-shadow: 0 0 3px rgb(97, 240, 59);}
</code>```

答:
The reason is because :valid is a pseudo-class specific to if the content of an input matches the [type] attribute.  As you can see on https://developer.mozilla.org/en-US/docs/Web/CSS/:valid .  What you are instead wanting is the class ng-valid as seen here https://docs.angularjs.org/api/ng/directive/form .

Let me know if you need any further help.

Body:
so here is my code, I use a custom directive to determine if the two passwords match, here is my html

                Confirm Password:

                <input type="password" name="confirmPassword" ng-model="boardingData.confirmPassword" class="form-control" required compare-to="boardingData.password">

and the directive to determine if the passwords match

app.directive('compareTo', function() {
return {
    require: "ngModel",
    scope: {
        otherModelValue: "=compareTo"
    },
    link: function(scope, element, attributes, ngModel) {

        ngModel.$validators.compareTo = function(modelValue) {
            return modelValue == scope.otherModelValue;
        };

        scope.$watch("otherModelValue", function() {
            ngModel.$validate();
        });
    }
};

});

finally the css

input:valid {box-shadow: 0 0 3px rgb(97, 240, 59);}


问:
Use of properties in java
I'm new here and i would like to ask on how properties can work with the java codes i mean the values inside of the properties will be use as variables. For example i have file1.txt and file2.txt inside  config.properties and store it in an Arraylist then scan the folder and if the files are found copy it. My work only shows the names of the data from the properties that is stored in the arraylist but my another problem is how these data will be copied to another folder.

so far this is my code

```<code>     public class MainClass {

          static Properties prop = new Properties();
    static InputStream input = null;
    static String filename = "";

    public static void main(String[] args) throws IOException {

        File source = new File("D:/ojt");
        File dest = new File("D:/ojt/New folder");

        Properties prop = new Properties();
        InputStream input = null;

        try {

    //    getFiles(filename);

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
       private static void copyFileUsingStream(File source, File dest) throws IOException {
            InputStream is = null;
            OutputStream os = null;

            try {
                is = new FileInputStream(source);
                os = new FileOutputStream(dest);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
            } finally {
                is.close();
                os.close();
            }
        }
       private static void copy(String fromPath, String outputPath)
       {
    //       filter = new FileTypeOrFolderFilter(fileType);
           File currentFolder = new File(fromPath);
           File outputFolder = new File(outputPath);
           scanFolder(currentFolder, outputFolder);

       }

      private static void getFiles(String path) throws IOException{
        //Put filenames in arraylist<string>
        String filename = "bydatefilesdir.props";
        input = MainClass.class.getClassLoader().getResourceAsStream(filename);
        Scanner s = new Scanner(input);
        File dir = new File(path);
        final ArrayList<String> list = new ArrayList<String>();
        while (s.hasNextLine()){
            list.add(s.nextLine());
        }
//      ArrayList<String> filenames = new ArrayList<String>();
//      for(File file : dir.listFiles()){
//          filenames.add(file.getName());
//      }

        prop.load(input);
        //Check if the files are in the arraylist
        for (int i = 0; i < list.size(); i++){
            String s1 = list.get(i);
            System.out.println("File "+i+" : "+s1);
        }
        System.out.println("\n");
    }

    private static void copyFileUsingStream(File source, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;

        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }
    private static void copy(String source, String dest)
    {
        //       filter = new FileTypeOrFolderFilter(fileType);
        File currentFolder = new File(source);
        File outputFolder = new File(dest);
        scanFolder(currentFolder, outputFolder);

    }

    private static void scanFolder(File source, File dest)
    {
        System.out.println("Scanning folder [" + source.toString() + "]...\n");
        File[] files = source.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                scanFolder(source, dest);
            } else {
                try {
                    copyFileUsingStream(source, dest);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
</code>```

PS: sorry for the poor programming just new in java.. still learning

Edited: I've included the updated codes above..

答:
I suppose java.util.Properties has build in methods to achieve what you are trying.
please refer this example and you will find a better solution.</p>

```<code>public class App {

  public static void main( String[] args ){

    Properties prop = new Properties();
    InputStream input = null;

    try {

        String filename = "config.properties";
        input = App.class.getClassLoader().getResourceAsStream(filename);
        if(input==null){
                System.out.println("Sorry, unable to find " + filename);
            return;
        }

        //load a properties file from class path, inside static method
        prop.load(input);

            //get the property value and print it out
            System.out.println(prop.getProperty("file1.txt"));
            System.out.println(prop.getProperty("file2.txt"));

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally{
        if(input!=null){
            try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
    }

}
}
</code>```

Title: Use of properties in java

Body:
I'm new here and i would like to ask on how properties can work with the java codes i mean the values inside of the properties will be use as variables. For example i have file1.txt and file2.txt inside  config.properties and store it in an Arraylist then scan the folder and if the files are found copy it. My work only shows the names of the data from the properties that is stored in the arraylist but my another problem is how these data will be copied to another folder.

so far this is my code

     public class MainClass {

          static Properties prop = new Properties();
    static InputStream input = null;
    static String filename = "";

    public static void main(String[] args) throws IOException {

        File source = new File("D:/ojt");
        File dest = new File("D:/ojt/New folder");

        Properties prop = new Properties();
        InputStream input = null;

        try {

    //    getFiles(filename);

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
       private static void copyFileUsingStream(File source, File dest) throws IOException {
            InputStream is = null;
            OutputStream os = null;

            try {
                is = new FileInputStream(source);
                os = new FileOutputStream(dest);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
            } finally {
                is.close();
                os.close();
            }
        }
       private static void copy(String fromPath, String outputPath)
       {
    //       filter = new FileTypeOrFolderFilter(fileType);
           File currentFolder = new File(fromPath);
           File outputFolder = new File(outputPath);
           scanFolder(currentFolder, outputFolder);

       }

      private static void getFiles(String path) throws IOException{
        //Put filenames in arraylist<string>
        String filename = "bydatefilesdir.props";
        input = MainClass.class.getClassLoader().getResourceAsStream(filename);
        Scanner s = new Scanner(input);
        File dir = new File(path);
        final ArrayList<String> list = new ArrayList<String>();
        while (s.hasNextLine()){
            list.add(s.nextLine());
        }
//      ArrayList<String> filenames = new ArrayList<String>();
//      for(File file : dir.listFiles()){
//          filenames.add(file.getName());
//      }

        prop.load(input);
        //Check if the files are in the arraylist
        for (int i = 0; i < list.size(); i++){
            String s1 = list.get(i);
            System.out.println("File "+i+" : "+s1);
        }
        System.out.println("\n");
    }

    private static void copyFileUsingStream(File source, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;

        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }
    private static void copy(String source, String dest)
    {
        //       filter = new FileTypeOrFolderFilter(fileType);
        File currentFolder = new File(source);
        File outputFolder = new File(dest);
        scanFolder(currentFolder, outputFolder);

    }

    private static void scanFolder(File source, File dest)
    {
        System.out.println("Scanning folder [" + source.toString() + "]...\n");
        File[] files = source.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                scanFolder(source, dest);
            } else {
                try {
                    copyFileUsingStream(source, dest);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

PS: sorry for the poor programming just new in java.. still learning

Edited: I've included the updated codes above..

Body:
I suppose java.util.Properties has build in methods to achieve what you are trying.
please refer this example and you will find a better solution.

public class App {

  public static void main( String[] args ){

    Properties prop = new Properties();
    InputStream input = null;

    try {

        String filename = "config.properties";
        input = App.class.getClassLoader().getResourceAsStream(filename);
        if(input==null){
                System.out.println("Sorry, unable to find " + filename);
            return;
        }

        //load a properties file from class path, inside static method
        prop.load(input);

            //get the property value and print it out
            System.out.println(prop.getProperty("file1.txt"));
            System.out.println(prop.getProperty("file2.txt"));

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally{
        if(input!=null){
            try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
    }

}
}


问:
Making a dictionary from a list
I want to write a function that imports ascii_lowercase and returns a dictionary with the letters of keys as keys and a randomly shuffled version of the keys as values.

for example,

```<code>keys = "abcdefg..."
</code>```

and then you shuffle it and get gydwsk... as an example, and the dictionary should look like

```<code>{'a':'g', 'b':'y', 'c':'d'...}
</code>```

Im not sure where to begin, any help is appreciated.

答:
You need to shuffle it with random.shuffle. Here is an example:

```<code>import random

keys = 'abcdefghijklmnopqrdtuvxz'
shuffle_keys = list_keys = list(keys)

random.shuffle(shuffle_keys)

my_dict = dict(zip(keys, shuffle_keys))

print(my_dict)
</code>```

Edited

Good suggestion for simpler dict construction (from comments. Thanks)

Title: Making a dictionary from a list

Body:
I want to write a function that imports ascii_lowercase and returns a dictionary with the letters of keys as keys and a randomly shuffled version of the keys as values.

for example,

keys = "abcdefg..."

and then you shuffle it and get gydwsk... as an example, and the dictionary should look like

{'a':'g', 'b':'y', 'c':'d'...}

Im not sure where to begin, any help is appreciated.

Body:
You need to shuffle it with random.shuffle. Here is an example:

import random

keys = 'abcdefghijklmnopqrdtuvxz'
shuffle_keys = list_keys = list(keys)

random.shuffle(shuffle_keys)

my_dict = dict(zip(keys, shuffle_keys))

print(my_dict)

Edited

Good suggestion for simpler dict construction (from comments. Thanks)


问:
Getting key by value in LinkedHashMap using Java
I have a big LinkedHashMap<Integer,<List<String>>

.

For example:

```<code><86, ["abc","def","xyz"]>
<32, ["ugy","oop","bbb"]>
<..., ...........]>
</code>```

What i want is when user type a Comma separated String(e.g "abc,oop,bbb"), i want to print out the key. In these case keys are 86,32,32. I can handle separete the String into an array by using .split(" "); but i don't know what is simplest way to search these Strings ?

答:
I would use a map of integers to sets, not lists, since using a set would make checking against the user input without regard to order relatively easy.  Doing the same check for a list would be harder.</p>

```<code>public Integer getKey(Map<Integer, Set<String>> map, String input) {
    String[] parts = input.split(",");
    for (Map.Entry<Integer, Set<String>> entry : map.entrySet()) {
        Integer key = entry.getKey();
        Set<String> value = entry.getValue();
        if (value.size() != parts.length) {
            continue;
        }
        int counter = 0;
        for (String part : parts) {
            if (value.contains(part)) {
                ++counter;
            }
            else {
                break;
            }
        }
        if (counter == value.size()) {
            return key;
        }
    }

    return null;
}
</code>```

Body:
I have a big LinkedHashMap<Integer,<List<String>>

.

For example:

<86, ["abc","def","xyz"]>
<32, ["ugy","oop","bbb"]>
<..., ...........]>

What i want is when user type a Comma separated String(e.g "abc,oop,bbb"), i want to print out the key. In these case keys are 86,32,32. I can handle separete the String into an array by using .split(" "); but i don't know what is simplest way to search these Strings ?

Body:
I would use a map of integers to sets, not lists, since using a set would make checking against the user input without regard to order relatively easy.  Doing the same check for a list would be harder.

public Integer getKey(Map<Integer, Set<String>> map, String input) {
    String[] parts = input.split(",");
    for (Map.Entry<Integer, Set<String>> entry : map.entrySet()) {
        Integer key = entry.getKey();
        Set<String> value = entry.getValue();
        if (value.size() != parts.length) {
            continue;
        }
        int counter = 0;
        for (String part : parts) {
            if (value.contains(part)) {
                ++counter;
            }
            else {
                break;
            }
        }
        if (counter == value.size()) {
            return key;
        }
    }

    return null;
}


问:
Create column of truth values
I have a data frame which looks like this:

```<code>    date      people_count
0   30/03/17  6

1   31/03/17  4

2   1/04/17   7

3   2/04/17   9
</code>```

How can you create a new column which indicates if the date is a weekend(1), or if the date is a weekday(0)?

Something like this:

```<code>    date      people_count   weekend
0   30/03/17  6              0

1   31/03/17  4              0

2   1/04/17   7              1

3   2/04/17   9              1
</code>```

So far I have created a column which stores the day number(0-6), from DateTimeIndex.dayofweek:

```<code>df = pd.read_csv('myfile.csv', encoding = 'ISO-8859-1')

df['weekend'] = pd.DatetimeIndex(df['date']).dayofweek
</code>```

But I am unsure of how to evaluate these values and replace them with 1 for weekends, and 0 for weekdays. How can I do this?

答:
Weekends are days 5 (Saturday) and 6 (Sunday). So just check what day it's returning.</p>

```<code>df['weekend'] = [ 1 if day in (5, 6) else 0 for day in pd.DatetimeIndex(df['date']).dayofweek ]
</code>```

Title: Create column of truth values

Body:
I have a data frame which looks like this:

    date      people_count
0   30/03/17  6

1   31/03/17  4

2   1/04/17   7

3   2/04/17   9

How can you create a new column which indicates if the date is a weekend(1), or if the date is a weekday(0)?

Something like this:

    date      people_count   weekend
0   30/03/17  6              0

1   31/03/17  4              0

2   1/04/17   7              1

3   2/04/17   9              1

So far I have created a column which stores the day number(0-6), from DateTimeIndex.dayofweek:

df = pd.read_csv('myfile.csv', encoding = 'ISO-8859-1')

df['weekend'] = pd.DatetimeIndex(df['date']).dayofweek

But I am unsure of how to evaluate these values and replace them with 1 for weekends, and 0 for weekdays. How can I do this?

Body:
Weekends are days 5 (Saturday) and 6 (Sunday). So just check what day it's returning.

df['weekend'] = [ 1 if day in (5, 6) else 0 for day in pd.DatetimeIndex(df['date']).dayofweek ]


问:
Split tmux.conf into multiple files?
I have a file of common tmux settings I share between computers (tmux.conf.common). I'd like to be able to source this file in my tmux.conf. A way to accomplish this in bash is to have the each computer's .bashrc source the common file. Is there a way to do something analogous in tmux?</p>

答:
The .tmux.conf format has the source-file directive which can be used the same way. Using source also works.

```<code>source-file /path/to/tmux.conf.common
</code>```

Title: Split tmux.conf into multiple files?

Body:
The .tmux.conf format has the source-file directive which can be used the same way. Using source also works.

source-file /path/to/tmux.conf.common


问:
Error when using pandas dataframe map function in ipython notebook
I'm just starting out with Python and getting stuck on something while playing with the Kaggle Titanic data.
https://www.kaggle.com/c/titanic/data

Here's what I am typing in an ipython notebook (train.csv comes from the titanic data from the kaggle link above):

```<code>import pandas as pd
df = pd.read_csv("C:/fakepath/titanic/data/train.csv")
</code>```

I then continue with this to check if there's any bad data in the 'Sex' column:

```<code>df['Sex'].value_counts()
</code>```

Which returns:

```<code>male      577

female    314

dtype: int64
</code>```

```<code>df['Gender'] = df['Sex'].map( {'male': 1, 'female': 0} ).astype(int)
</code>```

this doesn't produce any errors. To verify that it created a new column called 'Gender' with integer values :

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

which returns:

```<code>#    PassengerId    Survived    Pclass  Name    Sex Age SibSp   Parch   Ticket  Fare    Cabin   Embarked    Gender
    0   1   0   3   Braund, Mr. Owen Harris male    22  1   0   A/5 21171   7.2500  NaN S   1
    1   2   1   1   Cumings, Mrs. John Bradley (Florence Briggs Th...   female  38  1   0   PC 17599    71.2833 C85 C   0
    2   3   1   3   Heikkinen, Miss. Laina  female  26  0   0   STON/O2. 3101282    7.9250  NaN S   0
    3   4   1   1   Futrelle, Mrs. Jacques Heath (Lily May Peel)    female  35  1   0   113803  53.1000 C123    S   0
</code>```

...success, the Gender column is appended to the end and is 0 for female, 1 for male. Now, I create a new pandas dataframe which is a subset of the df dataframe.

```<code>df2 = df[ ['Survived', 'Pclass', 'Age', 'Gender', 'Embarked'] ]
df2
</code>```

which returns:

```<code>    Survived    Pclass  Age Gender  Embarked
0   0   3   22  1   S
1   1   1   38  0   C
2   1   3   26  0   S
3   1   1   35  0   S
4   0   3   35  1   S
5   0   3   NaN 1   Q
</code>```

```<code>df2['Embarked'].value_counts()
</code>```

...shows that there are 3 unique values (S, C, Q):

```<code>S    644
C    168
Q     77
dtype: int64
</code>```

However, when I try to execute what I think is the same type of operation as when I converted male/female to 1/0, I get an error:

```<code>df['Sex'].value_counts()
</code>```0

returns:

```<code>df['Sex'].value_counts()
</code>```1

Any idea why I get this error on the 2nd use of the map function but not the first? There are no NAN values in the Embarked column per value_counts(). I'm guessing it's a noob problem :)

答: I just came across this problem on the same dataset.  Removing 'astype.int' solved the whole problem. </p>

Body:
I'm just starting out with Python and getting stuck on something while playing with the Kaggle Titanic data.
https://www.kaggle.com/c/titanic/data

Here's what I am typing in an ipython notebook (train.csv comes from the titanic data from the kaggle link above):

import pandas as pd
df = pd.read_csv("C:/fakepath/titanic/data/train.csv")

I then continue with this to check if there's any bad data in the 'Sex' column:

df['Sex'].value_counts()

Which returns:

male      577

female    314

dtype: int64

df['Gender'] = df['Sex'].map( {'male': 1, 'female': 0} ).astype(int)

this doesn't produce any errors. To verify that it created a new column called 'Gender' with integer values :

df

which returns:

#    PassengerId    Survived    Pclass  Name    Sex Age SibSp   Parch   Ticket  Fare    Cabin   Embarked    Gender
    0   1   0   3   Braund, Mr. Owen Harris male    22  1   0   A/5 21171   7.2500  NaN S   1
    1   2   1   1   Cumings, Mrs. John Bradley (Florence Briggs Th...   female  38  1   0   PC 17599    71.2833 C85 C   0
    2   3   1   3   Heikkinen, Miss. Laina  female  26  0   0   STON/O2. 3101282    7.9250  NaN S   0
    3   4   1   1   Futrelle, Mrs. Jacques Heath (Lily May Peel)    female  35  1   0   113803  53.1000 C123    S   0

...success, the Gender column is appended to the end and is 0 for female, 1 for male. Now, I create a new pandas dataframe which is a subset of the df dataframe.

df2 = df[ ['Survived', 'Pclass', 'Age', 'Gender', 'Embarked'] ]
df2

which returns:

    Survived    Pclass  Age Gender  Embarked
0   0   3   22  1   S
1   1   1   38  0   C
2   1   3   26  0   S
3   1   1   35  0   S
4   0   3   35  1   S
5   0   3   NaN 1   Q

df2['Embarked'].value_counts()

...shows that there are 3 unique values (S, C, Q):

S    644
C    168
Q     77
dtype: int64

However, when I try to execute what I think is the same type of operation as when I converted male/female to 1/0, I get an error:

df2['Embarked_int'] = df2['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2}).astype(int)

returns:

    ValueError                                Traceback (most recent call last)
<ipython-input-29-294c08f2fc80> in <module>()
----> 1 df2['Embarked_int'] = df2['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2}).astype(int)

C:\Anaconda\lib\site-packages\pandas\core\generic.pyc in astype(self, dtype, copy, raise_on_error)
   2212
   2213         mgr = self._data.astype(
-> 2214             dtype=dtype, copy=copy, raise_on_error=raise_on_error)
   2215         return self._constructor(mgr).__finalize__(self)
   2216

C:\Anaconda\lib\site-packages\pandas\core\internals.pyc in astype(self, dtype, **kwargs)
   2500
   2501     def astype(self, dtype, **kwargs):
-> 2502         return self.apply('astype', dtype=dtype, **kwargs)
   2503
   2504     def convert(self, **kwargs):

C:\Anaconda\lib\site-packages\pandas\core\internals.pyc in apply(self, f, axes, filter, do_integrity_check, **kwargs)
   2455                                                  copy=align_copy)
   2456
-> 2457             applied = getattr(b, f)(**kwargs)
   2458
   2459             if isinstance(applied, list):

C:\Anaconda\lib\site-packages\pandas\core\internals.pyc in astype(self, dtype, copy, raise_on_error, values)
    369     def astype(self, dtype, copy=False, raise_on_error=True, values=None):
    370         return self._astype(dtype, copy=copy, raise_on_error=raise_on_error,
--> 371                             values=values)
    372
    373     def _astype(self, dtype, copy=False, raise_on_error=True, values=None,

C:\Anaconda\lib\site-packages\pandas\core\internals.pyc in _astype(self, dtype, copy, raise_on_error, values, klass)
    399             if values is None:
    400                 # _astype_nansafe works fine with 1-d only
--> 401                 values = com._astype_nansafe(self.values.ravel(), dtype, copy=True)
    402                 values = values.reshape(self.values.shape)
    403             newb = make_block(values,

C:\Anaconda\lib\site-packages\pandas\core\common.pyc in _astype_nansafe(arr, dtype, copy)
   2616
   2617         if np.isnan(arr).any():
-> 2618             raise ValueError('Cannot convert NA to integer')
   2619     elif arr.dtype == np.object_ and np.issubdtype(dtype.type, np.integer):
   2620         # work around NumPy brokenness, #1987

ValueError: Cannot convert NA to integer

Any idea why I get this error on the 2nd use of the map function but not the first? There are no NAN values in the Embarked column per value_counts(). I'm guessing it's a noob problem :)


问:
Detached HEAD Issue in Android Studio
I am new to Android Studio and have began developing a Navigation Drawer app.

After having made a mistake in a commit, I played around with the Version control's "Checkout Revision" and now I can no longer push my project onto Github due to a "Detached HEAD".

How can I fix this problem? My app runs perfectly fine in the emulator.

Thanks

答:
To get rid from Detached Head you need to know why this problem is arrived. Its Showing Detached Head because you merge your project several times(or atlas twice) by just committing your project locally. What you need to do is that by every time you merge your project just commit it locally as well as to server branch too.
This will resolve your problem as it does mine.

Title: Detached HEAD Issue in Android Studio


问:
makecython++ causes fatal error: Python.h: No such file or directory despite python3-dev installed
My makefile:

```<code>SHELL := /bin/bash

.PHONY: all
all:
    pip install runcython
    makecython++ stitch_wrapper.pyx "" "stitch_rects.cpp ./hungarian/hungarian.cpp"

hungarian: hungarian/hungarian.so

hungarian/hungarian.so:
    cd hungarian && \
    TF_INC=$$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())') && \
    if [ `uname` == Darwin ];\
    then g++ -std=c++11 -shared hungarian.cc -o hungarian.so -fPIC -I $$TF_INC -undefined dynamic_lookup;\
    else g++ -std=c++11 -shared hungarian.cc -o hungarian.so -fPIC -I  $$TF_INC; fi
</code>```

I have already installed

```<code>-cython
-runcython
-python-dev
-python3-dev
-cffi
</code>```

Unfortunately I continue to get the error:

```<code>pkg-config: command not found
.cpp:4:20: fatal error: Python.h: No such file or directory
compilation terminated.
Makefile:5: recipe for target 'all' failed
make: *** [all] Error 1
</code>```

答:
If you already have

```<code>sudo apt-get install python-dev
sudo apt-get install python3-dev
sudo apt-get install libpython3-dev
sudo apt-get install libpython3.4-dev
sudo apt-get install libpython3.5-dev
</code>```

the problem may be related to missing of one of these packages:

```<code>sudo apt-get install Cython
sudo apt-get install pkgconf
sudo apt-get install libpkgconf
sudo apt-get install python-pkgconfig
sudo apt-get install python3-pkgconfig
</code>```

Body:
My makefile:

SHELL := /bin/bash

.PHONY: all
all:
    pip install runcython
    makecython++ stitch_wrapper.pyx "" "stitch_rects.cpp ./hungarian/hungarian.cpp"

hungarian: hungarian/hungarian.so

hungarian/hungarian.so:
    cd hungarian && \
    TF_INC=$$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())') && \
    if [ `uname` == Darwin ];\
    then g++ -std=c++11 -shared hungarian.cc -o hungarian.so -fPIC -I $$TF_INC -undefined dynamic_lookup;\
    else g++ -std=c++11 -shared hungarian.cc -o hungarian.so -fPIC -I  $$TF_INC; fi

I have already installed

-cython
-runcython
-python-dev
-python3-dev
-cffi

Unfortunately I continue to get the error:

pkg-config: command not found
.cpp:4:20: fatal error: Python.h: No such file or directory
compilation terminated.
Makefile:5: recipe for target 'all' failed
make: *** [all] Error 1

Body:
If you already have

sudo apt-get install python-dev
sudo apt-get install python3-dev
sudo apt-get install libpython3-dev
sudo apt-get install libpython3.4-dev
sudo apt-get install libpython3.5-dev

the problem may be related to missing of one of these packages:

sudo apt-get install Cython
sudo apt-get install pkgconf
sudo apt-get install libpkgconf
sudo apt-get install python-pkgconfig
sudo apt-get install python3-pkgconfig


问:
Detect trigger for closeEvent in PyQt
I have a PyQt GUI which has multiple ways of being closed. Two such ways are if they X out of the window, or if they complete a certain task. My class, which extends from QMainWindow, implements the closeEvent method.

In the case when the use X's out of the window, I want to ask them if they're sure they want to quit, then do some cleanup and close if they say yes.

In the case where they complete the certain task, I just want to do the cleanup and quit.

Right now my closeEvent looks like this:

```<code>def closeEvent(self, event):
    # Ask the user if they actually want to quit using custom message box
    msg = MessageBox(self, 'Are you sure you want to quit?', title = 'Quit', buttons = QMessageBox.Yes|QMessageBox.No)
    if msg.reply == QMessageBox.Yes:
        #
        # Do some cleanup here
        #
        super().close()
    else:
        event.ignore()
</code>```

With this certain setup, it always asks if they are sure they want to close, which is necessary for when they X out of the window. When they've completed the specific task, I know they want to close and just want to jump to the cleanup and closing process, without asking this question.

My idea would be that in some close cases, I direct them to a separate function which does it's necessary tasks, then calls the close method. But the problem here is, I don't know how to direct the X out process to a different method before calling the close method. As it is right now, it always asks if they're sure they want to quit because this is needed as part of the X out closing method.

Is there any way to do what I'm trying to do?

答:
A method of solution is to close your application without running closeEvent, for this you can use the function qApp.quit().

For example in the following script can be closed by two methods: the first is a new button called btn, and the second the button X. For the first case we connect it to a slot that calls a dialog, if that is accepted I close the Application with qApp.quit, the second case is similar to the one you implement.

```<code>from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import sys

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent=parent)
        btn = QPushButton("close")
        self.setCentralWidget(btn)
        btn.clicked.connect(self.closeByButton)

    def closeByButton(self):
        msgBox = QMessageBox()
        msgBox.setText("new Method")
        msgBox.setStandardButtons(QMessageBox.Cancel | QMessageBox.Yes | QMessageBox.No);
        msgBox.setDefaultButton(QMessageBox.Yes);
        if msgBox.exec_() == QMessageBox.Yes:
            qApp.quit()

    def closeEvent(self, event):
        msgBox = QMessageBox()
        msgBox.setText("Button X Method")
        msgBox.setStandardButtons(QMessageBox.Cancel | QMessageBox.Yes | QMessageBox.No);
        msgBox.setDefaultButton(QMessageBox.Yes);
        if msgBox.exec_() == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
</code>```

Title: Detect trigger for closeEvent in PyQt

Body:
I have a PyQt GUI which has multiple ways of being closed. Two such ways are if they X out of the window, or if they complete a certain task. My class, which extends from QMainWindow, implements the closeEvent method.

In the case when the use X's out of the window, I want to ask them if they're sure they want to quit, then do some cleanup and close if they say yes.

In the case where they complete the certain task, I just want to do the cleanup and quit.

Right now my closeEvent looks like this:

def closeEvent(self, event):
    # Ask the user if they actually want to quit using custom message box
    msg = MessageBox(self, 'Are you sure you want to quit?', title = 'Quit', buttons = QMessageBox.Yes|QMessageBox.No)
    if msg.reply == QMessageBox.Yes:
        #
        # Do some cleanup here
        #
        super().close()
    else:
        event.ignore()

With this certain setup, it always asks if they are sure they want to close, which is necessary for when they X out of the window. When they've completed the specific task, I know they want to close and just want to jump to the cleanup and closing process, without asking this question.

My idea would be that in some close cases, I direct them to a separate function which does it's necessary tasks, then calls the close method. But the problem here is, I don't know how to direct the X out process to a different method before calling the close method. As it is right now, it always asks if they're sure they want to quit because this is needed as part of the X out closing method.

Is there any way to do what I'm trying to do?

Body:
A method of solution is to close your application without running closeEvent, for this you can use the function qApp.quit().

For example in the following script can be closed by two methods: the first is a new button called btn, and the second the button X. For the first case we connect it to a slot that calls a dialog, if that is accepted I close the Application with qApp.quit, the second case is similar to the one you implement.

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import sys

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent=parent)
        btn = QPushButton("close")
        self.setCentralWidget(btn)
        btn.clicked.connect(self.closeByButton)

    def closeByButton(self):
        msgBox = QMessageBox()
        msgBox.setText("new Method")
        msgBox.setStandardButtons(QMessageBox.Cancel | QMessageBox.Yes | QMessageBox.No);
        msgBox.setDefaultButton(QMessageBox.Yes);
        if msgBox.exec_() == QMessageBox.Yes:
            qApp.quit()

    def closeEvent(self, event):
        msgBox = QMessageBox()
        msgBox.setText("Button X Method")
        msgBox.setStandardButtons(QMessageBox.Cancel | QMessageBox.Yes | QMessageBox.No);
        msgBox.setDefaultButton(QMessageBox.Yes);
        if msgBox.exec_() == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())


问:
SilverStripe random order for ArrayList()
I know that we can randomly sort a DataList with the following:

```<code>$example = Example::get()->sort('RAND()');
</code>```

But when I try to randomly sort an ArrayList it doesn't work. I can sort an ArrayList by ID DESC, but not with RAND().

Is there a way to make an ArrayList randomly sort its items?

Example:

```<code>public function AllTheKits() {
    $kits = Versioned::get_by_stage('KitsPage', 'Live');
    $kitsArrayList = ArrayList::create();

    foreach ($kits as $kit) {
        if ($kit->MemberID == Member::currentUserID()) {
            $kitsArrayList->push($kit);
        }
    }
    return $kitsArrayList;
}
</code>```

In a page:

```<code>public function getKitsRandom() {
    return $this->AllTheKits()->sort('RAND()');
}
</code>```

This does not work in a template with <% loop KitsRandom %>

答:
You could randomly sort the DataList before you loop over it, instead of trying to randomly sort the ArrayList:

```<code>public function AllTheKits($sort = '') {
    $kits = Versioned::get_by_stage('KitsPage', 'Live', '', $sort);
    $kitsArrayList = ArrayList::create();

    foreach ($kits as $kit) {
        if ($kit->MemberID == Member::currentUserID()) {
            $kitsArrayList->push($kit);
        }
    }
    return $kitsArrayList;
}

public function getKitsRandom() {
    return $this->AllTheKits('RAND()'));
}
</code>```

As a side note, you can filter the original DataList to fetch KitsPages that relate to this MemberID in the Versioned::get_by_stage call:

```<code>public function AllTheKits($sort = '') {
    $kits = Versioned::get_by_stage(
        'KitsPage',
        'Live',
        'MemberID = ' . Member::currentUserID(),
        $sort
    );
    $kitsArrayList = ArrayList::create($kits);

    return $kitsArrayList;
}
</code>```

You could also just do this:

return KitsPage::get()->filter('MemberID', Member::currentUserID())->sort('RAND()');

When you are viewing the live site this will only get the live KitPages.

Body:
I know that we can randomly sort a DataList with the following:

$example = Example::get()->sort('RAND()');

But when I try to randomly sort an ArrayList it doesn't work. I can sort an ArrayList by ID DESC, but not with RAND().

Is there a way to make an ArrayList randomly sort its items?

Example:

public function AllTheKits() {
    $kits = Versioned::get_by_stage('KitsPage', 'Live');
    $kitsArrayList = ArrayList::create();

    foreach ($kits as $kit) {
        if ($kit->MemberID == Member::currentUserID()) {
            $kitsArrayList->push($kit);
        }
    }
    return $kitsArrayList;
}

In a page:

public function getKitsRandom() {
    return $this->AllTheKits()->sort('RAND()');
}

This does not work in a template with <% loop KitsRandom %>

Body:
You could randomly sort the DataList before you loop over it, instead of trying to randomly sort the ArrayList:

public function AllTheKits($sort = '') {
    $kits = Versioned::get_by_stage('KitsPage', 'Live', '', $sort);
    $kitsArrayList = ArrayList::create();

    foreach ($kits as $kit) {
        if ($kit->MemberID == Member::currentUserID()) {
            $kitsArrayList->push($kit);
        }
    }
    return $kitsArrayList;
}

public function getKitsRandom() {
    return $this->AllTheKits('RAND()'));
}

As a side note, you can filter the original DataList to fetch KitsPages that relate to this MemberID in the Versioned::get_by_stage call:

public function AllTheKits($sort = '') {
    $kits = Versioned::get_by_stage(
        'KitsPage',
        'Live',
        'MemberID = ' . Member::currentUserID(),
        $sort
    );
    $kitsArrayList = ArrayList::create($kits);

    return $kitsArrayList;
}

You could also just do this:

return KitsPage::get()->filter('MemberID', Member::currentUserID())->sort('RAND()');

When you are viewing the live site this will only get the live KitPages.


问:
Outlook API: Receiving 'ErrorIrresolvableConflict' when trying to send Draft
When trying to send a draft, I receive an error:

"ErrorIrresolvableConflict","message":"The send or update operation could not be performed because the change key passed in the request does not match the current change key for the item., Item could not be saved because conflicts were detected when saving.

The message seems to send later when trying in a sandbox.

答: I fixed this by inserting a timeout between the creation of the draft and sending the draft. Essentially, race condition issues.</p>