问:
How to make code object oriented by removing if checks?
I have a windows service which checks for date and send notification remainder to user for a payment for which user has subcribed for a service.

Its a monthly payment service system for which user has to make a payment at the end of the month and for that system sends 2 remainder notification to user :

1) Before N days from deadline if payment not made.

2) Send remainder on deadline if payment not received.

So below are the conditions based on which notifications are send to User as well as Administrator :

Code :

```<code>public enum PaymentStatusEnum
 {
    Ask_For_Payment = 0,
    Payment_Remainder_Sent = 1,
    Full_Payment_Done = 2,
    Payment_Not_Done = 3,
 }

public class ServicePaymentModel
{
    public int PaymentId { get; set; }
    public string Email { get; set; }
    public int PaymentStatus { get; set; }
    public string AdminId { get; set; }
    public int NoOfDaysPassed { get; set; }
    public decimal DueAmount { get; set; }
    public decimal PaymentMade { get; set; }
}

 public void SendNotification()
 {
    int daysBeforeDeadline = 10;
    int deadlineDays = 20;
    var paymentModel = new PaymentModel
    {
        Today = 10/5/2019,
        DaysBeforeDeadline = daysBeforeDeadline,
        DeadlineDays = deadlineDays
    };
    //Get all the payments whose daysBeforeDeadline or deadlineDays condition is met.
    //For eg: If some users subscription started from 1/5/2019 and Todays date is 10/5/2019 then this users will be will be fetched because of daysBeforeDeadline.
    //For eg: If some users subscription started from 20/4/2019 and Todays date is 10/5/2019 then this users will be will be fetched because deadlineDays condition
    List<ServicePaymentModel> payments = MyRepo.GetPayments(paymentModel);
    if (payments != null && payments.Count == 0)
        return;
    UserPayment userPayment = null;
    foreach (var payment in payments)
    {
      try
      {
        if (payment.DueAmount > 0) //Payment not done
        {
            if (paymentModel.DeadlineDays == payment.NoOfDaysPassed
                            && payment.PaymentStatus == (int)PaymentStatusEnum.Payment_Remainder_Sent) // payment not made on deadline
            {
                userPayment = new UserPayment
                {
                    PaymentId = payment.Id,
                    PaymentStatus = (int)PaymentStatusEnum.Payment_Not_Done
                }
                SendNotificationToUser(payment);//method handles email sending and different email template for user
                SendNotificationToAdmin(payment)//method handles email sending and different email template for Admin telling him about which user payment has not been received
            }
            else if (paymentModel.DaysBeforeDeadline == payment.NoOfDaysPassed
                            && payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)//payment not done after N days
            {
                userPayment = new UserPayment
                {
                    PaymentId = payment.Id,
                    PaymentStatus = (int)PaymentStatusEnum.Payment_Remainder_Sent
                }
                SendNotificationToUser(payment);//method handles email sending and different email template for user
                SendNotificationToAdmin(payment)//method handles email sending and different email template for Admin telling him about which user payment has not been received
            }
        }
        else if (payment.DueAmount == 0) // payment done
        {
            userPayment = new UserPayment
            {
              PaymentId = payment.Id,
              PaymentStatus = (int)PaymentStatusEnum.Full_Payment_Done
            }
            if ((paymentModel.DeadlineDays == payment.NoOfDaysPassed
                           && payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)// payment made on deadline
            {

                SendNotificationToUser(payment);//method handles email sending and different email template for user along with message and body
                SendNotificationToAdmin(payment)//method handles email sending and different email template for admin along with message and body
            }
            else if (paymentModel.DaysBeforeDeadline == payment.NoOfDaysPassed
                           && payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)//payment done before XX days
            {
               SendNotificationToAdmin(payment)//method handles email sending and different email template for admin along with message and body
            }
        }
        PaymentRepo.UpdateUserPaymentStatus(userPayment);
     }
     catch (Exception ex)
     {
        //do nothing and continue processing other payment
     }
    }
  }
</code>```

I have seen this Plural sight video where Author - Zoran Horvat is saying that we can turn almost any If checks to object oriented solution and as you can see my code contains alot of if checks and tomorrow if more Conditions are added than this If will grow tremendously creating maintainance night mare.

All my Conditions and PaymentStatus are being handled based on If checks but here I am not getting how to turn this if conditions in to object oriented solution and whether it would be really possible or not in this case.

So is it possible to make this code object oriented by removing if checks or any better way to handle this checks?

```<code>public void SendNotificationRefactor2()
{
    int daysBeforeDeadline = 10;
    int deadlineDays = 20;
    var paymentModel = new PaymentModel
    {
        Today = 10 / 5 / 2019,
        DaysBeforeDeadline = daysBeforeDeadline,
        DeadlineDays = deadlineDays
    };
    //Get all the payments whose daysBeforeDeadline or deadlineDays condition is met.
    //For eg: If some users subscription started from 1/5/2019 and Todays date is 10/5/2019 then this users will be will be fetched because of daysBeforeDeadline.
    //For eg: If some users subscription started from 20/4/2019 and Todays date is 10/5/2019 then this users will be will be fetched because deadlineDays condition
    List<ServicePaymentModel> payments = MyRepo.GetPayments(paymentModel);
    if (payments != null && payments.Count == 0)
        return;
    //UserPayment userPayment = null;

    foreach (var payment in payments)
    {
        try
        {
            //  Breaking this out into a method is optional, really, because there's little chance it'll
            HandlePayment(paymentModel, payment);
        }
        catch (Exception ex)
        {
            //  SWALLOWING EXCEPTIONS IS AN INDESCRIBABLY BAD IDEA. DON'T DO THIS.
        }
    }
}

protected void HandlePayment(PaymentModel paymentModel, ServicePaymentModel payment)
{
    var userPayment = new UserPayment
    {
        PaymentId = payment.Id
    };

    if (payment.DueAmount > 0) //Payment not done
    {
        if (paymentModel.DeadlineDays == payment.NoOfDaysPassed)
        {
            if (payment.PaymentStatus == (int)PaymentStatusEnum.Payment_Remainder_Sent)
            {
                userPayment.PaymentStatus = (int)PaymentStatusEnum.Payment_Not_Done;
            }
            else if (payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)//payment not done after N days
            {
                userPayment.PaymentStatus = (int)PaymentStatusEnum.Payment_Remainder_Sent;
            }

            SendNotificationToUser(payment);//method handles email sending and different email template for user
            SendNotificationToAdmin(payment);//method handles email sending and different email template for Admin telling him about which user payment has not been received
        }
    }
    else if (payment.DueAmount == 0) // payment done
    {
        userPayment.PaymentStatus = (int)PaymentStatusEnum.Full_Payment_Done;

        if (paymentModel.DeadlineDays == payment.NoOfDaysPassed)
        {
            if (payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)
            {
                SendNotificationToUser(payment);//method handles email sending and different email template for user along with message and body
                SendNotificationToAdmin(payment);//method handles email sending and different email template for admin along with message and body
            }
            else if (payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)
            {
                SendNotificationToAdmin(payment);//method handles email sending and different email template for admin along with message and body
            }
        }
    }

    PaymentRepo.UpdateUserPaymentStatus(userPayment);
}
</code>```

答:
First off: focus on the goal. The belief that making something more OO makes it better is a belief structure I call "object happiness disorder". Remember, the purpose of OO code is to lower the costs of large programs worked on by large teams, by making it very clear what service is provided by a piece of code, what its public interface is, and how it interacts with other components. It's not a general-purpose technique for making small code better.

Your goal should not be to make the program "more OO"; it should be to make it lower cost, so ask yourself "what are the costs associated with this program?"  Where are you spending money, remembering that your salary is probably most of that money?

For example:

We're spending too much time updating the code when business processes change.

If that's the problem then I would make the program more OO, but not by "replace condition with polymorphism". Just because it is polymorphic does not make it OO. What makes it OO is we have identified fundamental concepts in the business domain and encapsulated those concepts into objects that only have to change when the business process changes.

The key thing to look at is your extremely helpful diagram that shows:

What exogenous condition triggers a state change?

What are the state changes?

What action is associated with a state change?

So, codify that. Make a base class EventTrigger. You've already got a type representing states. Make a class called EventAction. Make a class Condition. And now what is our process?

```<code>for each trigger in eventTriggers
    if any trigger condition is met
        execute all trigger actions
</code>```

Now we're down to a single if statement, like you wanted. Now you can write one class for each condition, and one class for each action, and triggers tie them together.

If you want to change the action associated with a particular trigger, you change it in one place, not in a mass of spaghetti code.

Also, this technique is amenable to many other improvements. You can easily add logging; logging is just another action. You can make compositions of actions; make an action that takes two actions and runs them both. And so on.

You could even make a configuration document that looks like:

```<code>TRIGGER PaymentReceivedTrigger HAS CONDITION AskForPayment WITH ACTIONS  SetFullPayment, EmailAdmin
…
</code>```

And now you can set up your whole system based on a config file instead of writing C# code.

But what if that is not the problem? What if the problem is:

We're spending too much time tracking down bugs

Or

Our performance is bad and we do not know why

Or

We're completely tied to one database vendor but they are too expensive; how can we lower the cost of switching back ends?

Or any of a million other things?  In those cases, you don't want to waste any time building an OO business process engine; you want to concentrate on the problem that is actually costing you money, and figure out what lowers that cost.

Body:
I have a windows service which checks for date and send notification remainder to user for a payment for which user has subcribed for a service.

Its a monthly payment service system for which user has to make a payment at the end of the month and for that system sends 2 remainder notification to user :

1) Before N days from deadline if payment not made.

2) Send remainder on deadline if payment not received.

So below are the conditions based on which notifications are send to User as well as Administrator :

Code :

public enum PaymentStatusEnum
 {
    Ask_For_Payment = 0,
    Payment_Remainder_Sent = 1,
    Full_Payment_Done = 2,
    Payment_Not_Done = 3,
 }

public class ServicePaymentModel
{
    public int PaymentId { get; set; }
    public string Email { get; set; }
    public int PaymentStatus { get; set; }
    public string AdminId { get; set; }
    public int NoOfDaysPassed { get; set; }
    public decimal DueAmount { get; set; }
    public decimal PaymentMade { get; set; }
}

 public void SendNotification()
 {
    int daysBeforeDeadline = 10;
    int deadlineDays = 20;
    var paymentModel = new PaymentModel
    {
        Today = 10/5/2019,
        DaysBeforeDeadline = daysBeforeDeadline,
        DeadlineDays = deadlineDays
    };
    //Get all the payments whose daysBeforeDeadline or deadlineDays condition is met.
    //For eg: If some users subscription started from 1/5/2019 and Todays date is 10/5/2019 then this users will be will be fetched because of daysBeforeDeadline.
    //For eg: If some users subscription started from 20/4/2019 and Todays date is 10/5/2019 then this users will be will be fetched because deadlineDays condition
    List<ServicePaymentModel> payments = MyRepo.GetPayments(paymentModel);
    if (payments != null && payments.Count == 0)
        return;
    UserPayment userPayment = null;
    foreach (var payment in payments)
    {
      try
      {
        if (payment.DueAmount > 0) //Payment not done
        {
            if (paymentModel.DeadlineDays == payment.NoOfDaysPassed
                            && payment.PaymentStatus == (int)PaymentStatusEnum.Payment_Remainder_Sent) // payment not made on deadline
            {
                userPayment = new UserPayment
                {
                    PaymentId = payment.Id,
                    PaymentStatus = (int)PaymentStatusEnum.Payment_Not_Done
                }
                SendNotificationToUser(payment);//method handles email sending and different email template for user
                SendNotificationToAdmin(payment)//method handles email sending and different email template for Admin telling him about which user payment has not been received
            }
            else if (paymentModel.DaysBeforeDeadline == payment.NoOfDaysPassed
                            && payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)//payment not done after N days
            {
                userPayment = new UserPayment
                {
                    PaymentId = payment.Id,
                    PaymentStatus = (int)PaymentStatusEnum.Payment_Remainder_Sent
                }
                SendNotificationToUser(payment);//method handles email sending and different email template for user
                SendNotificationToAdmin(payment)//method handles email sending and different email template for Admin telling him about which user payment has not been received
            }
        }
        else if (payment.DueAmount == 0) // payment done
        {
            userPayment = new UserPayment
            {
              PaymentId = payment.Id,
              PaymentStatus = (int)PaymentStatusEnum.Full_Payment_Done
            }
            if ((paymentModel.DeadlineDays == payment.NoOfDaysPassed
                           && payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)// payment made on deadline
            {

                SendNotificationToUser(payment);//method handles email sending and different email template for user along with message and body
                SendNotificationToAdmin(payment)//method handles email sending and different email template for admin along with message and body
            }
            else if (paymentModel.DaysBeforeDeadline == payment.NoOfDaysPassed
                           && payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)//payment done before XX days
            {
               SendNotificationToAdmin(payment)//method handles email sending and different email template for admin along with message and body
            }
        }
        PaymentRepo.UpdateUserPaymentStatus(userPayment);
     }
     catch (Exception ex)
     {
        //do nothing and continue processing other payment
     }
    }
  }

I have seen this Plural sight video where Author - Zoran Horvat is saying that we can turn almost any If checks to object oriented solution and as you can see my code contains alot of if checks and tomorrow if more Conditions are added than this If will grow tremendously creating maintainance night mare.

All my Conditions and PaymentStatus are being handled based on If checks but here I am not getting how to turn this if conditions in to object oriented solution and whether it would be really possible or not in this case.

So is it possible to make this code object oriented by removing if checks or any better way to handle this checks?

public void SendNotificationRefactor2()
{
    int daysBeforeDeadline = 10;
    int deadlineDays = 20;
    var paymentModel = new PaymentModel
    {
        Today = 10 / 5 / 2019,
        DaysBeforeDeadline = daysBeforeDeadline,
        DeadlineDays = deadlineDays
    };
    //Get all the payments whose daysBeforeDeadline or deadlineDays condition is met.
    //For eg: If some users subscription started from 1/5/2019 and Todays date is 10/5/2019 then this users will be will be fetched because of daysBeforeDeadline.
    //For eg: If some users subscription started from 20/4/2019 and Todays date is 10/5/2019 then this users will be will be fetched because deadlineDays condition
    List<ServicePaymentModel> payments = MyRepo.GetPayments(paymentModel);
    if (payments != null && payments.Count == 0)
        return;
    //UserPayment userPayment = null;

    foreach (var payment in payments)
    {
        try
        {
            //  Breaking this out into a method is optional, really, because there's little chance it'll
            HandlePayment(paymentModel, payment);
        }
        catch (Exception ex)
        {
            //  SWALLOWING EXCEPTIONS IS AN INDESCRIBABLY BAD IDEA. DON'T DO THIS.
        }
    }
}

protected void HandlePayment(PaymentModel paymentModel, ServicePaymentModel payment)
{
    var userPayment = new UserPayment
    {
        PaymentId = payment.Id
    };

    if (payment.DueAmount > 0) //Payment not done
    {
        if (paymentModel.DeadlineDays == payment.NoOfDaysPassed)
        {
            if (payment.PaymentStatus == (int)PaymentStatusEnum.Payment_Remainder_Sent)
            {
                userPayment.PaymentStatus = (int)PaymentStatusEnum.Payment_Not_Done;
            }
            else if (payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)//payment not done after N days
            {
                userPayment.PaymentStatus = (int)PaymentStatusEnum.Payment_Remainder_Sent;
            }

            SendNotificationToUser(payment);//method handles email sending and different email template for user
            SendNotificationToAdmin(payment);//method handles email sending and different email template for Admin telling him about which user payment has not been received
        }
    }
    else if (payment.DueAmount == 0) // payment done
    {
        userPayment.PaymentStatus = (int)PaymentStatusEnum.Full_Payment_Done;

        if (paymentModel.DeadlineDays == payment.NoOfDaysPassed)
        {
            if (payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)
            {
                SendNotificationToUser(payment);//method handles email sending and different email template for user along with message and body
                SendNotificationToAdmin(payment);//method handles email sending and different email template for admin along with message and body
            }
            else if (payment.PaymentStatus == (int)PaymentStatusEnum.Ask_For_Payment)
            {
                SendNotificationToAdmin(payment);//method handles email sending and different email template for admin along with message and body
            }
        }
    }

    PaymentRepo.UpdateUserPaymentStatus(userPayment);
}

Body:
First off: focus on the goal. The belief that making something more OO makes it better is a belief structure I call "object happiness disorder". Remember, the purpose of OO code is to lower the costs of large programs worked on by large teams, by making it very clear what service is provided by a piece of code, what its public interface is, and how it interacts with other components. It's not a general-purpose technique for making small code better.

Your goal should not be to make the program "more OO"; it should be to make it lower cost, so ask yourself "what are the costs associated with this program?"  Where are you spending money, remembering that your salary is probably most of that money?

For example:

We're spending too much time updating the code when business processes change.

If that's the problem then I would make the program more OO, but not by "replace condition with polymorphism". Just because it is polymorphic does not make it OO. What makes it OO is we have identified fundamental concepts in the business domain and encapsulated those concepts into objects that only have to change when the business process changes.

The key thing to look at is your extremely helpful diagram that shows:

What exogenous condition triggers a state change?

What are the state changes?

What action is associated with a state change?

So, codify that. Make a base class EventTrigger. You've already got a type representing states. Make a class called EventAction. Make a class Condition. And now what is our process?

for each trigger in eventTriggers
    if any trigger condition is met
        execute all trigger actions

Now we're down to a single if statement, like you wanted. Now you can write one class for each condition, and one class for each action, and triggers tie them together.

If you want to change the action associated with a particular trigger, you change it in one place, not in a mass of spaghetti code.

Also, this technique is amenable to many other improvements. You can easily add logging; logging is just another action. You can make compositions of actions; make an action that takes two actions and runs them both. And so on.

You could even make a configuration document that looks like:

TRIGGER PaymentReceivedTrigger HAS CONDITION AskForPayment WITH ACTIONS  SetFullPayment, EmailAdmin
…

And now you can set up your whole system based on a config file instead of writing C# code.

But what if that is not the problem? What if the problem is:

We're spending too much time tracking down bugs

Or

Our performance is bad and we do not know why

Or

We're completely tied to one database vendor but they are too expensive; how can we lower the cost of switching back ends?

Or any of a million other things?  In those cases, you don't want to waste any time building an OO business process engine; you want to concentrate on the problem that is actually costing you money, and figure out what lowers that cost.


来源: stackexchange

问:
Unity 3D: what is the correct way to detect that the collision has already been processed for another collision participant?
I have a class CollisionHandler which has the OnCollisionEnter method. Each collideable entity in the game has CollisionHandler as a component. So, when 2 objects collide the OnCollisionEnter method is called twice and it's ok because the damage and other things are processed as a result of touching object "B" by object "A" and vice versa.

In addition, each collision creates a flash effect and plays a sound of impact and of course, these effects are also played twice for each collision. Although it wouldn't be imperceptible to the player it doesn't seem to be correct anyway. In order to prevent it, I came up with the following solution: I save the current frame number in another collision participant so it will know that these effects have been played already by the first one.

```<code>private void OnCollisionEnter(Collision collision)
{
    // Calculate the damage caused by `this.gameObject` to `collision.gameObject`.
    // ...

    // Play an impact sound and show a visual effect.
    if (thisObject.CollisionFrameId != Time.frameCount)
    {
        otherObject.CollisionFrameId = Time.frameCount;
        // play sound
        // show hit effect
    }
}
</code>```

Although it works I'm not sure (I'm a novice in Unity) that it's the best practice and if so please suggest other possible solutions.

Note that I didn't ask "Why is OnCollisionEnter getting called twice?". I know why it happens. My question is about the other, though it does mention the name of the same function it still doesn't asks the same.

答:
You can use the Unity Tag System, you tag action to occur when colliding with that specific tagged object.

As example:

```<code>internal void OnTriggerEnter(Collider other)    {

        if (other.gameObject.tag == "Oject Tag") {
            this.GetComponent<AudioSource> ().PlayOneShot (objectTagSoundClip);
        }
</code>```

Just need a audio to play placed in game object.

ContentLicense: CC BY-SA 4.0

Body:
I have a class CollisionHandler which has the OnCollisionEnter method. Each collideable entity in the game has CollisionHandler as a component. So, when 2 objects collide the OnCollisionEnter method is called twice and it's ok because the damage and other things are processed as a result of touching object "B" by object "A" and vice versa.

In addition, each collision creates a flash effect and plays a sound of impact and of course, these effects are also played twice for each collision. Although it wouldn't be imperceptible to the player it doesn't seem to be correct anyway. In order to prevent it, I came up with the following solution: I save the current frame number in another collision participant so it will know that these effects have been played already by the first one.

private void OnCollisionEnter(Collision collision)
{
    // Calculate the damage caused by `this.gameObject` to `collision.gameObject`.
    // ...

    // Play an impact sound and show a visual effect.
    if (thisObject.CollisionFrameId != Time.frameCount)
    {
        otherObject.CollisionFrameId = Time.frameCount;
        // play sound
        // show hit effect
    }
}

Although it works I'm not sure (I'm a novice in Unity) that it's the best practice and if so please suggest other possible solutions.

Note that I didn't ask "Why is OnCollisionEnter getting called twice?". I know why it happens. My question is about the other, though it does mention the name of the same function it still doesn't asks the same.

Body:
You can use the Unity Tag System, you tag action to occur when colliding with that specific tagged object.

As example:

internal void OnTriggerEnter(Collider other)    {

        if (other.gameObject.tag == "Oject Tag") {
            this.GetComponent<AudioSource> ().PlayOneShot (objectTagSoundClip);
        }

Just need a audio to play placed in game object.


问:
Tuple swap with indexOf
I'm trying to swap positions of elements in this array with a tuple swap and indexOf()

```<code>array1 = [1, 2, 3, 4, 5, 6, 7, 8]
</code>```

should equal:  [1, 2, 4, 3, 5, 6, 7, 8]

```<code>[ array1[array1.indexOf(3)], array1[array1.indexOf(4)] ] =

[ array1[array1.indexOf(4)], array1[array1.indexOf(3)] ]

</code>```

the evaluated result is simply the swapped elements and not the array itself..

```<code>[4, 3]
</code>```

How can I get the whole array back?

答:
Try this:

```<code>const index1 = array1.indexOf(3);
const index2 = array1.indexOf(4);

[ array1[index1], array1[index2] ] = [ array1[index2], array1[index1] ];
</code>```

Demo:

const array1 = [1, 2, 3, 4, 5, 6, 7, 8];

console.log('array1 before: ', array1);

const index1 = array1.indexOf(3);
const index2 = array1.indexOf(4);

[ array1[index1], array1[index2] ] = [ array1[index2], array1[index1] ];

console.log('array1 after: ',array1);```

Title: Tuple swap with indexOf

Body:
I'm trying to swap positions of elements in this array with a tuple swap and indexOf()

array1 = [1, 2, 3, 4, 5, 6, 7, 8]

should equal:  [1, 2, 4, 3, 5, 6, 7, 8]

[ array1[array1.indexOf(3)], array1[array1.indexOf(4)] ] =

[ array1[array1.indexOf(4)], array1[array1.indexOf(3)] ]

the evaluated result is simply the swapped elements and not the array itself..

[4, 3]

How can I get the whole array back?

Body:
Try this:

const index1 = array1.indexOf(3);
const index2 = array1.indexOf(4);

[ array1[index1], array1[index2] ] = [ array1[index2], array1[index1] ];

Demo:

const array1 = [1, 2, 3, 4, 5, 6, 7, 8];

console.log('array1 before: ', array1);

const index1 = array1.indexOf(3);
const index2 = array1.indexOf(4);

[ array1[index1], array1[index2] ] = [ array1[index2], array1[index1] ];

console.log('array1 after: ',array1);


问:
Reading file with alphabetic letters only
I am stuck on a small part of a task I am trying to complete and each word must be trimmed so that a word contains only alphabetic letters when I read from a .txt file. This is apart of an AVL tree yes but the problem I believe lies within the reading of the text document.

I have tried ise isalpha but can not get it to work and have run out of ideas and am stuck in a situation here. I will appreciate any help given to me!

```<code>           cout << "Input a file name (dictionary.txt):" << endl;
            cin >> file;
            myfile.open(file);
            if (!myfile) {
                cout << "\nFile does not exist." << endl;
                return 0;
            }
            else cout << "\nDictionary has been loaded." << endl;
            while(!myfile.eof()) {
                myfile >> insert;
                DATA newItem;
                newItem.key = insert;
                tree.AVL_Insert(newItem);
                count++;
            }
</code>```

答:
The algorithm library makes this easy:

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

int main ()
{
    std::string s = "A1B2C3";
    s.erase (std::remove_if (s.begin (), s.end (), [] (auto c) { return !std::isalpha ((unsigned char) c); }), s.end ());
    std::cout << s;
}
</code>```

Output:

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

Live demo

See also erase remove idiom

Body:
I am stuck on a small part of a task I am trying to complete and each word must be trimmed so that a word contains only alphabetic letters when I read from a .txt file. This is apart of an AVL tree yes but the problem I believe lies within the reading of the text document.

I have tried ise isalpha but can not get it to work and have run out of ideas and am stuck in a situation here. I will appreciate any help given to me!

           cout << "Input a file name (dictionary.txt):" << endl;
            cin >> file;
            myfile.open(file);
            if (!myfile) {
                cout << "\nFile does not exist." << endl;
                return 0;
            }
            else cout << "\nDictionary has been loaded." << endl;
            while(!myfile.eof()) {
                myfile >> insert;
                DATA newItem;
                newItem.key = insert;
                tree.AVL_Insert(newItem);
                count++;
            }

Body:
The algorithm library makes this easy:

#include <iostream>
#include <string>
#include <algorithm>

int main ()
{
    std::string s = "A1B2C3";
    s.erase (std::remove_if (s.begin (), s.end (), [] (auto c) { return !std::isalpha ((unsigned char) c); }), s.end ());
    std::cout << s;
}

Output:

ABC

Live demo

See also erase remove idiom


问:
Serial.read returning values that differ from the one in the Serial Monitor
Goal: I would like to prompt an integer from the serial monitor. These values will be used as part of a delay(value) command later on. The goal of this delay is to play two vibration motors slightly out of sync.

Issue: I'm trying to get values such as 60 or 400 from the command line. The current values do not match what is input.

My gut says this is a data format issue. I'm hoping someone can help me understand why each digit is printing as a number.

Prompt Subroutine Code:

```<code>  while (!Serial.available()) {       //this holds until we see a serial prompt
    }
  if (Serial.available() > 0) {
    uint8_t inChar = Serial.read();
    Serial.println(inChar);
    // convert the incoming byte to a char and add it to the string:
    if (isDigit(inChar)) {
      receivedChar += (char)inChar;
    }

    // if you get a newline, print the string, then the string's value:
    if (inChar == '\n') {
      Serial.print("Delay Value:");
      Serial.println(receivedChar.toInt());
      Serial.print("String: ");
      Serial.println(receivedChar);
      // clear the string for new input:
    }
    newData = true;
    prompthold = false;
  }
}
</code>```

Loop Code:

```<code>  void loop(){
    while (prompthold == false) {
      prompthold = true;

      Serial.println("Please enter delay");
      receivedChar = "";
      srl_prompt();
      apparentmotion();
    }

    delay(500);

  }
</code>```

Diagnostic Info:
Input of 1234567890

Returns:

```<code>16:28:13.079 -> 49
16:28:13.079 -> Please enter delay
16:28:13.079 -> 50
16:28:13.079 -> Please enter delay
16:28:13.079 -> 51
16:28:13.079 -> Please enter delay
16:28:13.079 -> 52
16:28:13.079 -> Please enter delay
16:28:13.079 -> 53
16:28:13.113 -> Please enter delay
16:28:13.113 -> 54
16:28:13.113 -> Please enter delay
16:28:13.113 -> 55
16:28:13.113 -> Please enter delay
16:28:13.113 -> 56
16:28:13.147 -> Please enter delay
16:28:13.147 -> 57
16:28:13.147 -> Please enter delay
16:28:13.147 -> 48
16:28:13.147 -> Please enter delay
16:28:13.147 -> 10
16:28:13.147 -> Delay Value:0
16:28:13.147 -> String:
16:28:13.147 -> Please enter delay
</code>```

Input of 200

```<code>16:29:06.082 -> Please enter delay
16:34:02.121 -> 50
16:34:02.121 -> Please enter delay
16:34:02.121 -> 48
16:34:02.155 -> Please enter delay
16:34:02.155 -> 48
16:34:02.155 -> Please enter delay
16:34:02.155 -> 10
16:34:02.155 -> Delay Value:0
16:34:02.155 -> String:
16:34:02.155 -> Please enter delay

</code>```

答:
Ok, I've solved this. If you use Serial.read() you get string/ASCII. If you use Serial.parseInt() you'll get a value. Updated code is below:</p>

```<code>void srl_prompt() {
  while (!Serial.available()) {       //this holds until we see a serial prompt
    }
  if (Serial.available() > 0) {
    uint8_t inChar = Serial.parseInt();
    Serial.println(inChar);
    // convert the incoming byte to a char and add it to the string:
    if (isDigit(inChar)) {
      receivedChar += (char)inChar;
    }

    // if you get a newline, print the string, then the string's value:
    if (inChar == '\n') {
      Serial.print("Delay Value:");
      Serial.println(receivedChar.toInt());
      Serial.print("String: ");
      Serial.println(receivedChar);
      // clear the string for new input:
    }
    newData = true;
    prompthold = false;
  }
}
</code>```

Body:
Goal: I would like to prompt an integer from the serial monitor. These values will be used as part of a delay(value) command later on. The goal of this delay is to play two vibration motors slightly out of sync.

Issue: I'm trying to get values such as 60 or 400 from the command line. The current values do not match what is input.

My gut says this is a data format issue. I'm hoping someone can help me understand why each digit is printing as a number.

Prompt Subroutine Code:

  while (!Serial.available()) {       //this holds until we see a serial prompt
    }
  if (Serial.available() > 0) {
    uint8_t inChar = Serial.read();
    Serial.println(inChar);
    // convert the incoming byte to a char and add it to the string:
    if (isDigit(inChar)) {
      receivedChar += (char)inChar;
    }

    // if you get a newline, print the string, then the string's value:
    if (inChar == '\n') {
      Serial.print("Delay Value:");
      Serial.println(receivedChar.toInt());
      Serial.print("String: ");
      Serial.println(receivedChar);
      // clear the string for new input:
    }
    newData = true;
    prompthold = false;
  }
}

Loop Code:

  void loop(){
    while (prompthold == false) {
      prompthold = true;

      Serial.println("Please enter delay");
      receivedChar = "";
      srl_prompt();
      apparentmotion();
    }

    delay(500);

  }

Diagnostic Info:
Input of 1234567890

Returns:

16:28:13.079 -> 49
16:28:13.079 -> Please enter delay
16:28:13.079 -> 50
16:28:13.079 -> Please enter delay
16:28:13.079 -> 51
16:28:13.079 -> Please enter delay
16:28:13.079 -> 52
16:28:13.079 -> Please enter delay
16:28:13.079 -> 53
16:28:13.113 -> Please enter delay
16:28:13.113 -> 54
16:28:13.113 -> Please enter delay
16:28:13.113 -> 55
16:28:13.113 -> Please enter delay
16:28:13.113 -> 56
16:28:13.147 -> Please enter delay
16:28:13.147 -> 57
16:28:13.147 -> Please enter delay
16:28:13.147 -> 48
16:28:13.147 -> Please enter delay
16:28:13.147 -> 10
16:28:13.147 -> Delay Value:0
16:28:13.147 -> String:
16:28:13.147 -> Please enter delay

Input of 200

16:29:06.082 -> Please enter delay
16:34:02.121 -> 50
16:34:02.121 -> Please enter delay
16:34:02.121 -> 48
16:34:02.155 -> Please enter delay
16:34:02.155 -> 48
16:34:02.155 -> Please enter delay
16:34:02.155 -> 10
16:34:02.155 -> Delay Value:0
16:34:02.155 -> String:
16:34:02.155 -> Please enter delay

Body:
Ok, I've solved this. If you use Serial.read() you get string/ASCII. If you use Serial.parseInt() you'll get a value. Updated code is below:

void srl_prompt() {
  while (!Serial.available()) {       //this holds until we see a serial prompt
    }
  if (Serial.available() > 0) {
    uint8_t inChar = Serial.parseInt();
    Serial.println(inChar);
    // convert the incoming byte to a char and add it to the string:
    if (isDigit(inChar)) {
      receivedChar += (char)inChar;
    }

    // if you get a newline, print the string, then the string's value:
    if (inChar == '\n') {
      Serial.print("Delay Value:");
      Serial.println(receivedChar.toInt());
      Serial.print("String: ");
      Serial.println(receivedChar);
      // clear the string for new input:
    }
    newData = true;
    prompthold = false;
  }
}


问:
How to prevent FCM from converting nested json objects to string in Data Message notifications in react-native
I'm using firebase in my react-native project (with typescript), I set up all thing correctly and it works fine with data messages like below:

```<code>{
  "to": "fcm-token",

  "data": {
    "field1": "value1",
    "field2": "value1",
    "field3": "value1"
  }
}
</code>```

in my App, I can access my data using data filed of RemoteMessage like below:

```<code>const data: MyDataType = remoteMessage.data;
const {/* destructed fields */} = data;
</code>```

But when my server send nested Object to FCM server, it converts them to string and so I can not access them directly like above.

this is what my server send to FCM server:

```<code>{
  "to": "fcm-token",

  "data": {
    "field1": {
      "subfield1": "subvalue1",
      "subfield2": "subvalue2",
    },
    "field2": "value1",
    "field3": "value1"
  }
}
</code>```

and this is what I get in my application:

```<code>{
  "to": "fcm-token",

  "data": {
    "field1": "{"subfield1": "subvalue1","subfield2": "subvalue2"}", <--- the problem is here, it must be a nested object not string
    "field2": "value1",
    "field3": "value1"
  }
}
</code>```

I set Content-Type header to application/json in my server post requests, so I don't think there is any problem with my headers.

Am I doing something wrong? How can I prevent FCM from converting my nested objects?

答:
If you look at the documentation for message type in the REST API, you'll see that data is declared as:

```<code>"data": {
  string: string,
  ...
},
</code>```

So the data field can only hold string values, not more complex objects.

If you want to store more complex values, encode them as a string first and then decode them on the client, for example with JSON.stringify() and JSON.parse().

Body:
I'm using firebase in my react-native project (with typescript), I set up all thing correctly and it works fine with data messages like below:

{
  "to": "fcm-token",

  "data": {
    "field1": "value1",
    "field2": "value1",
    "field3": "value1"
  }
}

in my App, I can access my data using data filed of RemoteMessage like below:

const data: MyDataType = remoteMessage.data;
const {/* destructed fields */} = data;

But when my server send nested Object to FCM server, it converts them to string and so I can not access them directly like above.

this is what my server send to FCM server:

{
  "to": "fcm-token",

  "data": {
    "field1": {
      "subfield1": "subvalue1",
      "subfield2": "subvalue2",
    },
    "field2": "value1",
    "field3": "value1"
  }
}

and this is what I get in my application:

{
  "to": "fcm-token",

  "data": {
    "field1": "{"subfield1": "subvalue1","subfield2": "subvalue2"}", <--- the problem is here, it must be a nested object not string
    "field2": "value1",
    "field3": "value1"
  }
}

I set Content-Type header to application/json in my server post requests, so I don't think there is any problem with my headers.

Am I doing something wrong? How can I prevent FCM from converting my nested objects?

Body:
If you look at the documentation for message type in the REST API, you'll see that data is declared as:

"data": {
  string: string,
  ...
},

So the data field can only hold string values, not more complex objects.

If you want to store more complex values, encode them as a string first and then decode them on the client, for example with JSON.stringify() and JSON.parse().


问:
Python Requests - Use navigate site by servers IP
I want to crawl a site, however cloudflare was getting in the way. I was able to get the servers IP, so cloudflare won't bother me.

How can I utilize this in the requests library?

For example, I want to go directly to
www.example.com/foo.php, but in requests it will resolve the IP on the cloudflare network instead of the one I want it to use. How can I make it use the one I want it to use?

I would of sent in a request so the real IP with the host set as the www.example.com, but that will just give me the home page. How can I visit other links on the site?

答:
Answer for HTTPS/SNI support: Use the HostHeaderSSLAdapter in the requests_toolbelt module:

The above solution works fine with virtualhosts for non-encrypted HTTP connections.  For HTTPS you also need to pass SNI (Server Name Identification) in the TLS header which as some servers will present a different SSL certificate depending on what is passed in via SNI.  Also, the python ssl libraries by default don't look at the Host: header to match the server connection at connection time.

The above provides a straight-forward for adding a transport adapter to requests that handles this for you.

Example

```<code>import requests

from requests_toolbelt.adapters import host_header_ssl

# Create a new requests session
s = requests.Session()

# Mount the adapter for https URLs
s.mount('https://', host_header_ssl.HostHeaderSSLAdapter())

# Send your request
s.get("https://198.51.100.50", headers={"Host": "example.org"})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Answer for HTTPS/SNI support: Use the HostHeaderSSLAdapter in the requests_toolbelt module:

The above solution works fine with virtualhosts for non-encrypted HTTP connections.  For HTTPS you also need to pass SNI (Server Name Identification) in the TLS header which as some servers will present a different SSL certificate depending on what is passed in via SNI.  Also, the python ssl libraries by default don't look at the Host: header to match the server connection at connection time.

The above provides a straight-forward for adding a transport adapter to requests that handles this for you.

Example

import requests

from requests_toolbelt.adapters import host_header_ssl

# Create a new requests session
s = requests.Session()

# Mount the adapter for https URLs
s.mount('https://', host_header_ssl.HostHeaderSSLAdapter())

# Send your request
s.get("https://198.51.100.50", headers={"Host": "example.org"})


问:
overloaded method not seen in subclass

Possible Duplicates:

  C++ overload resolution

  Why does an overridden function in the derived class hide other overloads of the base class?

Why the following example:

```<code>class A {
    public:
        void f(int x){ }
};

class B : public A {
    public:
        void f(float a, int b){ }
};

int main(){
    B *b = new B;
    b->f(1);
};
</code>```

causes:

test.cpp: In function ‘int main()’:
test.cpp:13: error: no matching function for call to ‘B::f(int)’
test.cpp:8: note: candidates are: void B::f(float, int)

f(int) and f(float, int) have different signatures. Why is it causing an error?

EDIT

I understand it's hiding. I am asking why is this happening?

答:
By declaring another function named 'f' in your class B, you are hiding the 'f' declared in A.

To get overloading to work along with inheritance, add a using directive to your class B.

```<code>class B : public A {
public:
    using A::f;
    void f(float a, int b){ }
};
</code>```

This is because compiler looks in the scope of class B and finds only one method that it has to consider for overload resolution.

Title: overloaded method not seen in subclass

Body:
Possible Duplicates:

  C++ overload resolution

  Why does an overridden function in the derived class hide other overloads of the base class?

Why the following example:

class A {
    public:
        void f(int x){ }
};

class B : public A {
    public:
        void f(float a, int b){ }
};

int main(){
    B *b = new B;
    b->f(1);
};

causes:

test.cpp: In function ‘int main()’:
test.cpp:13: error: no matching function for call to ‘B::f(int)’
test.cpp:8: note: candidates are: void B::f(float, int)

f(int) and f(float, int) have different signatures. Why is it causing an error?

EDIT

I understand it's hiding. I am asking why is this happening?

Body:
By declaring another function named 'f' in your class B, you are hiding the 'f' declared in A.

To get overloading to work along with inheritance, add a using directive to your class B.

class B : public A {
public:
    using A::f;
    void f(float a, int b){ }
};

This is because compiler looks in the scope of class B and finds only one method that it has to consider for overload resolution.


问:
How to create functional index on mariadb?
I'm trying to create functional index on mariadb 5.5 like below...

```<code>MariaDB [testdb]> create table foo(c1 datetime);
Query OK, 0 rows affected (0.43 sec)

MariaDB [testdb]> alter table foo add c2 varchar(10) AS (date_format(c1, '%Y-%m-%d'));
Query OK, 0 rows affected (0.22 sec)
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [testdb]> desc foo;
+-------+-------------+------+-----+---------+---------+
| Field | Type        | Null | Key | Default | Extra   |
+-------+-------------+------+-----+---------+---------+
| c1    | datetime    | YES  |     | NULL    |         |
| c2    | varchar(10) | YES  |     | NULL    | VIRTUAL |
+-------+-------------+------+-----+---------+---------+
2 rows in set (0.03 sec)

MariaDB [testdb]> create index idx_foo on foo(c1, c2);
ERROR 1904 (HY000): Key/Index cannot be defined on a non-stored computed column
MariaDB [testdb]>
</code>```

Is there any how to create compositional column based index with VIRUAL column?

Any advice would be appreciated.

Thanks in advance.

答:
See documentation:

Generated (Virtual and Persistent/Stored) Columns

...

MariaDB until 10.2.2

In MariaDB 10.2.2 and before, the following statements apply to
  indexes for generated columns:

Defining indexes on VIRTUAL generated columns is not supported.

...

...

Body:
I'm trying to create functional index on mariadb 5.5 like below...

MariaDB [testdb]> create table foo(c1 datetime);
Query OK, 0 rows affected (0.43 sec)

MariaDB [testdb]> alter table foo add c2 varchar(10) AS (date_format(c1, '%Y-%m-%d'));
Query OK, 0 rows affected (0.22 sec)
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [testdb]> desc foo;
+-------+-------------+------+-----+---------+---------+
| Field | Type        | Null | Key | Default | Extra   |
+-------+-------------+------+-----+---------+---------+
| c1    | datetime    | YES  |     | NULL    |         |
| c2    | varchar(10) | YES  |     | NULL    | VIRTUAL |
+-------+-------------+------+-----+---------+---------+
2 rows in set (0.03 sec)

MariaDB [testdb]> create index idx_foo on foo(c1, c2);
ERROR 1904 (HY000): Key/Index cannot be defined on a non-stored computed column
MariaDB [testdb]>

Is there any how to create compositional column based index with VIRUAL column?

Any advice would be appreciated.

Thanks in advance.


问:
How can I fake cloud provider credentials in Terraform?
I am writing a cross-cloud Terraform module (for google and aws) which accepts a cloud input variable and applies it accordingly, for example:

```<code>variable "cloud" {}

resource "google_example" {
  count = "${var.cloud == "google" ? 1 : 0}"
}

resource "aws_example" {
  count = "${var.cloud == "aws" ? 1 : 0}"
}
</code>```

The problem with this approach is that I only want to provide credentials for the selected cloud, not both - setting cloud=aws for example I get:

```<code>Error: google: could not find default credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
</code>```

Is there any way to fake cloud provider credentials for the non-selected cloud, or do I need to implement some sort of Terraform templating?

答:
Every resource can allow a provider field, which tells it which provider to use. I think you may need to set real credentials for both providers, else Terraform will fail to initialise if you use backend configuration. Otherwise, set fake credentials as environment variables and see what happens:

```<code>TF_VAR_AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" # et cetera
</code>```

Body:
I am writing a cross-cloud Terraform module (for google and aws) which accepts a cloud input variable and applies it accordingly, for example:

variable "cloud" {}

resource "google_example" {
  count = "${var.cloud == "google" ? 1 : 0}"
}

resource "aws_example" {
  count = "${var.cloud == "aws" ? 1 : 0}"
}

The problem with this approach is that I only want to provide credentials for the selected cloud, not both - setting cloud=aws for example I get:

Error: google: could not find default credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.

Is there any way to fake cloud provider credentials for the non-selected cloud, or do I need to implement some sort of Terraform templating?

Body:
Every resource can allow a provider field, which tells it which provider to use. I think you may need to set real credentials for both providers, else Terraform will fail to initialise if you use backend configuration. Otherwise, set fake credentials as environment variables and see what happens:

TF_VAR_AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" # et cetera


问:
Is it possible to use symbolic links in Virtualbox shared folder without administrator priviledges?
Is it possible to have Unix guest on Windows 10 host and use symbolic links in Virtualbox shared folders without administrator priviledges?

I'm asking because previously symbolic links on Windows 10 required administator priviledges but now it's possible to enable Developer mode to create symbolic links using standard account and mklink. Thus it make sense there would be a way use the Developer mode to lift the administrator requirement on symbolic links in shared folders as well.

答:
Short answer is yes. It is possible to use symbolic links in Virtualbox shared folders without administrator priviledges and it doesn't even require the Developer Mode.

Here are the step-by-step instructions how to do it, thanks eryksun for helping me out!

Launch Local Security Policy app from start menu (or Win+R, then type secpol.msc)

Navigate to Local Policies -> User Rights Assignment

Open Create symbolic links property. By default it has only Administrators listed.

Click Add User or Group... and write Authenticated Users to the Enter the object names to select field to grant the symbolic link priviledge to all users who log on with credetials

Close the windows by clicking OKs and log off and log on

Now symbolic links are working in VirtualBox shared folders without administrator priviledges!

The Developer Mode didn't help here even though it enables the use of symbolic links without elevated access in two ways:

mklink command can be used without elevated access

CreateSymbolicLink API can be used without elevated access if you pass dwFlags option SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE

Since even after enabling the Developer Mode VirtualBox has to be run as Administrator in order to create symlinks I assume the method 2 i.e. API calls are used to create the symlinks. Thus VirtualBox code would need to be updated to use the SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE flag. After that update enabling Developer Mode should be sufficient to enable symbolic links in shared folders.


问:
how to handle xml data in javascript
I am newbie in javascript xml data handling. Currently, my ajax call to a server, and the server returns xml data, I don't know how to parse the xml data to get some values.

My ajax call:

```<code>$.ajax({
            url: 'http://localhost:8080/someinterface/the-id',
            type: 'GET',
            async: false,
            dataType: 'application/xml',
            data: {id: 43},
            success: function(data) {

                //handle the data

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })
</code>```

the returned xml data looks like:

```<code><DOCUMENT>
  <AGE>16</AGE>
  <USERNAME>default user</USERNAME>
  <SECURITYID>1111</SECURITYID>
...
</code>```

how to parse the xml data to get for example "USERNAME" in my javascript ??

------------EDIT------------

I tried to use your proposed ways, but now I got error message:

XML Parsing Error: no element found Location: moz-nullprincipal:{120e8c1d-5174-4e94-9ebb-2bffda80b170} Line Number 1, Column 1:
^

and the ajax call result to the error function

-------------------PARTLY SOLVED------------------------

Finally, I found the reason is that my application is running on jetty server on localhost:8080, while my ajax is requesting xml data on tomcat server which is running on localhost:8085. Because of the domain port are different, I got the weired problem. Now, after I move my application to tomcat server and request tomcat server, I got the xml response successfully.

The ajax call goes to the success function, and I use

```<code>success: function(data){
           xmlDoc = $.parseXML(data);
            $xml = $(xmlDoc);
            $userName = $xml.find('USERNAME');
            var userName = $userName.text();
            alert('1');
            alert(userName);
}
</code>```

I got alert('1') in my browser, BUT I do not get alert(userName) , I don't know why... So I put here "PARTLY SOLVED", so...why I do not get my userName alert..

答:
The browser will basically handle it for you:</p>

```<code>success: function(data) {
  var username = $(data).find('username').text();
  // ...
}
</code>```

Title: how to handle xml data in javascript

Body:
I am newbie in javascript xml data handling. Currently, my ajax call to a server, and the server returns xml data, I don't know how to parse the xml data to get some values.

My ajax call:

$.ajax({
            url: 'http://localhost:8080/someinterface/the-id',
            type: 'GET',
            async: false,
            dataType: 'application/xml',
            data: {id: 43},
            success: function(data) {

                //handle the data

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })

the returned xml data looks like:

<DOCUMENT>
  <AGE>16</AGE>
  <USERNAME>default user</USERNAME>
  <SECURITYID>1111</SECURITYID>
...

how to parse the xml data to get for example "USERNAME" in my javascript ??

------------EDIT------------

I tried to use your proposed ways, but now I got error message:

XML Parsing Error: no element found Location: moz-nullprincipal:{120e8c1d-5174-4e94-9ebb-2bffda80b170} Line Number 1, Column 1:
^

and the ajax call result to the error function

-------------------PARTLY SOLVED------------------------

Finally, I found the reason is that my application is running on jetty server on localhost:8080, while my ajax is requesting xml data on tomcat server which is running on localhost:8085. Because of the domain port are different, I got the weired problem. Now, after I move my application to tomcat server and request tomcat server, I got the xml response successfully.

The ajax call goes to the success function, and I use

success: function(data){
           xmlDoc = $.parseXML(data);
            $xml = $(xmlDoc);
            $userName = $xml.find('USERNAME');
            var userName = $userName.text();
            alert('1');
            alert(userName);
}

I got alert('1') in my browser, BUT I do not get alert(userName) , I don't know why... So I put here "PARTLY SOLVED", so...why I do not get my userName alert..

Body:
The browser will basically handle it for you:

success: function(data) {
  var username = $(data).find('username').text();
  // ...
}


问:
Using Lodash to find a partial string in any property value of an object
I want to use Lodash to return true when an object contains in any of its values, a match for a partial string. I've tried this with _.includes as follows.

```<code>const ob = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = _.includes(ob, search)
console.log(result); // false
</code>```

I've also tried this using a regular expression instead of a string for the search term.

```<code>const search = /stone/gi;
</code>```

Both times result returns false. I want result to return true. How can I do this in Lodash?

答:
You could find the string partial within an array of the object's values like this.

const ob = {
  first: "Fred",
  last: "Flintstone"
}
const search = "stone"
const isFound = Boolean(Object.values(ob).find(item => item.includes(search)))
console.log(isFound)```
</div>
</div>
</p>

<p>And as per @Kobe's suggestion, you could use some instead of evaluating the result of <code>find</code> with <code>Boolean()</code>.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const ob = {
  first: "Fred",
  last: "Flintstone"
}
const search = "stone"
const isFound = Object.values(ob).some(item => item.includes(search))
console.log(isFound)</code>```

Body:
I want to use Lodash to return true when an object contains in any of its values, a match for a partial string. I've tried this with _.includes as follows.

const ob = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = _.includes(ob, search)
console.log(result); // false

I've also tried this using a regular expression instead of a string for the search term.

const search = /stone/gi;

Both times result returns false. I want result to return true. How can I do this in Lodash?

Body:
You could find the string partial within an array of the object's values like this.

const ob = {
  first: "Fred",
  last: "Flintstone"
}
const search = "stone"
const isFound = Boolean(Object.values(ob).find(item => item.includes(search)))
console.log(isFound)

And as per @Kobe's suggestion, you could use some instead of evaluating the result of find with Boolean().

const ob = {
  first: "Fred",
  last: "Flintstone"
}
const search = "stone"
const isFound = Object.values(ob).some(item => item.includes(search))
console.log(isFound)


问:
Is there a type for "Class" in Typescript? And does "any" include it?
In Java, you can give a class to a method as a parameter using the type "Class". I didn't find anything similar in the typescript docs - is it possible to hand a class to a method? And if so, does the type "any" include such class-types?

Background: I'm having an issue with Webstorm, telling me that I cannot hand over a class to @ViewChild(...) in Angular 2. However, the Typescript compiler does not complain. The signature of @ViewChild() seems to be "Type<any> | Function | string", so I wonder if any includes Classes or not.

答:
Type<T> from @angular/core is a proper interface for Class.

```<code>export interface Type<T> extends Function {
    new (...args: any[]): T;
}
</code>```

You can use it to keep reference to class, instead of instance of this class:

```<code>private classRef: Type<MyCustomClass>;
</code>```

or

```<code>private classRef: Type<any>;
</code>```

According to background of your question with @ViewChild:

@ViewChild allows to inject "string selector" / Component / Directive

Signature of Type<any> | Function | string
is an abstract signature that allows us to inject all of above.

Body:
Type<T> from @angular/core is a proper interface for Class.

export interface Type<T> extends Function {
    new (...args: any[]): T;
}

You can use it to keep reference to class, instead of instance of this class:

private classRef: Type<MyCustomClass>;

or

private classRef: Type<any>;

According to background of your question with @ViewChild:

@ViewChild allows to inject "string selector" / Component / Directive

Signature of Type<any> | Function | string
is an abstract signature that allows us to inject all of above.


问:
Read words from paragraph to paragraph, from line to line (C++)
I'm looking for a way to read and locate words (line number, paragraph number) from a file.

For example, I want to track the number of the word "you" in a file. Each time I find this word on a line, I will push the line number and the paragraph number to the two vectors

```<code>ifstream file;
file.open(input.txt)
vector<int> paragraph_number;
vector<int> line_number;
</code>```

What's the best way to read paragraph by paragraph and line by line? Thank you!

答:
Line number is fairly simple, as you can just use getline or something similar to read one line at a time. Just keep track of the number of times you read a line from the file. Or, you could count the number of newline (\n) you run across.

Paragraph is a bit trickier, there's no standardized way to look at paragraph in a file. You would probably need some sort of character delimiter for the end of a paragraph. You could interpret two newlines as a new paragraph, but that part is up to you.

Body:
I'm looking for a way to read and locate words (line number, paragraph number) from a file.

For example, I want to track the number of the word "you" in a file. Each time I find this word on a line, I will push the line number and the paragraph number to the two vectors

ifstream file;
file.open(input.txt)
vector<int> paragraph_number;
vector<int> line_number;

What's the best way to read paragraph by paragraph and line by line? Thank you!


问:
Filter top n largest groups in data.frame
For the example data:

```<code>set.seed(2222)
example_data <- data.frame(col1 = 1:15,
                           col2 = 16:30,
                           group = sample(1:3, 15, replace = TRUE))

   col1 col2 group
1     1   16     2
2     2   17     1
3     3   18     3
4     4   19     2
5     5   20     3
6     6   21     1
7     7   22     3
8     8   23     1
9     9   24     3
10   10   25     1
11   11   26     2
12   12   27     2
13   13   28     2
14   14   29     3
15   15   30     3
</code>```

I want to find the top n groups with the most number of records.

Let's say I want to get the top 2 groups with the most number of records. In the data, this would be group 3 and 2:

```<code>example_data %>%
  group_by(group) %>%
  summarise(n = n())

# A tibble: 3 x 2
  group     n
  <int> <int>
1     1     4
2     2     5
3     3     6
</code>```

The expected output is:

```<code>   col1 col2 group
1     1   16     2
2     3   18     3
3     4   19     2
4     5   20     3
5     7   22     3
6     9   24     3
7    11   26     2
8    12   27     2
9    13   28     2
10   14   29     3
11   15   30     3
</code>```

答:
Another dplyr method could be:

```<code>example_data %>%
  group_by(group) %>%
  count() %>%
  ungroup() %>%
  top_n(n = 2, wt = n) %>%
  select(-n) %>%
  inner_join(example_data)
</code>```

Body:
For the example data:

set.seed(2222)
example_data <- data.frame(col1 = 1:15,
                           col2 = 16:30,
                           group = sample(1:3, 15, replace = TRUE))

   col1 col2 group
1     1   16     2
2     2   17     1
3     3   18     3
4     4   19     2
5     5   20     3
6     6   21     1
7     7   22     3
8     8   23     1
9     9   24     3
10   10   25     1
11   11   26     2
12   12   27     2
13   13   28     2
14   14   29     3
15   15   30     3

I want to find the top n groups with the most number of records.

Let's say I want to get the top 2 groups with the most number of records. In the data, this would be group 3 and 2:

example_data %>%
  group_by(group) %>%
  summarise(n = n())

# A tibble: 3 x 2
  group     n
  <int> <int>
1     1     4
2     2     5
3     3     6

The expected output is:

   col1 col2 group
1     1   16     2
2     3   18     3
3     4   19     2
4     5   20     3
5     7   22     3
6     9   24     3
7    11   26     2
8    12   27     2
9    13   28     2
10   14   29     3
11   15   30     3

Body:
Another dplyr method could be:

example_data %>%
  group_by(group) %>%
  count() %>%
  ungroup() %>%
  top_n(n = 2, wt = n) %>%
  select(-n) %>%
  inner_join(example_data)


问:
2 questions, Python OverflowError: (34, 'Result too large') and wrong function results
1st of all, I'm trying to understand why I'm getting an overflow error.  the first function "fibGen" works fine unless I give it an insanely large nth Fibonacci term.

```<code>    #the golden ration function
    def fibGen(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                print('{i:3}: {v:3}'.format(i=number, v=round(val)))
</code>```

The second function "elemFib" will give me the correct answer but then errors out if number is over 1500.

```<code>    #the find element < Max number function
    def elemFib(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                if val < num:
                    print('Fib({}): {}'.format(number, round(val)))
</code>```

lastly, the function "pythonic" works like the "elemFib" function and does not give me an error code for even a very large number, why is that?  Also, I'm trying to get it to print the Fibonacci numbers like the first function "fibGen" but can't get it to work like that.

```<code>    #Pythonic way
    def pythonic(num):
        a, b = 0,1

        while a < num:
            print(a, sep=" ", end=" ")
            a, b = b, a+b
</code>```

My complete code for your review:

```<code>    import math
    import time

    #create the golden Ratio formula
    golden_ratio = (1 + math.sqrt(5)) / 2

    #the timer function
    def clockTime(start_time):
        print('\nRun Time:', time.time() - start_time)

    #the golden ration function
    def fibGen(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                print('{i:3}: {v:3}'.format(i=number, v=round(val)))

    #the find element < Max number function
    def elemFib(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                if val < num:
                    print('Fib({}): {}'.format(number, round(val)))

    #Pythonic way
    def pythonic(num):
        a, b = 0,1

        while a < num:
            print(a, sep=" ", end=" ")
            a, b = b, a+b

    #display the Main Menu
    def dispMenu():
        print('---------------------Fibonacci Series ------------------\n')
        print('(A) Print Fibonacci numbers to the nth term')
        print('(B) Print Fibonacci numbers until element is less than Max number')
        print('(C) pythonic print')
        print('(Q) Quit the program\n')

    def  main():
              # set boolean control variable for loop
              loop = True

              #Create while loop for menu
              while loop:

                  #Display the menu
                  dispMenu()

                  #Get user's input
                  #choice = (input('Please make a selection: '))

                  #Get user's input
                  choice = input('Please make a selection: ').upper()

                  #Perform the selected action
                  if choice == 'A':
                      num = int(input("How many Fibonacci numbers should I print? "))
                      start_time = time.time()
                      fibGen(num)
                      clockTime(start_time)
                  elif choice == 'B':
                      num = int(input("the element should be less than? "))
                      start_time = time.time()
                      elemFib(num)
                      clockTime(start_time)
                  elif choice == 'C':
                      num = int(input('Pythonic Fibonacci series to the nth term? '))
                      start_time = time.time()
                      pythonic(num)
                      clockTime(start_time)
                  elif choice == 'Q':
                      print('\nExiting program, Thank you and Goodbye')
                      loop = False
                  else:
                      print('\nInvalid selection, try again\n')

    main()
</code>```

答:
To expand on the explanation above, python integers will automatically be promoted to long data types so that it can hold any number. This feature has existed since python 2.2. Floats are limited, and they are not automatically promoted to Decimal types. Since the golden_ratio variable is a float, any calculation with it is limited unless you manually change the type.

https://www.python.org/dev/peps/pep-0237/

You can find out the max float value with sys.float_info:

```<code>>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
</code>```

Here you can see that the float cause an OverflowError but the Decimal or integer will not:

```<code>>>> 10.0 ** 309
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: (34, 'Numerical result out of range')
>>> Decimal(10.0) ** 309
Decimal('1.000000000000000000000000000E+309')
>>> 10 ** 309
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L
</code>```

Interestingly, the exponent operator ** raises an OverflowError exception, but multiplication just returns an inf float value:

```<code>>>> 2 * (10.0 ** 308)
inf
>>> -2 * (10.0 ** 308)
-inf
>>> math.isinf(2 * (10.0 ** 308))
True
</code>```

Body:
1st of all, I'm trying to understand why I'm getting an overflow error.  the first function "fibGen" works fine unless I give it an insanely large nth Fibonacci term.

    #the golden ration function
    def fibGen(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                print('{i:3}: {v:3}'.format(i=number, v=round(val)))

The second function "elemFib" will give me the correct answer but then errors out if number is over 1500.

    #the find element < Max number function
    def elemFib(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                if val < num:
                    print('Fib({}): {}'.format(number, round(val)))

lastly, the function "pythonic" works like the "elemFib" function and does not give me an error code for even a very large number, why is that?  Also, I'm trying to get it to print the Fibonacci numbers like the first function "fibGen" but can't get it to work like that.

    #Pythonic way
    def pythonic(num):
        a, b = 0,1

        while a < num:
            print(a, sep=" ", end=" ")
            a, b = b, a+b

My complete code for your review:

    import math
    import time

    #create the golden Ratio formula
    golden_ratio = (1 + math.sqrt(5)) / 2

    #the timer function
    def clockTime(start_time):
        print('\nRun Time:', time.time() - start_time)

    #the golden ration function
    def fibGen(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                print('{i:3}: {v:3}'.format(i=number, v=round(val)))

    #the find element < Max number function
    def elemFib(num):
            for number in range(0,num+1):
                val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
                if val < num:
                    print('Fib({}): {}'.format(number, round(val)))

    #Pythonic way
    def pythonic(num):
        a, b = 0,1

        while a < num:
            print(a, sep=" ", end=" ")
            a, b = b, a+b

    #display the Main Menu
    def dispMenu():
        print('---------------------Fibonacci Series ------------------\n')
        print('(A) Print Fibonacci numbers to the nth term')
        print('(B) Print Fibonacci numbers until element is less than Max number')
        print('(C) pythonic print')
        print('(Q) Quit the program\n')

    def  main():
              # set boolean control variable for loop
              loop = True

              #Create while loop for menu
              while loop:

                  #Display the menu
                  dispMenu()

                  #Get user's input
                  #choice = (input('Please make a selection: '))

                  #Get user's input
                  choice = input('Please make a selection: ').upper()

                  #Perform the selected action
                  if choice == 'A':
                      num = int(input("How many Fibonacci numbers should I print? "))
                      start_time = time.time()
                      fibGen(num)
                      clockTime(start_time)
                  elif choice == 'B':
                      num = int(input("the element should be less than? "))
                      start_time = time.time()
                      elemFib(num)
                      clockTime(start_time)
                  elif choice == 'C':
                      num = int(input('Pythonic Fibonacci series to the nth term? '))
                      start_time = time.time()
                      pythonic(num)
                      clockTime(start_time)
                  elif choice == 'Q':
                      print('\nExiting program, Thank you and Goodbye')
                      loop = False
                  else:
                      print('\nInvalid selection, try again\n')

    main()

Body:
To expand on the explanation above, python integers will automatically be promoted to long data types so that it can hold any number. This feature has existed since python 2.2. Floats are limited, and they are not automatically promoted to Decimal types. Since the golden_ratio variable is a float, any calculation with it is limited unless you manually change the type.

https://www.python.org/dev/peps/pep-0237/

You can find out the max float value with sys.float_info:

>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

Here you can see that the float cause an OverflowError but the Decimal or integer will not:

>>> 10.0 ** 309
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: (34, 'Numerical result out of range')
>>> Decimal(10.0) ** 309
Decimal('1.000000000000000000000000000E+309')
>>> 10 ** 309
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

Interestingly, the exponent operator ** raises an OverflowError exception, but multiplication just returns an inf float value:

>>> 2 * (10.0 ** 308)
inf
>>> -2 * (10.0 ** 308)
-inf
>>> math.isinf(2 * (10.0 ** 308))
True


问:
Reference array keys without knowing their names?
If I have an array like this:

```<code>$array = array('something'=>array('more'=>array('id'=> 34)));
</code>```

Then print_r($array['something']['more']['id'] works fine.

But say the key names might change but the structure wont. How could I reference the same values without knowing the names?

I thought maybe print_r($array[0][1][2] might work, but of course those keys don't exist.

答:
You can use reset(), next() and end() as always

```<code>$array = array('something'=>array('more'=>array('id'=> 34)));
echo reset(reset(reset($array)));
</code>```

Body:
If I have an array like this:

$array = array('something'=>array('more'=>array('id'=> 34)));

Then print_r($array['something']['more']['id'] works fine.

But say the key names might change but the structure wont. How could I reference the same values without knowing the names?

I thought maybe print_r($array[0][1][2] might work, but of course those keys don't exist.

Body:
You can use reset(), next() and end() as always

$array = array('something'=>array('more'=>array('id'=> 34)));
echo reset(reset(reset($array)));


问:
Get name of currently logged in user
I made a simple login using Identity. I logged in with signInManager.PasswordSignInAsync().

If the login was successful, I would like to get the currently logged in user's data using the userManager.

The problem is that I can only get an id from the GetUserAsync and don't know what to do with it.

```<code>var result = await mSignInManager.PasswordSignInAsync(username, password, true, false);

if (result.Succeeded)
{
    //var loggedUser = mUserManager.GetUserName(HttpContext.User);
    var userData = mUserManager.GetUserAsync(HttpContext.User);
    var user = await mUserManager.FindByIdAsync(userData.Id.ToString());
    return Redirect("/createpost");
}
</code>```

答:
You've got two issues. First, GetUserAsync relies on the principal being set in HttpContext, which hasn't occurred yet, so that method will fail. There must be an intervening request before you can access the user that way.

What you can do is pull the user out directly using something like FindByIdAsync, which you're attempting to do already. However, you're trying to find the user based on the id of the user instance you tried to retrieve via GetUserAsync. Since that failed, there will be no user, and thus no id to use in this lookup, causing it to fail as well. It doesn't even make sense to do this, as if you had the user already to get the id from, there'd be no point in looking that user up by its id.

So, what you need to do is look the user up by information you actually do have, which based on your code, is username. Therefore, do:

```<code>var user = await mUserManager.FindByNameAsync(username);
</code>```

Title: Get name of currently logged in user

Body:
I made a simple login using Identity. I logged in with signInManager.PasswordSignInAsync().

If the login was successful, I would like to get the currently logged in user's data using the userManager.

The problem is that I can only get an id from the GetUserAsync and don't know what to do with it.

var result = await mSignInManager.PasswordSignInAsync(username, password, true, false);

if (result.Succeeded)
{
    //var loggedUser = mUserManager.GetUserName(HttpContext.User);
    var userData = mUserManager.GetUserAsync(HttpContext.User);
    var user = await mUserManager.FindByIdAsync(userData.Id.ToString());
    return Redirect("/createpost");
}

Body:
You've got two issues. First, GetUserAsync relies on the principal being set in HttpContext, which hasn't occurred yet, so that method will fail. There must be an intervening request before you can access the user that way.

What you can do is pull the user out directly using something like FindByIdAsync, which you're attempting to do already. However, you're trying to find the user based on the id of the user instance you tried to retrieve via GetUserAsync. Since that failed, there will be no user, and thus no id to use in this lookup, causing it to fail as well. It doesn't even make sense to do this, as if you had the user already to get the id from, there'd be no point in looking that user up by its id.

So, what you need to do is look the user up by information you actually do have, which based on your code, is username. Therefore, do:

var user = await mUserManager.FindByNameAsync(username);


问:
Bitfield endianness in gcc
The endianness of bitfields is implementation defined. Is there a way to check, at compile time, whether via some macro or other compiler flag, what gcc's bitfield endianness actually is?

In other words, given something like:

```<code>struct X {
    uint32_t a : 8;
    uint32_t b : 24;
};
</code>```

Is there a way for me to know at compile time whether or not a is the first or last byte in X?

答:
It might be of some interest that when the bitfields are multiples of 8-bits across, it appears that endianness of the arcitecture does not matter.

See here [godbolt.org]

I chose the arm architecture in this godbolt example because that supports both big and little endian, and it is easy to compare the differences.

Note that whether the architecture is big or small endian, in both cases the 8-bit field is at the start of the struct.

I tested all of the compilers on godbolt that could generate readable assembly code for the is_8bit_tag_at_start function, and they all appeared to return true.

Title: Bitfield endianness in gcc

Body:
The endianness of bitfields is implementation defined. Is there a way to check, at compile time, whether via some macro or other compiler flag, what gcc's bitfield endianness actually is?

In other words, given something like:

struct X {
    uint32_t a : 8;
    uint32_t b : 24;
};

Is there a way for me to know at compile time whether or not a is the first or last byte in X?


问:
Azure AD authentication token fails web api authorization
I have a web-api on Azure that requires authorization and I am using Azure AD to authenticate accounts and generate access tokens.

I can successfully acquire access tokens from Azure AD with ADAL for the same account in two different ways, but only one of them is authorized by the web-api, the other one fails.

The following is authenticating an account interactively and the token is authorized by the web-api

```<code>result = AuthenticationContext.AcquireTokenAsync(resource, clientId, redirectUri, new PlatformParameters(PromptBehavior)).Result;
</code>```

where resource is web-api application id (guid).

The following is authenticating an account non-interactively with a given user name and password, but the token is not authorized by the web api

```<code>UserPasswordCredential cred = new UserPasswordCredential(userName, password);
result = AuthenticationContext.AcquireTokenAsync(resource, clientId, cred).Result;
</code>```

where resource = https://{tenant}/{api name}.

The web-api call is as follows:

```<code>HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await httpClient.GetAsync(ApplicationCallUri);
</code>```

Both ways return identical AuthenticationResult objects (apart from tokens and time stamps) and I cannot see why authorization fails for the second one.

The web-api response is "Authorization has been denied for this request."

Since authentication succeeds for both ways, I assume it must be something with at the web-api's side. Help is much appreciated. Thanks.

答:
Thanks to juunas who pointed out the audience parameter I realized that the web api was set to expect tokens for only one the two audience values. I added a second option for bearer authentication and it works for both scenarios.

Thank you juunas!

Body:
I have a web-api on Azure that requires authorization and I am using Azure AD to authenticate accounts and generate access tokens.

I can successfully acquire access tokens from Azure AD with ADAL for the same account in two different ways, but only one of them is authorized by the web-api, the other one fails.

The following is authenticating an account interactively and the token is authorized by the web-api

result = AuthenticationContext.AcquireTokenAsync(resource, clientId, redirectUri, new PlatformParameters(PromptBehavior)).Result;

where resource is web-api application id (guid).

The following is authenticating an account non-interactively with a given user name and password, but the token is not authorized by the web api

UserPasswordCredential cred = new UserPasswordCredential(userName, password);
result = AuthenticationContext.AcquireTokenAsync(resource, clientId, cred).Result;

where resource = https://{tenant}/{api name}.

The web-api call is as follows:

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await httpClient.GetAsync(ApplicationCallUri);

Both ways return identical AuthenticationResult objects (apart from tokens and time stamps) and I cannot see why authorization fails for the second one.

The web-api response is "Authorization has been denied for this request."

Since authentication succeeds for both ways, I assume it must be something with at the web-api's side. Help is much appreciated. Thanks.


问:
tableView.selectRow has no effect when called within a UIContextualAction callback
When calling selectRow(at:animated:scrollPosition:) inside a UIContextualAction callback, nothing changes: the specified row doesn't turn gray.

Here's the simplest code I could write that exhibits the issue:

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, callback in
        tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
        callback(true)
    }

    return UISwipeActionsConfiguration(actions: [deleteAction])
}
```

I tried many variations:

properly performing the delete operation (updating the model then updating the table view with deleteRows())

not animating the selection operation

using a .normal action instead of a .destructive one

grouping various parts of the callback code in a tableView.performBatchUpdates() block

calling all of these methods in various orders, inside and outside the performBatchUpdates() call

somehow waiting for the end of the deletion animation with CATransaction.setCompletionBlock()

dispatching the selection operation on the main queue to have it execute a smidge later

All without success.

答:
In the specific case of a delete action, you can implement the tableView(tableView: cell: indexPath:) delegate method, and perform the selection there; make sure to check that the cell didn't simply scroll off-screen, though.

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if cellWasBeingDeleted(cell) { // your own implementation
        tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
    }
}
```

Body:
When calling selectRow(at:animated:scrollPosition:) inside a UIContextualAction callback, nothing changes: the specified row doesn't turn gray.

Here's the simplest code I could write that exhibits the issue:

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, callback in
        tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
        callback(true)
    }

    return UISwipeActionsConfiguration(actions: [deleteAction])
}

I tried many variations:

properly performing the delete operation (updating the model then updating the table view with deleteRows())

not animating the selection operation

using a .normal action instead of a .destructive one

grouping various parts of the callback code in a tableView.performBatchUpdates() block

calling all of these methods in various orders, inside and outside the performBatchUpdates() call

somehow waiting for the end of the deletion animation with CATransaction.setCompletionBlock()

dispatching the selection operation on the main queue to have it execute a smidge later

All without success.


问:
How to use volley in post request?
I am new in android studio and I am going to use volley library to get data from server.

json request is follow:

```<code>{
  "method": "authenticate",
  "params": [
    "dummyuser",
    "dummy"
  ],
  "id": "1",
  "jsonrpc": "2.0"
}
</code>```

Following is my code

```<code>RequestQueue requestQueueV1= Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequestV1 = new StringRequest(Request.Method.POST, server_url + AppConfig.VERSION1_URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
            // response is JSONObject
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(SettingsActivity.this, "Error occurred.", Toast.LENGTH_LONG).show();
    }
}) {
     @Override
     protected Map<String, String> getParams() {
         Map<String, String> request_body = new HashMap<String, String>();
         request_body.put("method", "authenticate");
         request_body.put("id", "1");
         request_body.put("jsonrpc", "2.0");
         JSONArray params = new JSONArray();
         params.put(user_name);
         params.put(password);
         request_body.put("params", params.toString());
         return request_body;
    }
    @Override
    public String getBodyContentType() {
         return "application/json; charset=utf-8";
    }

};
requestQueueV1.add(stringRequestV1);
</code>```

I have error "com.android.volley.TimeoutError". How can I fix this error?

And follow is response

```<code>{
    "result": {
        "success": true,
        "items": [
            {
                "apiKey": "4902ad6c957144aba697995f8",
                "userID": "41426322"
            }
        ],
        "total": 1
    },
    "id": "1",
    "jsonrpc": "2.0"
}
</code>```

How can I pass this response json object when fetching is success.

Following is my postman screenshot:

答:
Add this below your stringRequestV1 before adding it to Requestqueue.

```<code>stringRequestV1.setRetryPolicy(new DefaultRetryPolicy(4000, 2, 2f));
</code>```

Where 4000 is TIMEOUT_MS, 2 is DEFAULT_MAX_RETRIES, 2f is DEFAULT_BACKOFF_MULT.

You can use default volley timeout settings like below.

```<code>stringRequestV1.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
</code>```

Title: How to use volley in post request?

Body:
I am new in android studio and I am going to use volley library to get data from server.

json request is follow:

{
  "method": "authenticate",
  "params": [
    "dummyuser",
    "dummy"
  ],
  "id": "1",
  "jsonrpc": "2.0"
}

Following is my code

RequestQueue requestQueueV1= Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequestV1 = new StringRequest(Request.Method.POST, server_url + AppConfig.VERSION1_URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
            // response is JSONObject
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(SettingsActivity.this, "Error occurred.", Toast.LENGTH_LONG).show();
    }
}) {
     @Override
     protected Map<String, String> getParams() {
         Map<String, String> request_body = new HashMap<String, String>();
         request_body.put("method", "authenticate");
         request_body.put("id", "1");
         request_body.put("jsonrpc", "2.0");
         JSONArray params = new JSONArray();
         params.put(user_name);
         params.put(password);
         request_body.put("params", params.toString());
         return request_body;
    }
    @Override
    public String getBodyContentType() {
         return "application/json; charset=utf-8";
    }

};
requestQueueV1.add(stringRequestV1);

I have error "com.android.volley.TimeoutError". How can I fix this error?

And follow is response

{
    "result": {
        "success": true,
        "items": [
            {
                "apiKey": "4902ad6c957144aba697995f8",
                "userID": "41426322"
            }
        ],
        "total": 1
    },
    "id": "1",
    "jsonrpc": "2.0"
}

How can I pass this response json object when fetching is success.

Following is my postman screenshot:

Body:
Add this below your stringRequestV1 before adding it to Requestqueue.

stringRequestV1.setRetryPolicy(new DefaultRetryPolicy(4000, 2, 2f));

Where 4000 is TIMEOUT_MS, 2 is DEFAULT_MAX_RETRIES, 2f is DEFAULT_BACKOFF_MULT.

You can use default volley timeout settings like below.

stringRequestV1.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


问:
Sort object keys with each and handlebars helper
I would like to sort objects keys with each:
test1, test4, test3 => test1, test3, test4
...

My json:

```<code>"tests": {
    "chapter1": {
        "test1": 5,
        "test4": 8,
        "test3": 3
    },
    "chapter2": {
        "test1": 1,
        "test5": 14,
        "test3": 12
     }
}
</code>```

My handlebars code:

```<code>{{#each tests}}
    <h1>{{@key}}</h1>
    <ul>{{#eachSorted this}}<li>{{this}}</li>{{/eachSorted}}</ul>
{{/each}}
</code>```

I tried but does not work:

```<code>Handlebars.registerHelper('eachSorted', function(context, options) {
    var ret = ""
    Object.keys(context).sort().forEach(function(key) {
        ret = ret + options.fn({key: key, value: context[key]})
    })
    return ret
})
</code>```

答:
you are rendering the whole object instead of the value. Try this:</p>

```<code>{{#each tests}}
    <h1>{{@key}}</h1>
    <ul>{{#eachSorted this}}<li>{{this.value}}</li>{{/eachSorted}}</ul>
{{/each}}
</code>```

Body:
I would like to sort objects keys with each:
test1, test4, test3 => test1, test3, test4
...

My json:

"tests": {
    "chapter1": {
        "test1": 5,
        "test4": 8,
        "test3": 3
    },
    "chapter2": {
        "test1": 1,
        "test5": 14,
        "test3": 12
     }
}

My handlebars code:

{{#each tests}}

{{@key}}

{{#eachSorted this}}
{{this}}
{{/eachSorted}}

{{/each}}

I tried but does not work:

Handlebars.registerHelper('eachSorted', function(context, options) {
    var ret = ""
    Object.keys(context).sort().forEach(function(key) {
        ret = ret + options.fn({key: key, value: context[key]})
    })
    return ret
})

Body:
you are rendering the whole object instead of the value. Try this:

{{#each tests}}
    <h1>{{@key}}</h1>
    <ul>{{#eachSorted this}}<li>{{this.value}}</li>{{/eachSorted}}</ul>
{{/each}}


问:
To run ant commands through batch file
Please tell me how to call a command "ant deploy-hibernate" through batch file located in c: and i want to run the above command on trunk folder located in d: drive.The pupose is i want to run this command every time before i call a start-up for tomcat.Thanks in advance</p>

答: You should add Ant\bin to your PATH environment variable.

Title: To run ant commands through batch file