问:
How can I speed up performance of this Firestore query loop? Comparing phone contact list to Firestore database for matches
I am comparing a list of contacts' emails in the user's phone to a list of user's emails in my Firestore Database, and then creating a new list of "contactsInApp".

First, I get the entire collection of users from firestore database.  Then for each user, I create a forEach loop, checking each contact in my list of phone contacts for a match.  If there is a match, it creates a new list of "androidContactsInApp".  It works fine when there are a small amount of users, but when I tested it with 5,000 users, it takes much longer - about 30 seconds.  I thought firestore was supposed to scale well, so wondering if there is problem with my code.

Here is my code:

```<code>fsDB.collection("users")
                .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot documentSnapshots) {
                for (DocumentSnapshot document : documentSnapshots) {

                    String userEmail = document.get("email").toString();

                    for (UserInfoForRequest android_contact: arrayListAndroidContacts) {
                        String isEmailInDatabase = android_contact.getUserEmail();
                        String trimmedEmail = isEmailInDatabase.trim();
                        if (userEmail.equals(trimmedEmail)) {
                            String userID = document.getId();

                            UserInfoForRequest android_contact2 = new UserInfoForRequest();
                            android_contact2.setUserName(document.get("username").toString());
                            android_contact2.setUserEmail(userEmail);
                            android_contact2.setCurrentUID(currentUID);
                            android_contact2.setContactsUID(userID);
                            arrayListAndroidContactsInApp.add(android_contact2);

                        }

                    }

                }
                adapterWithApp.notifyDataSetChanged();
                adapterNoApp.notifyDataSetChanged();
            }
        });
</code>```

I have also tried inverting the loop. Doing it that way, I get each contact within my list of phone contacts, and I perform a query for each phone contact.  This means I don't have download the entire collection of users.  This method is much, much slower -  multitudes slower.  I think that is because I perform separate, individual queries.   Here is my code:

```<code>        for (final UserInfoForRequest android_contact: arrayListAndroidContacts) {

            String contactsEmail = android_contact.getUserEmail();
            String trimmedEmail = contactsEmail.trim();

            fsDB.collection("users").whereEqualTo("email", trimmedEmail).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot documentSnapshots) {

                    if (documentSnapshots.isEmpty()) {
                        Log.d("FOUNDEMAIL", " document is empty ");

                    }
                    else {

                        List list = documentSnapshots.getDocuments();

                        DocumentSnapshot doc = (DocumentSnapshot) list.get(0);

                        UserInfoForRequest android_contact2 = new UserInfoForRequest();
                        android_contact2.setUserName(doc.get("username").toString());
                        android_contact2.setUserEmail(doc.get("email").toString());
                        android_contact2.setCurrentUID(currentUID);
                        android_contact2.setContactsUID(doc.getId());
                        arrayListAndroidContactsInApp.add(android_contact2);

                        adapterWithApp.notifyDataSetChanged();
                        adapterNoApp.notifyDataSetChanged();

                    }
                }
            })
</code>```

Edit:  Ok, so I did some tests.  When I used "Snapshot Listener" instead of using .get, I was able to save 4 seconds to retrieve the document Snapshots, going from 27.5s down to 23.5 seconds.  I also found that the loop itself is only taking 4 seconds - the retrieval of documents takes 19.

I then deleted the 5,000 users and tested with 1,000 users.  The load time for 1,000 users is 6.5 seconds, and the loop itself was. 1 second.  Is this just an issue that firebase needs to address in order to speed this up?

答:
I figured out a way to greatly speed up the search.

There isn't a problem with the code.  The problem is that it is just too intensive for the client device.

Instead, I used Cloud Functions, so the server, which has much greater power, itself handles the looping.

Get list of contacts on Device.

Send list of contacts (emails or phone number) to a specific document in firestore Database. i.e..
fsDB.doc("users/UID/device_contacts);

Create a Cloud function that activates when that document is created... exports.NewContactList = admin.firestore().doc('users/${UID}/device_contacts);

That function reads the document, and looks for any "users" where their email or phone number == the phone or email in the doc.

It then puts those users into a new document - users/UID/suggestedFriends

Then the client device reads the list of suggested Friends from the created doc.

This process still takes time, but only on the 1st time you create the suggested list.  It also happens in the background, so the device isn't stalled.  I then also created a function that updates the list when new user is added to database or there is a new contact in the user's phone.

EDIT

The function I wrote...

```<code>exports.createdFriendListTest =     functions.firestore.document('users/{userID}/device_contacts/device_contacts').onCreate(event => {
console.log('test worked... function called after creating doc 1st time.');

const userID = event.params.userID;
const docWithContacts = event.data.data();
console.log(docWithContacts);

var promises = []; // to hold promises within the keyList.forEach loop.
const keyList = Object.keys(docWithContacts);
keyList.forEach(key => {

    var promise = admin.firestore().collection('users').where('email', '==', key).get().then(querySnapshot =>{
        console.log('querySnapshot obtained');
         if (querySnapshot.empty) {
             console.log('there is no user ', key, ' within database.');
             return true;
         } else {
             console.log('user, ', key, ' exists in database');
             querySnapshot.docs.forEach(docSnap => {

                const userExistID = docSnap.id;
                console.log('that user ID is ', userExistID);

                const userData = docSnap.data();
                console.log('user Data', userData);

                const SuggestFriend = admin.firestore().doc(`users/${userID}/suggested_friends/${userExistID}`).set(userData);
                return SuggestFriend.then(result => {
                    console.log('suggested friend added');
                    return true;
                })
            })
         }
    })
    promises.push(promise);
})
return Promise.all(promises);
});
</code>```

Body:
I am comparing a list of contacts' emails in the user's phone to a list of user's emails in my Firestore Database, and then creating a new list of "contactsInApp".

First, I get the entire collection of users from firestore database.  Then for each user, I create a forEach loop, checking each contact in my list of phone contacts for a match.  If there is a match, it creates a new list of "androidContactsInApp".  It works fine when there are a small amount of users, but when I tested it with 5,000 users, it takes much longer - about 30 seconds.  I thought firestore was supposed to scale well, so wondering if there is problem with my code.

Here is my code:

fsDB.collection("users")
                .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot documentSnapshots) {
                for (DocumentSnapshot document : documentSnapshots) {

                    String userEmail = document.get("email").toString();

                    for (UserInfoForRequest android_contact: arrayListAndroidContacts) {
                        String isEmailInDatabase = android_contact.getUserEmail();
                        String trimmedEmail = isEmailInDatabase.trim();
                        if (userEmail.equals(trimmedEmail)) {
                            String userID = document.getId();

                            UserInfoForRequest android_contact2 = new UserInfoForRequest();
                            android_contact2.setUserName(document.get("username").toString());
                            android_contact2.setUserEmail(userEmail);
                            android_contact2.setCurrentUID(currentUID);
                            android_contact2.setContactsUID(userID);
                            arrayListAndroidContactsInApp.add(android_contact2);

                        }

                    }

                }
                adapterWithApp.notifyDataSetChanged();
                adapterNoApp.notifyDataSetChanged();
            }
        });

I have also tried inverting the loop. Doing it that way, I get each contact within my list of phone contacts, and I perform a query for each phone contact.  This means I don't have download the entire collection of users.  This method is much, much slower -  multitudes slower.  I think that is because I perform separate, individual queries.   Here is my code:

        for (final UserInfoForRequest android_contact: arrayListAndroidContacts) {

            String contactsEmail = android_contact.getUserEmail();
            String trimmedEmail = contactsEmail.trim();

            fsDB.collection("users").whereEqualTo("email", trimmedEmail).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot documentSnapshots) {

                    if (documentSnapshots.isEmpty()) {
                        Log.d("FOUNDEMAIL", " document is empty ");

                    }
                    else {

                        List list = documentSnapshots.getDocuments();

                        DocumentSnapshot doc = (DocumentSnapshot) list.get(0);

                        UserInfoForRequest android_contact2 = new UserInfoForRequest();
                        android_contact2.setUserName(doc.get("username").toString());
                        android_contact2.setUserEmail(doc.get("email").toString());
                        android_contact2.setCurrentUID(currentUID);
                        android_contact2.setContactsUID(doc.getId());
                        arrayListAndroidContactsInApp.add(android_contact2);

                        adapterWithApp.notifyDataSetChanged();
                        adapterNoApp.notifyDataSetChanged();

                    }
                }
            })

Edit:  Ok, so I did some tests.  When I used "Snapshot Listener" instead of using .get, I was able to save 4 seconds to retrieve the document Snapshots, going from 27.5s down to 23.5 seconds.  I also found that the loop itself is only taking 4 seconds - the retrieval of documents takes 19.

I then deleted the 5,000 users and tested with 1,000 users.  The load time for 1,000 users is 6.5 seconds, and the loop itself was. 1 second.  Is this just an issue that firebase needs to address in order to speed this up?

Body:
I figured out a way to greatly speed up the search.

There isn't a problem with the code.  The problem is that it is just too intensive for the client device.

Instead, I used Cloud Functions, so the server, which has much greater power, itself handles the looping.

Get list of contacts on Device.

Send list of contacts (emails or phone number) to a specific document in firestore Database. i.e..
fsDB.doc("users/UID/device_contacts);

Create a Cloud function that activates when that document is created... exports.NewContactList = admin.firestore().doc('users/${UID}/device_contacts);

That function reads the document, and looks for any "users" where their email or phone number == the phone or email in the doc.

It then puts those users into a new document - users/UID/suggestedFriends

Then the client device reads the list of suggested Friends from the created doc.

This process still takes time, but only on the 1st time you create the suggested list.  It also happens in the background, so the device isn't stalled.  I then also created a function that updates the list when new user is added to database or there is a new contact in the user's phone.

EDIT

The function I wrote...

exports.createdFriendListTest =     functions.firestore.document('users/{userID}/device_contacts/device_contacts').onCreate(event => {
console.log('test worked... function called after creating doc 1st time.');

const userID = event.params.userID;
const docWithContacts = event.data.data();
console.log(docWithContacts);

var promises = []; // to hold promises within the keyList.forEach loop.
const keyList = Object.keys(docWithContacts);
keyList.forEach(key => {

    var promise = admin.firestore().collection('users').where('email', '==', key).get().then(querySnapshot =>{
        console.log('querySnapshot obtained');
         if (querySnapshot.empty) {
             console.log('there is no user ', key, ' within database.');
             return true;
         } else {
             console.log('user, ', key, ' exists in database');
             querySnapshot.docs.forEach(docSnap => {

                const userExistID = docSnap.id;
                console.log('that user ID is ', userExistID);

                const userData = docSnap.data();
                console.log('user Data', userData);

                const SuggestFriend = admin.firestore().doc(`users/${userID}/suggested_friends/${userExistID}`).set(userData);
                return SuggestFriend.then(result => {
                    console.log('suggested friend added');
                    return true;
                })
            })
         }
    })
    promises.push(promise);
})
return Promise.all(promises);
});


来源: stackexchange

问:
single identifier for multiple css classes
I have frequent bundling together of css classes like this:

```<code><div class="row z-depth-2 gradient-background">
... Blah
</div>
</code>```

I have these three classes: row z-depth-2 gradient-background used together in more than 200 places. How can I introduce a single class for these three taken together?

I don't mind CSS or SASS. One other problem is that row and z-depth-2 are defined in materialize.css which I don't wanna touch. So I can't simply extend these classes in SASS like so:

```<code>.input-group {
    @extend .row, .z-depth-2, .gradient-background
}
</code>```

So I want to be able to do something like this:

```<code><div class="input-group">
    ... Blah
</div>
</code>```

答:
Why not simply use the three classes as one selector like this .row.z-depth-2.gradient-background. It will allow you to select elements that have these 3 classes (it can have more of course) :

div {
  margin:10px;
  height: 20px;
  background: blue;
}

.row.z-depth-2.gradient-background {/* pay attention as there is no spaces between the classes*/
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row z-depth-2 gradient-background">
<!-- Select this one -->
</div>
<div class="row gradient-background">

</div>

<div class="row z-depth-2">

</div>

<div class="row gradient-background z-depth-2 more-class">
<!-- Select this one -->
</div></code>```

Usefull links to get more details :

https://css-tricks.com/multiple-class-id-selectors/

Using two CSS classes on one element

UPDATE

If you want to use a new class that will later be replaced with these 3 ones, you can use a small jQuery script in order to do what you need, like this :

//select all element with class input-group
$('.input-group').each(function() {
  $(this).removeClass('input-group'); //remove input-group
  $(this).addClass('row z-depth-2 gradient-background'); //add the other classes
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  margin: 10px;
  height: 20px;
  background: blue;
}

.row.z-depth-2.gradient-background {
  /* pay attention as there is no spaces between the classes*/
  background: red;
}</code>```

```

ContentLicense: CC BY-SA 3.0

Body:
I have frequent bundling together of css classes like this:

... Blah

I have these three classes: row z-depth-2 gradient-background used together in more than 200 places. How can I introduce a single class for these three taken together?

I don't mind CSS or SASS. One other problem is that row and z-depth-2 are defined in materialize.css which I don't wanna touch. So I can't simply extend these classes in SASS like so:

.input-group {
    @extend .row, .z-depth-2, .gradient-background
}

So I want to be able to do something like this:

    ... Blah

Body:
Why not simply use the three classes as one selector like this .row.z-depth-2.gradient-background. It will allow you to select elements that have these 3 classes (it can have more of course) :

div {
  margin:10px;
  height: 20px;
  background: blue;
}

.row.z-depth-2.gradient-background {/* pay attention as there is no spaces between the classes*/
  background: red;
}

<div class="row z-depth-2 gradient-background">
<!-- Select this one -->
</div>
<div class="row gradient-background">

</div>

<div class="row z-depth-2">

</div>

<div class="row gradient-background z-depth-2 more-class">
<!-- Select this one -->
</div>

Usefull links to get more details :

https://css-tricks.com/multiple-class-id-selectors/

Using two CSS classes on one element

UPDATE

If you want to use a new class that will later be replaced with these 3 ones, you can use a small jQuery script in order to do what you need, like this :

//select all element with class input-group
$('.input-group').each(function() {
  $(this).removeClass('input-group'); //remove input-group
  $(this).addClass('row z-depth-2 gradient-background'); //add the other classes
})

div {
  margin: 10px;
  height: 20px;
  background: blue;
}

.row.z-depth-2.gradient-background {
  /* pay attention as there is no spaces between the classes*/
  background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-group">

</div>
<div class="class">

</div>


问:
How to detect if speech to text is available on android?
I believe I have figured out how to detect if an android device has a microphone, like so:

```<code>Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        List<ResolveInfo> speechActivities = packageManager.queryIntentActivities(speechIntent, 0);
        TextView micAvailView = (TextView) findViewById(R.id.mic_available_flag);
        if (speechActivities.size() != 0) { //we have a microphone

        }
        else { //we do not have a microphones

        }
</code>```

However, how does one detect whether the android device has speech-to-text capability? Or should the above be used to detect that? If so, how does one detect if the device has a microphone?

Any feedback is appreciated, thanks.

答:
The code you attached is indeed used to detect if audio recognition is available [1]:

```
// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List activities = pm.queryIntentActivities(
  new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
  speakButton.setOnClickListener(this);
} else {
  speakButton.setEnabled(false);
  speakButton.setText("Recognizer not present");
}
```

To test if a mic is present, just follow the code in [2] and the docs at [3], when calling prepare() you should get an IOException if the mic is not available:

```
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
```

[1] http://developer.android.com/resources/articles/speech-input.html

[2] http://developer.android.com/guide/topics/media/index.html#capture

[3] http://developer.android.com/reference/android/media/MediaRecorder.AudioSource.html

ContentLicense: CC BY-SA 2.5

Body:
I believe I have figured out how to detect if an android device has a microphone, like so:

Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        List<ResolveInfo> speechActivities = packageManager.queryIntentActivities(speechIntent, 0);
        TextView micAvailView = (TextView) findViewById(R.id.mic_available_flag);
        if (speechActivities.size() != 0) { //we have a microphone

        }
        else { //we do not have a microphones

        }

However, how does one detect whether the android device has speech-to-text capability? Or should the above be used to detect that? If so, how does one detect if the device has a microphone?

Any feedback is appreciated, thanks.

Body:
The code you attached is indeed used to detect if audio recognition is available [1]:

// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List activities = pm.queryIntentActivities(
  new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
  speakButton.setOnClickListener(this);
} else {
  speakButton.setEnabled(false);
  speakButton.setText("Recognizer not present");
}

To test if a mic is present, just follow the code in [2] and the docs at [3], when calling prepare() you should get an IOException if the mic is not available:

recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();

[1] http://developer.android.com/resources/articles/speech-input.html

[2] http://developer.android.com/guide/topics/media/index.html#capture

[3] http://developer.android.com/reference/android/media/MediaRecorder.AudioSource.html


问:
Freemarker template to check the constant value
Here is my piece of code

```<code><#if (miscValue_index > 0)><#break></#if>
<td valign=""top"">${miscValue.propertyName!}</td>
<td width=""10px"">   </td>
<td valign=""top"">${miscValue.propertyValue!}</td>
<td width=""10px"">   </td>
<td valign=""top"">${miscValue.newPropertyValue!}</td>
<td width=""10px"">   </td>
</code>```

i want to check if "miscValue.propertyValue" value is UNDEFINED or valid string

miscValue.propertyValue will return a valid string or UNDEFINED.
If the value returned is "UNDEFINED",i need to update "empty string" else the "orginal value" using freemarker language.Could anyone please help on this.
Thanks in advance

答:
You can use like this:

<#if variable_to_test??>not null!<#else>null!</#if>

ContentLicense: CC BY-SA 4.0

Body:
Here is my piece of code

<#if (miscValue_index > 0)><#break></#if>
${miscValue.propertyName!}

${miscValue.propertyValue!}

${miscValue.newPropertyValue!}

i want to check if "miscValue.propertyValue" value is UNDEFINED or valid string

miscValue.propertyValue will return a valid string or UNDEFINED.
If the value returned is "UNDEFINED",i need to update "empty string" else the "orginal value" using freemarker language.Could anyone please help on this.
Thanks in advance


问:
deactivate account from firebase chat app
i'm using the firebase database for my chat application, When i click on the deactivate button it deletes the user from the Authentication section of firebase but not from the database section of firebase and my all user activity retrieve the user data from the database section. because of this when a user deactivate his account it get delete, but his account is still visible to the other user. below this i'm attaching my codes..

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

    ImageView ivCamera;

    private DatabaseReference mUserDatabase;
    private FirebaseUser mCurrentUser;

    private CircleImageView mDisplayImage;
    private TextView mName;
    private TextView mStatus;

    private Button mProfileBtn;
    private Button mDeactivateBtn;
    //private Button mImageBtn;

    private static final int GALLERY_PICK = 1;

    private StorageReference mImageStorage;

    private ProgressDialog mProgressDialog;

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

        mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
        mName = (TextView) findViewById(R.id.settings_name);
        mStatus = (TextView) findViewById(R.id.settings_status);

        mProfileBtn = (Button) findViewById(R.id.settings_profile_btn);
        mDeactivateBtn = (Button) findViewById(R.id.deactivate_btn);
        ivCamera = (ImageView) findViewById(R.id.ivCamera);
        mProgressDialog = new ProgressDialog(this);

        mImageStorage = FirebaseStorage.getInstance().getReference();

        mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();

        String current_uid = mCurrentUser.getUid();

        mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);

        mUserDatabase.keepSynced(true);

        mUserDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                String name = dataSnapshot.child("name").getValue().toString();
                final String image = dataSnapshot.child("image").getValue().toString();
                String status = dataSnapshot.child("status").getValue().toString();
                String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();

                mName.setText(name);
                mStatus.setText(status);

                if (!image.equals("default")) {

                    //Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
                    Picasso.with(SettingsActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE)
                            .placeholder(R.drawable.avatar).into(mDisplayImage, new Callback() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onError() {

                            Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
                        }
                    });

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        //ivGallery =(ImageView) findViewById(R.id.ivGallery);

        //ivGallery.setOnClickListener(new View.OnClickListener() {
        //   @Override
        // public void onClick(View view) {

        //}
        //});

        mProfileBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name_value = mName.getText().toString();
                String status_value = mStatus.getText().toString();

                Intent status_Intent = new Intent(SettingsActivity.this, StatusActivity.class);
                status_Intent.putExtra("status_value", status_value);
                status_Intent.putExtra("name_value", name_value);

                startActivity(status_Intent);
            }

        });

        ivCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent galleryIntent = new Intent();
                galleryIntent.setType("image/*");
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

                startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);

            }

        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {

            Uri imageUri = data.getData();

            CropImage.activity(imageUri).setAspectRatio(1, 1).start(this);

            //Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_LONG).show();

        }
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {

            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if (resultCode == RESULT_OK) {

                mProgressDialog = new ProgressDialog(SettingsActivity.this);
                mProgressDialog.setTitle("Uploading Image.....");
                mProgressDialog.setMessage("Please wait while we upload and process the image.");
                mProgressDialog.setCanceledOnTouchOutside(false);
                mProgressDialog.show();

                Uri resultUri = result.getUri();

                File thumb_filePath = new File(resultUri.getPath());

                String current_user_id = mCurrentUser.getUid();

                Bitmap thumb_bitmap = new Compressor(this)
                        .setMaxWidth(200)
                        .setMaxHeight(200)
                        .setQuality(75)
                        .compressToBitmap(thumb_filePath);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                final byte[] thumb_byte = baos.toByteArray();

                StorageReference filePath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");

                final StorageReference thumb_filepath = mImageStorage.child("profile_images").child("thumbs").child(current_user_id + ".jpg");

                filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                        if (task.isSuccessful()) {

                            final String download_url = task.getResult().getDownloadUrl().toString();

                            UploadTask uploadTask = thumb_filepath.putBytes(thumb_byte);
                            uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {

                                    String thumb_downloadUrl = thumb_task.getResult().getDownloadUrl().toString();

                                    if (thumb_task.isSuccessful()) {

                                        Map update_hashMap = new HashMap();
                                        update_hashMap.put("image", download_url);
                                        update_hashMap.put("thumb_image", thumb_downloadUrl);

                                        mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if (task.isSuccessful()) {

                                                    mProgressDialog.dismiss();
                                                    Toast.makeText(SettingsActivity.this, "Success Uploading.", Toast.LENGTH_LONG).show();
                                                }
                                            }
                                        });
                                    } else {

                                        Toast.makeText(SettingsActivity.this, "Error in Uploading thumbnail.", Toast.LENGTH_LONG).show();
                                        mProgressDialog.dismiss();
                                    }
                                }
                            });

                        } else {

                            Toast.makeText(SettingsActivity.this, "Error in Uploading.", Toast.LENGTH_LONG).show();
                            mProgressDialog.dismiss();
                        }
                    }
                });

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                Exception error = result.getError();
            }
        }
    }

    public static String random() {
        Random generator = new Random();
        StringBuilder randomStringBuilder = new StringBuilder();
        int randomLength = generator.nextInt(10);
        char tempChar;
        for (int i = 0; i < randomLength; i++) {
            tempChar = (char) (generator.nextInt(96) + 32);
            randomStringBuilder.append(tempChar);
        }
        return randomStringBuilder.toString();
    }

            public void deactivate(View view)
            {
              FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if (user!=null)
            {
             mProgressDialog.setTitle("Deactivate Account");
            mProgressDialog.setMessage("Deactivating...");
              mProgressDialog.show();
              mUserDatabase.child(mCurrentUser.getUid()).removeValue();
             user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
                 public void onComplete(@NonNull Task<Void> task) {
                     if (task.isSuccessful()) {
                         Toast.makeText(getApplicationContext(), "Account is Deactivated", Toast.LENGTH_LONG).show();
                         finish();
                         Intent intent = new Intent(SettingsActivity.this, RegisterActivity.class);
                         startActivity(intent);
                     } else {
                         Toast.makeText(getApplicationContext(), "Account could not be Deactivate", Toast.LENGTH_LONG).show();
                     }
                     mProgressDialog.dismiss();
                 }
             });
              }
            }
}
</code>```

i want that when the user deactivate his account it will not visible anymore in the all user activity

答:
DatabaseReference delete = FirebaseDatabase.getInstance().getReference().child("Node");
                delete.setValue(null);</p>

Body:
i'm using the firebase database for my chat application, When i click on the deactivate button it deletes the user from the Authentication section of firebase but not from the database section of firebase and my all user activity retrieve the user data from the database section. because of this when a user deactivate his account it get delete, but his account is still visible to the other user. below this i'm attaching my codes..

public class SettingsActivity extends AppCompatActivity{

    ImageView ivCamera;

    private DatabaseReference mUserDatabase;
    private FirebaseUser mCurrentUser;

    private CircleImageView mDisplayImage;
    private TextView mName;
    private TextView mStatus;

    private Button mProfileBtn;
    private Button mDeactivateBtn;
    //private Button mImageBtn;

    private static final int GALLERY_PICK = 1;

    private StorageReference mImageStorage;

    private ProgressDialog mProgressDialog;

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

        mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
        mName = (TextView) findViewById(R.id.settings_name);
        mStatus = (TextView) findViewById(R.id.settings_status);

        mProfileBtn = (Button) findViewById(R.id.settings_profile_btn);
        mDeactivateBtn = (Button) findViewById(R.id.deactivate_btn);
        ivCamera = (ImageView) findViewById(R.id.ivCamera);
        mProgressDialog = new ProgressDialog(this);

        mImageStorage = FirebaseStorage.getInstance().getReference();

        mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();

        String current_uid = mCurrentUser.getUid();

        mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);

        mUserDatabase.keepSynced(true);

        mUserDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                String name = dataSnapshot.child("name").getValue().toString();
                final String image = dataSnapshot.child("image").getValue().toString();
                String status = dataSnapshot.child("status").getValue().toString();
                String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();

                mName.setText(name);
                mStatus.setText(status);

                if (!image.equals("default")) {

                    //Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
                    Picasso.with(SettingsActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE)
                            .placeholder(R.drawable.avatar).into(mDisplayImage, new Callback() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onError() {

                            Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
                        }
                    });

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        //ivGallery =(ImageView) findViewById(R.id.ivGallery);

        //ivGallery.setOnClickListener(new View.OnClickListener() {
        //   @Override
        // public void onClick(View view) {

        //}
        //});

        mProfileBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name_value = mName.getText().toString();
                String status_value = mStatus.getText().toString();

                Intent status_Intent = new Intent(SettingsActivity.this, StatusActivity.class);
                status_Intent.putExtra("status_value", status_value);
                status_Intent.putExtra("name_value", name_value);

                startActivity(status_Intent);
            }

        });

        ivCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent galleryIntent = new Intent();
                galleryIntent.setType("image/*");
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

                startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);

            }

        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {

            Uri imageUri = data.getData();

            CropImage.activity(imageUri).setAspectRatio(1, 1).start(this);

            //Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_LONG).show();

        }
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {

            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if (resultCode == RESULT_OK) {

                mProgressDialog = new ProgressDialog(SettingsActivity.this);
                mProgressDialog.setTitle("Uploading Image.....");
                mProgressDialog.setMessage("Please wait while we upload and process the image.");
                mProgressDialog.setCanceledOnTouchOutside(false);
                mProgressDialog.show();

                Uri resultUri = result.getUri();

                File thumb_filePath = new File(resultUri.getPath());

                String current_user_id = mCurrentUser.getUid();

                Bitmap thumb_bitmap = new Compressor(this)
                        .setMaxWidth(200)
                        .setMaxHeight(200)
                        .setQuality(75)
                        .compressToBitmap(thumb_filePath);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                final byte[] thumb_byte = baos.toByteArray();

                StorageReference filePath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");

                final StorageReference thumb_filepath = mImageStorage.child("profile_images").child("thumbs").child(current_user_id + ".jpg");

                filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                        if (task.isSuccessful()) {

                            final String download_url = task.getResult().getDownloadUrl().toString();

                            UploadTask uploadTask = thumb_filepath.putBytes(thumb_byte);
                            uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {

                                    String thumb_downloadUrl = thumb_task.getResult().getDownloadUrl().toString();

                                    if (thumb_task.isSuccessful()) {

                                        Map update_hashMap = new HashMap();
                                        update_hashMap.put("image", download_url);
                                        update_hashMap.put("thumb_image", thumb_downloadUrl);

                                        mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if (task.isSuccessful()) {

                                                    mProgressDialog.dismiss();
                                                    Toast.makeText(SettingsActivity.this, "Success Uploading.", Toast.LENGTH_LONG).show();
                                                }
                                            }
                                        });
                                    } else {

                                        Toast.makeText(SettingsActivity.this, "Error in Uploading thumbnail.", Toast.LENGTH_LONG).show();
                                        mProgressDialog.dismiss();
                                    }
                                }
                            });

                        } else {

                            Toast.makeText(SettingsActivity.this, "Error in Uploading.", Toast.LENGTH_LONG).show();
                            mProgressDialog.dismiss();
                        }
                    }
                });

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                Exception error = result.getError();
            }
        }
    }

    public static String random() {
        Random generator = new Random();
        StringBuilder randomStringBuilder = new StringBuilder();
        int randomLength = generator.nextInt(10);
        char tempChar;
        for (int i = 0; i < randomLength; i++) {
            tempChar = (char) (generator.nextInt(96) + 32);
            randomStringBuilder.append(tempChar);
        }
        return randomStringBuilder.toString();
    }

            public void deactivate(View view)
            {
              FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if (user!=null)
            {
             mProgressDialog.setTitle("Deactivate Account");
            mProgressDialog.setMessage("Deactivating...");
              mProgressDialog.show();
              mUserDatabase.child(mCurrentUser.getUid()).removeValue();
             user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
                 public void onComplete(@NonNull Task<Void> task) {
                     if (task.isSuccessful()) {
                         Toast.makeText(getApplicationContext(), "Account is Deactivated", Toast.LENGTH_LONG).show();
                         finish();
                         Intent intent = new Intent(SettingsActivity.this, RegisterActivity.class);
                         startActivity(intent);
                     } else {
                         Toast.makeText(getApplicationContext(), "Account could not be Deactivate", Toast.LENGTH_LONG).show();
                     }
                     mProgressDialog.dismiss();
                 }
             });
              }
            }
}

i want that when the user deactivate his account it will not visible anymore in the all user activity


问:
junit no webapplication context found: no ContextLoad Listener registered?
I am trying to write test cases for my structs application in which some of configurations in springs based xml files.
i moved all my applicationContext files into src/test/resources class path but when i run my test class(RunAs-> Junit Test), it throws below error </p>

```<code>java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
    at org.springframework.web.context.support.WebApplicationContextUtils.getRequiredWebApplicationContext(WebApplicationContextUtils.java:90)
    at com.cisco.attrui.test.BundleSearchActionTest.getPidBTSplitPctSearchTest(BundleSearchActionTest.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

答:
Seems like similar problem as in other post I recently answered here:
JUnit 4.12: testing util classes

Moving xml configs to classpath is not enough. You need to tell Spring which ones to use and you need to use Spring test runner in the first place.

Like this:

```<code>@ContextConfiguration(locations = {"/integrationContextTest.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class TdkSMSSenderTest  {
}
</code>```

Body:
I am trying to write test cases for my structs application in which some of configurations in springs based xml files.
i moved all my applicationContext files into src/test/resources class path but when i run my test class(RunAs-> Junit Test), it throws below error

java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
    at org.springframework.web.context.support.WebApplicationContextUtils.getRequiredWebApplicationContext(WebApplicationContextUtils.java:90)
    at com.cisco.attrui.test.BundleSearchActionTest.getPidBTSplitPctSearchTest(BundleSearchActionTest.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Body:
Seems like similar problem as in other post I recently answered here:
JUnit 4.12: testing util classes

Moving xml configs to classpath is not enough. You need to tell Spring which ones to use and you need to use Spring test runner in the first place.

Like this:

@ContextConfiguration(locations = {"/integrationContextTest.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class TdkSMSSenderTest  {
}


问:
Newtonsoft.Json SerializeObject without escape backslashes
Given the code:

```<code>dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
</code>```

The output is below:

```<code>"{\"Bar\":\"something\"}"
</code>```

When debugging a large json document it is hard to read - using the built in features of Newtonsoft.Json (not regex or hacks that could break things) is there any way to make the output a string with the valie:

```<code>{Bar: "something"}
</code>```

答:
Instead of using Newstonsoft.Json you should employ the JavaScriptSerializer.Serialize Method:

```<code>dynamic foo = new ExpandoObject();
foo.Bar = "something";
var js = new JavaScriptSerializer( );
string json = js.Serialize(foo);
</code>```

This method produces exactly the output you are looking for. I read about it here.

Body:
Given the code:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

The output is below:

"{\"Bar\":\"something\"}"

When debugging a large json document it is hard to read - using the built in features of Newtonsoft.Json (not regex or hacks that could break things) is there any way to make the output a string with the valie:

{Bar: "something"}

Body:
Instead of using Newstonsoft.Json you should employ the JavaScriptSerializer.Serialize Method:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
var js = new JavaScriptSerializer( );
string json = js.Serialize(foo);

This method produces exactly the output you are looking for. I read about it here.


问:
Codeigniter .htaccess file for SSL inserts index.php
I'm using the following .htaccess file to redirect certain pages to https://

```<code>RewriteEngine on

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} (sale|success|cancel)
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301]

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !(static|sale|success|cancel)
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301]

RewriteCond $1 !^(index\.php|resources|robots\.txt|static)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

This works, except that when you go to the page that gets rewritten to https:// it also inserts index.php in the URL. Everything works fine, but I would like that index.php not to be inserted. Any ideas?

Thanks.

答:
```<code><Directory "/home/test">
    Require all granted
    ***AllowOverride All***
    SSLOptions +StdEnvVars
</Directory>
</code>```

After adding "AllowOverride All" in your apache configuration, it will work properly.

Regards.

Body:
I'm using the following .htaccess file to redirect certain pages to https://

RewriteEngine on

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} (sale|success|cancel)
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301]

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !(static|sale|success|cancel)
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301]

RewriteCond $1 !^(index\.php|resources|robots\.txt|static)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

This works, except that when you go to the page that gets rewritten to https:// it also inserts index.php in the URL. Everything works fine, but I would like that index.php not to be inserted. Any ideas?

Thanks.

Body:
<Directory "/home/test">
    Require all granted
    ***AllowOverride All***
    SSLOptions +StdEnvVars
</Directory>

After adding "AllowOverride All" in your apache configuration, it will work properly.

Regards.


问:
Execution failed for task ':app:transformClassesWithMultidexlistForDebug' in Android Studio 2.3
I can build my project but can not run the app. When executing app it gives me error like

Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.android.multidex.ClassReferenceListBuilder with arguments {/home/Git_Projects/Test1/app/build/intermediates/multi-dex/debug/componentClasses.jar /home/Git_Projects/Test1/app/build/intermediates/transforms/jarMerging/debug/jars/1/1f/combined.jar}

I tried to clean and rebuild project and Invalidate Catche and Restart. But, nothing helped me.

build.gradle (app)

```<code>apply plugin: 'com.android.application'

android {
    dexOptions {
        javaMaxHeapSize "4g"
    }
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.app.test1"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    mavenCentral()
    maven { url 'https://github.com/Kaustubh-Deshmukh/progressbar_repo/raw/master' }

    maven { url 'https://dl.bintray.com/yazeed44/maven' }
    }

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.google.android.gms:play-services-places:10.0.1'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-vision:10.0.1'

    compile 'com.github.clans:fab:1.6.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.jakewharton:butterknife:8.4.0'
    compile 'com.googlecode.libphonenumber:libphonenumber:7.1.1'
    compile 'com.android.support:appcompat-v7:26.0.0'
    compile 'com.android.support:design:26.0.0'
    compile 'com.android.support:recyclerview-v7:26.0.0'
    compile 'com.android.support:cardview-v7:26.0.0'
    compile 'com.android.support:support-v4:26.0.0'
    compile 'com.android.support:support-annotations:26.0.0'
    compile 'com.android.support:percent:26.0.0'
    compile 'com.android.support:support-v13:26.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
    compile 'com.facebook.fresco:fresco:1.5.0'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.kontaktio:sdk:3.3.2'

    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

    testCompile 'junit:junit:4.12'
}
</code>```

If I randomly remove some dependencies, then it executes fine. Does large app size creating problem to execute app ?

I am using android studio 2.3 and java-8-openjdk-amd64 and ubuntu 16.04

One strange thing : Everything was working correct before executing command

```<code>apt-get update
</code>```

I am searching from days but nothing seems work.

答:
After updating Android Studio from 2.3.0 to 3.0.1 , my problem solved.

Now, it works perfect.

Body:
I can build my project but can not run the app. When executing app it gives me error like

Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.android.multidex.ClassReferenceListBuilder with arguments {/home/Git_Projects/Test1/app/build/intermediates/multi-dex/debug/componentClasses.jar /home/Git_Projects/Test1/app/build/intermediates/transforms/jarMerging/debug/jars/1/1f/combined.jar}

I tried to clean and rebuild project and Invalidate Catche and Restart. But, nothing helped me.

build.gradle (app)

apply plugin: 'com.android.application'

android {
    dexOptions {
        javaMaxHeapSize "4g"
    }
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.app.test1"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    mavenCentral()
    maven { url 'https://github.com/Kaustubh-Deshmukh/progressbar_repo/raw/master' }

    maven { url 'https://dl.bintray.com/yazeed44/maven' }
    }

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.google.android.gms:play-services-places:10.0.1'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-vision:10.0.1'

    compile 'com.github.clans:fab:1.6.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.jakewharton:butterknife:8.4.0'
    compile 'com.googlecode.libphonenumber:libphonenumber:7.1.1'
    compile 'com.android.support:appcompat-v7:26.0.0'
    compile 'com.android.support:design:26.0.0'
    compile 'com.android.support:recyclerview-v7:26.0.0'
    compile 'com.android.support:cardview-v7:26.0.0'
    compile 'com.android.support:support-v4:26.0.0'
    compile 'com.android.support:support-annotations:26.0.0'
    compile 'com.android.support:percent:26.0.0'
    compile 'com.android.support:support-v13:26.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
    compile 'com.facebook.fresco:fresco:1.5.0'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.kontaktio:sdk:3.3.2'

    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

    testCompile 'junit:junit:4.12'
}

If I randomly remove some dependencies, then it executes fine. Does large app size creating problem to execute app ?

I am using android studio 2.3 and java-8-openjdk-amd64 and ubuntu 16.04

One strange thing : Everything was working correct before executing command

apt-get update

I am searching from days but nothing seems work.


问:
Stop repeating UIImage background pattern image - Swift
I'm using swipe to delete in UITableView. In swipe I need to add image. When I add image it repeats. How to stop repeating

```<code> func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let deleteButton = UITableViewRowAction(style: .default, title: "Delete") { (action, indexPath) in
            self.tableView.dataSource?.tableView!(self.tableView, commit: .delete, forRowAt: indexPath)
            return
        }

        deleteButton.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "favourite_delete"))
        deleteButton.title = ""
            return [deleteButton]
}
</code>```

Problem

What I need

答:
The problem, as you might have guessed, is here:

```<code>deleteButton.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "favourite_delete"))
</code>```

You are creating a UIColor using the (patternImage:) initializer. This means that the image will be repeated (See the word "pattern"?).

From the docs:

You can use pattern colors to set the fill or stroke color just as you would a solid color. During drawing, the image in the pattern color is tiled as necessary to cover the given area.

To solve this, you can resize your image so that it fits the frame of the button programmatically. See The simplest way to resize an UIImage?

Alternatively, use MGSwipeTableViewCell, it allows you to put images on swipe buttons.

Body:
I'm using swipe to delete in UITableView. In swipe I need to add image. When I add image it repeats. How to stop repeating

 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let deleteButton = UITableViewRowAction(style: .default, title: "Delete") { (action, indexPath) in
            self.tableView.dataSource?.tableView!(self.tableView, commit: .delete, forRowAt: indexPath)
            return
        }

        deleteButton.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "favourite_delete"))
        deleteButton.title = ""
            return [deleteButton]
}

Problem

What I need

Body:
The problem, as you might have guessed, is here:

deleteButton.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "favourite_delete"))

You are creating a UIColor using the (patternImage:) initializer. This means that the image will be repeated (See the word "pattern"?).

From the docs:

You can use pattern colors to set the fill or stroke color just as you would a solid color. During drawing, the image in the pattern color is tiled as necessary to cover the given area.

To solve this, you can resize your image so that it fits the frame of the button programmatically. See The simplest way to resize an UIImage?

Alternatively, use MGSwipeTableViewCell, it allows you to put images on swipe buttons.


问:
Android - Cancel AsyncTask Forcefully
I have implemented AsyncTask in my one of activity:

```<code> performBackgroundTask asyncTask = new performBackgroundTask();
 asyncTask.execute();
</code>```

Now, i need to implement the "Cancel" button functionality, so i have to stop the execution of the running task. I don't know how do i stop the running task(background task).

So Please suggest me, how do i cancel the AsyncTask forcefully ?

Update:

I found about the Cancel() method of the same, but i found that calling cancel(boolean mayInterruptIfRunning) doesn't necessarily stop the execution of the background process. All that seems to happen is that the AsyncTask will execute onCancelled(), and won't run onPostExecute() when it completes.

答:
Just check isCancelled() once in a while:

```<code> protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
 }
</code>```

Title: Android - Cancel AsyncTask Forcefully

Body:
I have implemented AsyncTask in my one of activity:

 performBackgroundTask asyncTask = new performBackgroundTask();
 asyncTask.execute();

Now, i need to implement the "Cancel" button functionality, so i have to stop the execution of the running task. I don't know how do i stop the running task(background task).

So Please suggest me, how do i cancel the AsyncTask forcefully ?

Update:

I found about the Cancel() method of the same, but i found that calling cancel(boolean mayInterruptIfRunning) doesn't necessarily stop the execution of the background process. All that seems to happen is that the AsyncTask will execute onCancelled(), and won't run onPostExecute() when it completes.

Body:
Just check isCancelled() once in a while:

 protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
 }


问:
Throwing custom error doesn't preserve Error formatting in the log
JavaScript, when throw-ing a built-in error as such:

```<code>throw new Error("Something was wrong");
</code>```

displays the text nicely - you can't tell you threw an object

However, when creating a custom error by subclassing the Error object (or other error object for that matter), the thrown error is not displayed the same way in the console.

So, by using this code:

```<code>var ImproperlyConfigured = function(message){
    this.name ="ImproperlyConfigured";
    this.message = message || "The object you tried to construct was improperly configured due to an unknown error";
}
ImproperlyConfigured.prototype = new Error();
</code>```

The following is the output

I don't like the fact that the object properties (name and message) are shown. In fact, I don't like that I don't understand why the properties are shown.

I've googled a bit and I got the feeling that by implementing a toString method will help but, by using this method, the fact that the name of the error is no longer in red puzzles me even more.

Code

```<code>var ImproperlyConfigured = function(message){
    this.name ="ImproperlyConfigured";
    this.message = message || "The object you tried to construct was improperly configured due to an unknown error";
    this.toString = function(){
        return this.message;
    }
}
ImproperlyConfigured.prototype = new Error();
</code>```

Output:

What I would like to achieve is a standard looking error, by the use of custom error and, of course, by not using the console.error method manually in a try...catch block.

Is this possible?

答:
As Pointy correctly pointed out (pun intended), the issue here is not with JavaScript, but rather with the environment JavaScript is running (in this case, Google Chrome).

In another environment (like Chromium, Firefox, NodeJS, etc.)  the behavior will likely be different, using the same code, depending on how those JavaScript hosts are handling these cases.

Body:
JavaScript, when throw-ing a built-in error as such:

throw new Error("Something was wrong");

displays the text nicely - you can't tell you threw an object

However, when creating a custom error by subclassing the Error object (or other error object for that matter), the thrown error is not displayed the same way in the console.

So, by using this code:

var ImproperlyConfigured = function(message){
    this.name ="ImproperlyConfigured";
    this.message = message || "The object you tried to construct was improperly configured due to an unknown error";
}
ImproperlyConfigured.prototype = new Error();

The following is the output

I don't like the fact that the object properties (name and message) are shown. In fact, I don't like that I don't understand why the properties are shown.

I've googled a bit and I got the feeling that by implementing a toString method will help but, by using this method, the fact that the name of the error is no longer in red puzzles me even more.

Code

var ImproperlyConfigured = function(message){
    this.name ="ImproperlyConfigured";
    this.message = message || "The object you tried to construct was improperly configured due to an unknown error";
    this.toString = function(){
        return this.message;
    }
}
ImproperlyConfigured.prototype = new Error();

Output:

What I would like to achieve is a standard looking error, by the use of custom error and, of course, by not using the console.error method manually in a try...catch block.

Is this possible?


问:
Process Model minFreeThreads clarification
I have been modifying the .net process model to solve some throughput issues.  I've read a lot of the articles out there but need some clarification on the minFreeThreads property.  Does raising this value mean that more threads are reserved to process outgoing requests (make call to external web service)?

Use Case:
I have a async handler that is waiting for a callback to respond to the requester.  There is a timer that causes requests past a time limit to respond with "no data".  If there are 100's of these requests that need a response, does a high minFreeThreads value allow more of these requests to go out?

答:
Although outdated and deprecated:
http://msdn.microsoft.com/en-us/library/ff647787.aspx

I interpret table 6.1 as follows: (for a 1 CPU/core case)
maxWorkerThreads is the number of threads available for ANY operation (incoming, outgoing)
minFreeThreads is the low water mark for INCOMING request. If this mark is reached no more incoming request will be taken on, they will queued. That queuing will help to get the web server any pending stuff (like processing outgoing webservice calls) done.

To answer your question, based on this guidance, no, raising the minFreeThreads will not help performance in your case, it might even reduce it.

Maybe this is a good (no longer maintained) start point to explore further:
http://msdn.microsoft.com/en-us/library/ff647791.aspx#scalenetchapt15_topic12


问:
Can't figure out where my routing error is coming from
So I am trying to implement a polymorphic association for the first time and I'm running into a little bit of trouble.

I am trying to allow users to leave a note on a contact or organization. But after I submit a note I run into a routing error.

Here is the error I'm receiving (image)

Here are my routes:

Here are my routes (screenshot)

Here is my routes.rb file:

```<code>Rails.application.routes.draw do
  get 'welcome/index'

  resources :organizations do
    resources :contacts do
      resources :notes, module: :contacts
    end
    resources :notes, module: :organizations
  end

  root 'welcome#index'
end
</code>```

Here is my notes_controller.rb file:

```<code>class NotesController < ApplicationController

  def create
    @note = @noteable.notes.new note_params

    redirect_to @noteable, notice: "Your note was successful!!!"
  end

  private

  def note_params
    params.require(:note).permit(:note_title, :note_body)
  end
end
</code>```

Here is my contacts/notes_controller.rb file:

```<code>class Contacts::NotesController < ApplicationController

  private

  def set_noteable
    @noteable = Contact.find(params[:contact_id])
  end
end
</code>```

Here is my oranizations/notes_controller.rb file:

```<code>class Organizations::NotesController < ApplicationController

  private

  def set_noteable
    @noteable = Organization.find(params[:organization_id])
  end
end
</code>```

Here is my view/notes/_form.html.rb file:

```<code><h1>New Note</h1>
<%= form_for [noteable, Note.new] do |form| %>

  <p>
    <%= form.label :note_title %><br>
    <%= form.text_field :note_title %>
  </p>
  <p>
    <%= form.label :note_body %><br>
    <%= form.text_area :note_body %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>
</code>```

If you need anything else, I will provide it! Thank you ahead of time!

答:
Try changing this:

```<code>resources :organizations do
  resources :contacts do
    resources :notes, module: :contacts
  end
  resources :notes, module: :organizations
end
</code>```

to these lines:

```<code>resources :organizations do
  resources :contacts do
    resources :notes
  end
  resources :notes
end
</code>```

You don't need the module there since they are already scoped by the parent resource.

Also move the contacts/notes_controller.rb to organizations/contacts/notes_controller.rb. Make sure you also move the view into the corresponding folder.

Hope it helps :)

Body:
So I am trying to implement a polymorphic association for the first time and I'm running into a little bit of trouble.

I am trying to allow users to leave a note on a contact or organization. But after I submit a note I run into a routing error.

Here is the error I'm receiving (image)

Here are my routes:

Here are my routes (screenshot)

Here is my routes.rb file:

Rails.application.routes.draw do
  get 'welcome/index'

  resources :organizations do
    resources :contacts do
      resources :notes, module: :contacts
    end
    resources :notes, module: :organizations
  end

  root 'welcome#index'
end

Here is my notes_controller.rb file:

class NotesController < ApplicationController

  def create
    @note = @noteable.notes.new note_params

    redirect_to @noteable, notice: "Your note was successful!!!"
  end

  private

  def note_params
    params.require(:note).permit(:note_title, :note_body)
  end
end

Here is my contacts/notes_controller.rb file:

class Contacts::NotesController < ApplicationController

  private

  def set_noteable
    @noteable = Contact.find(params[:contact_id])
  end
end

Here is my oranizations/notes_controller.rb file:

class Organizations::NotesController < ApplicationController

  private

  def set_noteable
    @noteable = Organization.find(params[:organization_id])
  end
end

Here is my view/notes/_form.html.rb file:

New Note

<%= form_for [noteable, Note.new] do |form| %>

    <%= form.label :note_title %>

    <%= form.text_field :note_title %>

    <%= form.label :note_body %>

    <%= form.text_area :note_body %>

    <%= form.submit %>

<% end %>

If you need anything else, I will provide it! Thank you ahead of time!

Body:
Try changing this:

resources :organizations do
  resources :contacts do
    resources :notes, module: :contacts
  end
  resources :notes, module: :organizations
end

to these lines:

resources :organizations do
  resources :contacts do
    resources :notes
  end
  resources :notes
end

You don't need the module there since they are already scoped by the parent resource.

Also move the contacts/notes_controller.rb to organizations/contacts/notes_controller.rb. Make sure you also move the view into the corresponding folder.

Hope it helps :)


问:
Get the non-zero minimum of a column and its index
I want to find the minimum value of a column of a matrix of non-negative integers, excluding 0. I know the matrix is square and only has zeros on every element of its main diagonal (i.e. a(i,i)=0 for all i).

I have tried this:

```<code>[best_cost,index] = min(star_costs([1:i-1,i+1:nbr],i));
</code>```

Where nbr is the size of my matrix.

However, the index that is returned is the index excluding the zero, not taking into account the ith element. For example, my first column is:

```<code>[0 9 11 5 18 13 14]'
</code>```

so the code returns best_cost=5and index=3 because the 0 element is excluded. However, I would like to get index=4 as anyone would expect.

Of course just adding 1 does not have sense, as it could happen for any column and, except for the case of this first column, the minimum of the column could be above or below the diagonal.

答:
As suggested in the comment I would try a work around changing the diagonal to the maximum value of the matrix, assuming that only the zeros on the diagonal are to be omitted.

```<code>%create random matrix
A = magic(4)
%change diagonal to the maximum
A(logical(eye(size(A)))) = max(A(:));
</code>```

And now you can apply your search for the minimum

Body:
I want to find the minimum value of a column of a matrix of non-negative integers, excluding 0. I know the matrix is square and only has zeros on every element of its main diagonal (i.e. a(i,i)=0 for all i).

I have tried this:

[best_cost,index] = min(star_costs([1:i-1,i+1:nbr],i));

Where nbr is the size of my matrix.

However, the index that is returned is the index excluding the zero, not taking into account the ith element. For example, my first column is:

[0 9 11 5 18 13 14]'

so the code returns best_cost=5and index=3 because the 0 element is excluded. However, I would like to get index=4 as anyone would expect.

Of course just adding 1 does not have sense, as it could happen for any column and, except for the case of this first column, the minimum of the column could be above or below the diagonal.

Body:
As suggested in the comment I would try a work around changing the diagonal to the maximum value of the matrix, assuming that only the zeros on the diagonal are to be omitted.

%create random matrix
A = magic(4)
%change diagonal to the maximum
A(logical(eye(size(A)))) = max(A(:));

And now you can apply your search for the minimum


问:
Basic Objective-C array 'for' loop assistance
So heres my hangup, I create an array, pass buttons into it and use a for loop in an attempt to place each button on the view. I know they will be in the same position because they both go through the same CGRectMake. However i cannot seem to place anything on the screen with this code, although it doesn't return any errors it still has me stumped as to why.

Anyone got any suggestions? Thanks!

```<code>- (void)practiceMethod{

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Practice Method has begun" message:@"Alert" delegate: self cancelButtonTitle:@"Close" otherButtonTitles: nil];
 //[alert show];
 [alert release];

 float i=0;

 CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];

 UIImage *buttonGraphic = [UIImage imageNamed:@"1.png"];

 UIButton *buttonOne = [[UIButton alloc] initWithFrame:applicationFrame];
 UIButton *buttonTwo = [[UIButton alloc] initWithFrame:applicationFrame];

 buttonArray = [[NSArray alloc] initWithObjects:buttonOne, buttonTwo,nil];

 for (i = 0; i > [buttonArray count]; i++) {

  UIButton *tempElement = [buttonArray objectAtIndex:i];

  tempElement.frame = CGRectMake(140, 230, 50, 50);

  [tempElement setBackgroundImage:buttonGraphic forState:UIControlStateNormal];

  [self addSubview:tempElement];
 }
}
</code>```

答:
Change

for (i = 0; i > [buttonArray count]; i++) {

to

for (i = 0; i < [buttonArray count]; i++) {

and you'll be up and running.

PS.  I suggest you use Objective-Cs for each iterator for these kinds of problem:

```<code>for( UIButton* button in buttonArray )
{
    // stuff with button
}
</code>```

Body:
So heres my hangup, I create an array, pass buttons into it and use a for loop in an attempt to place each button on the view. I know they will be in the same position because they both go through the same CGRectMake. However i cannot seem to place anything on the screen with this code, although it doesn't return any errors it still has me stumped as to why.

Anyone got any suggestions? Thanks!

- (void)practiceMethod{

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Practice Method has begun" message:@"Alert" delegate: self cancelButtonTitle:@"Close" otherButtonTitles: nil];
 //[alert show];
 [alert release];

 float i=0;

 CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];

 UIImage *buttonGraphic = [UIImage imageNamed:@"1.png"];

 UIButton *buttonOne = [[UIButton alloc] initWithFrame:applicationFrame];
 UIButton *buttonTwo = [[UIButton alloc] initWithFrame:applicationFrame];

 buttonArray = [[NSArray alloc] initWithObjects:buttonOne, buttonTwo,nil];

 for (i = 0; i > [buttonArray count]; i++) {

  UIButton *tempElement = [buttonArray objectAtIndex:i];

  tempElement.frame = CGRectMake(140, 230, 50, 50);

  [tempElement setBackgroundImage:buttonGraphic forState:UIControlStateNormal];

  [self addSubview:tempElement];
 }
}

Body:
Change

for (i = 0; i > [buttonArray count]; i++) {

to

for (i = 0; i < [buttonArray count]; i++) {

and you'll be up and running.

PS.  I suggest you use Objective-Cs for each iterator for these kinds of problem:

for( UIButton* button in buttonArray )
{
    // stuff with button
}


问:
How do i get the text from a xml.dom.minidom Dom Element?
How do I get the text value of the title element?
Is this even possible with a Dom Element?
Will I have to parse out the text by hand?</p>

```<code>#-*-coding:utf8;-*-
#qpy:3
#qpy:console

import re
import urllib.request
from xml.dom import minidom

def download(url):
    with urllib.request.urlopen(url) as res:
        return res.read().decode('latin-1')

class RSSFeed(object):
    def __init__(self, url):
        self.url = url
        self.raw_xml = download(url)
        self.dom = minidom.parseString(self.raw_xml)
        self.links = self.dom.getElementsByTagName('link')

    def entries(self):
        ret = {}
        for element in self.dom.getElementsByTagName('entry'):
            title = element.getElementsByTagName('title')[0]
            print(title.toprettyxml())

    def __str__(self):
        return self.dom.toprettyxml()

feed_url = 'https://rickys-python-notes.blogspot.com/atom.xml?redirect=false&start-index=1&max-results=500'
feed = RSSFeed(feed_url)
dom = feed.dom
print(feedHow totries())
</code>```

答:
```<code>def entries(self):
        for element in self.dom.getElementsByTagName('entry'):
            title = element.getElementsByTagName('title')[0].firstChild.nodeValue
            link = element.getElementsByTagName('link')[0].getAttribute('href')
            author = element.getElementsByTagName('name')[0].firstChild.nodeValue
            article = element.getElementsByTagName('content')[0].firstChild
            yield type('Entry', (object,), dict(title=title, link=link, author=author, article=article))
</code>```

Body:
How do I get the text value of the title element?
Is this even possible with a Dom Element?
Will I have to parse out the text by hand?

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

import re
import urllib.request
from xml.dom import minidom

def download(url):
    with urllib.request.urlopen(url) as res:
        return res.read().decode('latin-1')

class RSSFeed(object):
    def __init__(self, url):
        self.url = url
        self.raw_xml = download(url)
        self.dom = minidom.parseString(self.raw_xml)
        self.links = self.dom.getElementsByTagName('link')

    def entries(self):
        ret = {}
        for element in self.dom.getElementsByTagName('entry'):
            title = element.getElementsByTagName('title')[0]
            print(title.toprettyxml())

    def __str__(self):
        return self.dom.toprettyxml()

feed_url = 'https://rickys-python-notes.blogspot.com/atom.xml?redirect=false&start-index=1&max-results=500'
feed = RSSFeed(feed_url)
dom = feed.dom
print(feedHow totries())


问:
Unparseable date: "Thu, 7 Dec 2017 07:40:40 "
I am getting the above exception while trying to parse. I tried the following date format,</p>

```<code>SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM  yyyy  HH:mm:ss ", Locale.ENGLISH);
</code>```

答:
it seems working fine with space as well...what exception you get?

```<code>import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SimpleDateFormatExample {
 public static void main(String[] args) {
  SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy  HH:mm:ss ",Locale.ENGLISH);
   String strDate= sdf.format(new Date());
   System.out.println(strDate);
 }
}
</code>```

Ouput:Fri, 08 Dec 2017  07:54:08

Body:
I am getting the above exception while trying to parse. I tried the following date format,

SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM  yyyy  HH:mm:ss ", Locale.ENGLISH);

Body:
it seems working fine with space as well...what exception you get?

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SimpleDateFormatExample {
 public static void main(String[] args) {
  SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy  HH:mm:ss ",Locale.ENGLISH);
   String strDate= sdf.format(new Date());
   System.out.println(strDate);
 }
}

Ouput:Fri, 08 Dec 2017  07:54:08


问:
webclient bugging out or what?
hi

I ran my project yesterday just fine, but today when I ran the same code it hangs on WebClient.DownloadFile() and eventually times out with this error message:

 "An unhandled exception of type 'System.Net.WebException' occurred in System.dll"

So I tried running only the webclient in a new project, downloading from a hardcoded url that I know is up like this.

```<code>static void Main(string[] args)
    {
        WebClient client = new WebClient();
        client.DownloadFile("http://www.ashersarlin.com/cartoons/officerap2.gif", "pic.gif");
    }
</code>```

Same thing happens. It creates an empty file "pic.gif" but times out eventually.

I could use some pointers. I'm new to .NET and have no idea how to troubleshoot this.

答:
Your exact code works for me...

Perhaps your default proxy is messed up?

Suggestions:

Print out the detail of the WebException - it may give more hints

Use Wireshark to see what's going on at the network level. That should show you if it's trying to connect, what it's getting back etc.

Title: webclient bugging out or what?

Body:
hi

I ran my project yesterday just fine, but today when I ran the same code it hangs on WebClient.DownloadFile() and eventually times out with this error message:

 "An unhandled exception of type 'System.Net.WebException' occurred in System.dll"

So I tried running only the webclient in a new project, downloading from a hardcoded url that I know is up like this.

static void Main(string[] args)
    {
        WebClient client = new WebClient();
        client.DownloadFile("http://www.ashersarlin.com/cartoons/officerap2.gif", "pic.gif");
    }

Same thing happens. It creates an empty file "pic.gif" but times out eventually.

I could use some pointers. I'm new to .NET and have no idea how to troubleshoot this.


问:
How to extend confluence autocomplete-content
I try to extend autocomplete-content macro by own logic witch should be call some rest.

I finded autocomplete-content.js file where autocomplete-content is defined, but I dont have idea how to extend it by own autocompleteModule.
I tried create own JS file as resource in own add-on, but it execute before autocomplete-content.js on confluence, and autocompleteContent object was undefined.

In the end I need to have own autocomplete tool with own rest service witch will be fatch data from other DB.

答:
If possible use AUI Select2.

Please note: AUI Select2 is based on older Select2. You have to refer to this documentation: http://select2.github.io/select2/

Something else would be to use QuickSearchDropDown

It is not really documented, but quite easy to use. Look for a file quicksearchdropdown.js in Confluence sources.

You can use it like this:

```<code>AJS.$('#myinput').quicksearch(URL_RELATIVE_TO_CONFLUENCE_BASE, false, {
            makeParams: function (params) {
                return {
                    username: params.term,
                    staticParam: 'blabla'
                };
            }
        }
</code>```

Body:
If possible use AUI Select2.

Please note: AUI Select2 is based on older Select2. You have to refer to this documentation: http://select2.github.io/select2/

Something else would be to use QuickSearchDropDown

It is not really documented, but quite easy to use. Look for a file quicksearchdropdown.js in Confluence sources.

You can use it like this:

AJS.$('#myinput').quicksearch(URL_RELATIVE_TO_CONFLUENCE_BASE, false, {
            makeParams: function (params) {
                return {
                    username: params.term,
                    staticParam: 'blabla'
                };
            }
        }


问:
[C++]Does NULL actually hold a specific address in memory as well?
My question comes up when I'm doing some linked list practice. My task here is to combine two linked lists into one, so I will first need to get the address of the last node of the first linked list and assign the first node of the second list to the next of the last node in my first linked list, namely

```<code>list1->last->next = list2->first;
</code>```

So we all know that, list1.last->next is NULL, and let's say what if I do:

```<code>Node * lastNext = list1->last->next;
lastNext = list2->first;
</code>```

Will this work?

Thanks guys!

答:
No, it will not work, and the reason why has nothing to do with NULL. It  has to do with the fact that all you're doing here is changing the value of a local pointer variable. You aren't affecting the list in any way. Specifically, you aren't changing the value of list->last->next.

If lastNext was a reference:

```<code>Node *&lastNext = list1->last->next;
</code>```

it would be a different matter. But it isn't. And NULL would still not come into play.

Body:
My question comes up when I'm doing some linked list practice. My task here is to combine two linked lists into one, so I will first need to get the address of the last node of the first linked list and assign the first node of the second list to the next of the last node in my first linked list, namely

list1->last->next = list2->first;

So we all know that, list1.last->next is NULL, and let's say what if I do:

Node * lastNext = list1->last->next;
lastNext = list2->first;

Will this work?

Thanks guys!

Body:
No, it will not work, and the reason why has nothing to do with NULL. It  has to do with the fact that all you're doing here is changing the value of a local pointer variable. You aren't affecting the list in any way. Specifically, you aren't changing the value of list->last->next.

If lastNext was a reference:

Node *&lastNext = list1->last->next;

it would be a different matter. But it isn't. And NULL would still not come into play.


Title: Changing time format in an array using moment and angularjs and lodash

Body:
I have Json data which has timings based on dates.

obj = {
"2017-12-08": [
    "2017-12-08T13:00:00+0530",
    "2017-12-08T15:00:00+0530",
    "2017-12-08T15:30:00+0530",
    "2017-12-08T16:00:00+0530"
],
"2017-12-09": [
    "2017-12-09T09:00:00+0530",
    "2017-12-09T09:30:00+0530",
    "2017-12-09T10:00:00+0530"
],
"2017-12-10": [
    "2017-12-10T09:00:00+0530",
    "2017-12-10T09:30:00+0530",
    "2017-12-10T10:00:00+0530",
    "2017-12-10T10:30:00+0530"
]
}

I want to convert this json object into the format below:

obj = {
"2017-12-08": ["13:00","15:00","15:30","16:00"],
"2017-12-09": ["09:00","09:30","10:00"],
"2017-12-10": ["09:00","09:30","10:00","10:30"]
}

Currently I'm using a for loop to traverse through each element in the array and then replace each element using

obj[Object.keys(obj)[date]][time]=moment(obj[Object.keys(obj)[date]][time]).format(HH:mm);

how do i accomplish this using lodash , moment and angularjs?

Body:
or you can use _.mapValues

const obj = {
  "2017-12-08": [
    "2017-12-08T13:00:00+0530",
    "2017-12-08T15:00:00+0530",
    "2017-12-08T15:30:00+0530",
    "2017-12-08T16:00:00+0530"
  ],
  "2017-12-09": [
    "2017-12-09T09:00:00+0530",
    "2017-12-09T09:30:00+0530",
    "2017-12-09T10:00:00+0530"
  ],
  "2017-12-10": [
    "2017-12-10T09:00:00+0530",
    "2017-12-10T09:30:00+0530",
    "2017-12-10T10:00:00+0530",
    "2017-12-10T10:30:00+0530"
  ]
};

const res = _.mapValues(obj, el => el.map(d => moment(d).format('HH:mm')));

console.log(res);

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"></script>


问:
After page refresh ngx-translate in angular4 is swiching back to english
I have switched my site language to spanish in angular4 using ngx-translate,so when i refresh the page it switches back to english language.
So,is there any way to keep spanish as a  language of my site,after i refresh the page using ngx-translate.</p>

答:
when you set your language spanish then store in localstore

Like ::

below code when you select switched your site language to spanish

```<code> this.translate.setDefaultLang('es');
 this.translate.use('es');
 this.localStorage.setItem("language","es");
</code>```

and below code when you first time set language

```<code>constructor(public translate: TranslateService) {
    if(localStorage.getItem('language')){
        translate.setDefaultLang(localStorage.getItem('language'));
        translate.use(localStorage.getItem('language'));
    }else {
         translate.setDefaultLang('en');
         translate.use('en');
         localStorage.setItem("language","en");
    }
}
</code>```

Body:
when you set your language spanish then store in localstore

Like ::

below code when you select switched your site language to spanish

 this.translate.setDefaultLang('es');
 this.translate.use('es');
 this.localStorage.setItem("language","es");

and below code when you first time set language

constructor(public translate: TranslateService) {
    if(localStorage.getItem('language')){
        translate.setDefaultLang(localStorage.getItem('language'));
        translate.use(localStorage.getItem('language'));
    }else {
         translate.setDefaultLang('en');
         translate.use('en');
         localStorage.setItem("language","en");
    }
}


问:
IllegalArgumentException or NullPointerException for a null parameter?
I have a simple setter method for a property and null is not appropriate for this particular property. I have always been torn in this situation: should I throw an IllegalArgumentException, or a NullPointerException? From the javadocs, both seem appropriate. Is there some kind of an understood standard?  Or is this just one of those things that you should do whatever you prefer and both are really correct?

答:
You should be using IllegalArgumentException (IAE), not NullPointerException (NPE) for the following reasons:

First, the NPE JavaDoc explicitly lists the cases where NPE is appropriate.  Notice that all of them are thrown by the runtime when null is used inappropriately.  In contrast, the IAE JavaDoc couldn't be more clear: "Thrown to indicate that a method has been passed an illegal or inappropriate argument."  Yup, that's you!

Second, when you see an NPE in a stack trace, what do you assume?  Probably that someone dereferenced a null.  When you see IAE, you assume the caller of the method at the top of the stack passed in an illegal value.  Again, the latter assumption is true, the former is misleading.

Third, since IAE is clearly designed for validating parameters, you have to assume it as the default choice of exception, so why would you choose NPE instead?  Certainly not for different behavior -- do you really expect calling code to catch NPE's separately from IAE and do something different as a result?  Are you trying to communicate a more specific error message?  But you can do that in the exception message text anyway, as you should for all other incorrect parameters.

Fourth, all other incorrect parameter data will be IAE, so why not be consistent?  Why is it that an illegal null is so special that it deserves a separate exception from all other types of illegal arguments?

Finally, I accept the argument given by other answers that parts of the Java API use NPE in this manner.  However, the Java API is inconsistent with everything from exception types to naming conventions, so I think just blindly copying (your favorite part of) the Java API isn't a good enough argument to trump these other considerations.

LastEditorDisplayName: Chris Fournier

OwnerDisplayName: Jason Cohen