问:
swift how to set autolayout programmatically
I have buttons inside a view which in potrait mode I want like this -

which is achieved by the following code -

```<code>//original potrait mode/////

 import UIKit
 class PotraitViewController: UIViewController {
 override func viewDidLoad() {
 let buttonred = UIButton()
 buttonred.backgroundColor = UIColor.red
 let buttonblue = UIButton()
 buttonblue.backgroundColor = UIColor.blue
 let landscapesmallview = UIView()
 view.addSubview(landscapesmallview)
 landscapesmallview.addSubview(buttonred)
 landscapesmallview.addSubview(buttonblue)
 buttonred.translatesAutoresizingMaskIntoConstraints = false
 buttonblue.translatesAutoresizingMaskIntoConstraints = false
 NSLayoutConstraint.activate([

    buttonred.topAnchor.constraint(equalTo: view.topAnchor,constant: 200),
    buttonred.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    buttonred.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
    buttonred.widthAnchor.constraint(equalToConstant: 50),
    //-------
    buttonblue.topAnchor.constraint(equalTo: buttonred.bottomAnchor,constant: 40),
    buttonblue.leadingAnchor.constraint(equalTo: buttonred.leadingAnchor),
    buttonblue.trailingAnchor.constraint(equalTo:buttonred.trailingAnchor),
    buttonblue.widthAnchor.constraint(equalTo: buttonred.widthAnchor)

      ])
    }
  }
</code>```

and in landscape mode I want like this -

which is achieved by the following code -

```<code> // original lanscape mode/////

import UIKit
class LandscapeViewController: UIViewController {
override func viewDidLoad() {
let buttonred = UIButton()
buttonred.backgroundColor = UIColor.red
let buttonblue = UIButton()
buttonblue.backgroundColor = UIColor.blue
view.addSubview(buttonred)
view.addSubview(buttonblue)
buttonred.translatesAutoresizingMaskIntoConstraints = false
buttonblue.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([

    buttonred.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    buttonred.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant:40),
    buttonred.trailingAnchor.constraint(equalTo: view.centerXAnchor,constant:-20),
    buttonred.widthAnchor.constraint(equalToConstant: 50),

    //-------
    buttonblue.centerYAnchor.constraint(equalTo: buttonred.centerYAnchor),
    buttonblue.leadingAnchor.constraint(equalTo: view.centerXAnchor,constant:40),
    buttonblue.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
    buttonblue.widthAnchor.constraint(equalTo:buttonred.widthAnchor)

       ])
     }
  }
</code>```

So, I tried the following code to achieve by screen rotation i.e. two different layouts in potrait and landscape views programmatically with the help of the following code:-

```<code>import UIKit

class NewViewController: UIViewController {
override func viewDidLoad() {
let buttonredlandscape = UIButton()
buttonredlandscape.backgroundColor = UIColor.red
let buttonbluelandscape = UIButton()
buttonbluelandscape.backgroundColor = UIColor.blue
let buttonredportrait = UIButton()
buttonredportrait.backgroundColor = UIColor.red
let buttonblueportrait = UIButton()
buttonblueportrait.backgroundColor = UIColor.blue

let landscapesmallview = UIView()
let portraitsmallview = UIView()
landscapesmallview.backgroundColor = UIColor.gray
portraitsmallview.backgroundColor = UIColor.purple
landscapesmallview.frame = view.frame
portraitsmallview.frame = view.frame
view.addSubview(landscapesmallview)
view.addSubview(portraitsmallview)

landscapesmallview.addSubview(buttonredlandscape)
landscapesmallview.addSubview(buttonbluelandscape)
portraitsmallview.addSubview(buttonredportrait)
portraitsmallview.addSubview(buttonblueportrait)
buttonredlandscape.translatesAutoresizingMaskIntoConstraints = false
buttonbluelandscape.translatesAutoresizingMaskIntoConstraints = false
buttonredportrait.translatesAutoresizingMaskIntoConstraints = false
buttonblueportrait.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([

     buttonredlandscape.centerYAnchor.constraint(equalTo:landscapesmallview.centerYAnchor),
      buttonredlandscape.topAnchor.constraint(equalTo:landscapesmallview.topAnchor,constant:40),
    buttonredlandscape.trailingAnchor.constraint(equalTo:   landscapesmallview.centerXAnchor,constant:-20),
    buttonredlandscape.heightAnchor.constraint(equalTo:   landscapesmallview.heightAnchor,constant:50),

    buttonbluelandscape.centerYAnchor.constraint(equalTo:buttonredlandscape.centerYAnchor),
    buttonbluelandscape.leadingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:40),
    buttonbluelandscape.trailingAnchor.constraint(equalTo: landscapesmallview.trailingAnchor,constant:-20),
    buttonbluelandscape.heightAnchor.constraint(equalTo: buttonredlandscape.heightAnchor),

    buttonredportrait.topAnchor.constraint(equalTo: portraitsmallview.topAnchor,constant: 200),
    buttonredportrait.centerXAnchor.constraint(equalTo: portraitsmallview.centerXAnchor),
    buttonredportrait.trailingAnchor.constraint(equalTo: portraitsmallview.trailingAnchor,constant:-20),
    buttonredportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor),

    buttonblueportrait.topAnchor.constraint(equalTo: buttonredportrait.bottomAnchor,constant: 40),
    buttonblueportrait.leadingAnchor.constraint(equalTo: buttonredportrait.leadingAnchor),
    buttonblueportrait.trailingAnchor.constraint(equalTo:buttonredportrait.trailingAnchor),
    buttonblueportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor)

     ])

//-------

func viewWillTransition(to size: CGSize, with coordinator:    ) {
    if UIDevice.current.orientation.isLandscape {
        landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
        portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
     } else if UIDevice.current.orientation.isPortrait {
        portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
        landscapesmallview.translatesAutoresizingMaskIntoConstraints = true

        }
      }
    }
 }
</code>```

which in potrait mode shows -

and which in landscape mode shows -

How to achieve what I want programmatically i.e. topmost 2 buttons to rearrange themselves programmatically every-time the user rotates the device. Its not just the buttons. It can be labels, images, collectionview etc. or just anything. The upshot is that I want to achieve two different layouts in landscape and portrait modes programmatically irrespective of the device.

Points to be noted :-

i) I have tried used NSLayoutAnchor with "NSLayoutConstraint.activate" because apple recommends it, but if the code can be made shorter(and faster) with some other method like visual format etc. I'm okay with that as well/

ii) If possible, I do not want to use stackview or containerview, because there can be many more types of labels, buttons etc, but if there is no other way, then I will use it.

iii) Is my code DRY principle compliant ?

答:
There are various ways to do this. One approach:

declare two "constraint" arrays

one to hold the "narrow view" constraints

one to hold the "wide view" constraints

activate / deactivate the constraints as needed

Here is a complete example:

```<code>class ChangeLayoutViewController: UIViewController {

    let redButton: UIButton = {
        let v = UIButton()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        v.setTitle("Red Button", for: [])
        return v
    }()

    let blueButton: UIButton = {
        let v = UIButton()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .blue
        v.setTitle("Blue Button", for: [])
        return v
    }()

    var narrowConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]()
    var wideConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(redButton)
        view.addSubview(blueButton)

        let g = view.safeAreaLayoutGuide

        var c: NSLayoutConstraint

        // MARK: - narrow orientation

        // constrain redButton above blueButton

        // constrain redButton leading and trailing to safe-area (with 8-pts on each side)
        c = redButton.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 8.0)
        narrowConstraints.append(c)
        c = redButton.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -8.0)
        narrowConstraints.append(c)

        // constrain blueButton leading and trailing to safe-area (with 8-pts on each side)
        c = blueButton.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 8.0)
        narrowConstraints.append(c)
        c = blueButton.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -8.0)
        narrowConstraints.append(c)

        // constrain redButton top 40-pts from safe-area top
        c = redButton.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0)
        narrowConstraints.append(c)
        // constrain blueButton top 20-pts from redButton bottom
        c = blueButton.topAnchor.constraint(equalTo: redButton.bottomAnchor, constant: 20.0)
        narrowConstraints.append(c)

        // MARK: - wide orientation

        // constrain redButton & blueButton side-by-side
        //  with equal widths and 8-pts between them

        // constrain redButton leading 8-pts from safe-area leading
        c = redButton.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 8.0)
        wideConstraints.append(c)
        // constrain blueButton trailing 8-pts from safe-area trailing
        c = blueButton.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -8.0)
        wideConstraints.append(c)

        // constrain blueButton leading 8-pts from redButton trailing
        c = blueButton.leadingAnchor.constraint(equalTo: redButton.trailingAnchor, constant: 8.0)
        wideConstraints.append(c)

        // constrain buttons to equal widths
        c = blueButton.widthAnchor.constraint(equalTo: redButton.widthAnchor)
        wideConstraints.append(c)

        // constrain both buttons centerY to safe-area centerY
        c = redButton.centerYAnchor.constraint(equalTo: g.centerYAnchor)
        wideConstraints.append(c)
        c = blueButton.centerYAnchor.constraint(equalTo: g.centerYAnchor)
        wideConstraints.append(c)

        // activate initial constraints based on view width:height ratio
        changeConstraints(view.frame.width > view.frame.height)

    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        // change active set of constraints based on view width:height ratio
        self.changeConstraints(size.width > size.height)
    }

    func changeConstraints(_ useWide: Bool) -> Void {
        if useWide {
            NSLayoutConstraint.deactivate(narrowConstraints)
            NSLayoutConstraint.activate(wideConstraints)
        } else {
            NSLayoutConstraint.deactivate(wideConstraints)
            NSLayoutConstraint.activate(narrowConstraints)
        }
    }

}
</code>```

Results:

Body:
I have buttons inside a view which in potrait mode I want like this -

which is achieved by the following code -

//original potrait mode/////

 import UIKit
 class PotraitViewController: UIViewController {
 override func viewDidLoad() {
 let buttonred = UIButton()
 buttonred.backgroundColor = UIColor.red
 let buttonblue = UIButton()
 buttonblue.backgroundColor = UIColor.blue
 let landscapesmallview = UIView()
 view.addSubview(landscapesmallview)
 landscapesmallview.addSubview(buttonred)
 landscapesmallview.addSubview(buttonblue)
 buttonred.translatesAutoresizingMaskIntoConstraints = false
 buttonblue.translatesAutoresizingMaskIntoConstraints = false
 NSLayoutConstraint.activate([

    buttonred.topAnchor.constraint(equalTo: view.topAnchor,constant: 200),
    buttonred.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    buttonred.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
    buttonred.widthAnchor.constraint(equalToConstant: 50),
    //-------
    buttonblue.topAnchor.constraint(equalTo: buttonred.bottomAnchor,constant: 40),
    buttonblue.leadingAnchor.constraint(equalTo: buttonred.leadingAnchor),
    buttonblue.trailingAnchor.constraint(equalTo:buttonred.trailingAnchor),
    buttonblue.widthAnchor.constraint(equalTo: buttonred.widthAnchor)

      ])
    }
  }

and in landscape mode I want like this -

which is achieved by the following code -

 // original lanscape mode/////

import UIKit
class LandscapeViewController: UIViewController {
override func viewDidLoad() {
let buttonred = UIButton()
buttonred.backgroundColor = UIColor.red
let buttonblue = UIButton()
buttonblue.backgroundColor = UIColor.blue
view.addSubview(buttonred)
view.addSubview(buttonblue)
buttonred.translatesAutoresizingMaskIntoConstraints = false
buttonblue.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([

    buttonred.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    buttonred.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant:40),
    buttonred.trailingAnchor.constraint(equalTo: view.centerXAnchor,constant:-20),
    buttonred.widthAnchor.constraint(equalToConstant: 50),

    //-------
    buttonblue.centerYAnchor.constraint(equalTo: buttonred.centerYAnchor),
    buttonblue.leadingAnchor.constraint(equalTo: view.centerXAnchor,constant:40),
    buttonblue.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
    buttonblue.widthAnchor.constraint(equalTo:buttonred.widthAnchor)

       ])
     }
  }

So, I tried the following code to achieve by screen rotation i.e. two different layouts in potrait and landscape views programmatically with the help of the following code:-

import UIKit

class NewViewController: UIViewController {
override func viewDidLoad() {
let buttonredlandscape = UIButton()
buttonredlandscape.backgroundColor = UIColor.red
let buttonbluelandscape = UIButton()
buttonbluelandscape.backgroundColor = UIColor.blue
let buttonredportrait = UIButton()
buttonredportrait.backgroundColor = UIColor.red
let buttonblueportrait = UIButton()
buttonblueportrait.backgroundColor = UIColor.blue

let landscapesmallview = UIView()
let portraitsmallview = UIView()
landscapesmallview.backgroundColor = UIColor.gray
portraitsmallview.backgroundColor = UIColor.purple
landscapesmallview.frame = view.frame
portraitsmallview.frame = view.frame
view.addSubview(landscapesmallview)
view.addSubview(portraitsmallview)

landscapesmallview.addSubview(buttonredlandscape)
landscapesmallview.addSubview(buttonbluelandscape)
portraitsmallview.addSubview(buttonredportrait)
portraitsmallview.addSubview(buttonblueportrait)
buttonredlandscape.translatesAutoresizingMaskIntoConstraints = false
buttonbluelandscape.translatesAutoresizingMaskIntoConstraints = false
buttonredportrait.translatesAutoresizingMaskIntoConstraints = false
buttonblueportrait.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([

     buttonredlandscape.centerYAnchor.constraint(equalTo:landscapesmallview.centerYAnchor),
      buttonredlandscape.topAnchor.constraint(equalTo:landscapesmallview.topAnchor,constant:40),
    buttonredlandscape.trailingAnchor.constraint(equalTo:   landscapesmallview.centerXAnchor,constant:-20),
    buttonredlandscape.heightAnchor.constraint(equalTo:   landscapesmallview.heightAnchor,constant:50),

    buttonbluelandscape.centerYAnchor.constraint(equalTo:buttonredlandscape.centerYAnchor),
    buttonbluelandscape.leadingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:40),
    buttonbluelandscape.trailingAnchor.constraint(equalTo: landscapesmallview.trailingAnchor,constant:-20),
    buttonbluelandscape.heightAnchor.constraint(equalTo: buttonredlandscape.heightAnchor),

    buttonredportrait.topAnchor.constraint(equalTo: portraitsmallview.topAnchor,constant: 200),
    buttonredportrait.centerXAnchor.constraint(equalTo: portraitsmallview.centerXAnchor),
    buttonredportrait.trailingAnchor.constraint(equalTo: portraitsmallview.trailingAnchor,constant:-20),
    buttonredportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor),

    buttonblueportrait.topAnchor.constraint(equalTo: buttonredportrait.bottomAnchor,constant: 40),
    buttonblueportrait.leadingAnchor.constraint(equalTo: buttonredportrait.leadingAnchor),
    buttonblueportrait.trailingAnchor.constraint(equalTo:buttonredportrait.trailingAnchor),
    buttonblueportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor)

     ])

//-------

func viewWillTransition(to size: CGSize, with coordinator:    ) {
    if UIDevice.current.orientation.isLandscape {
        landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
        portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
     } else if UIDevice.current.orientation.isPortrait {
        portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
        landscapesmallview.translatesAutoresizingMaskIntoConstraints = true

        }
      }
    }
 }

which in potrait mode shows -

and which in landscape mode shows -

How to achieve what I want programmatically i.e. topmost 2 buttons to rearrange themselves programmatically every-time the user rotates the device. Its not just the buttons. It can be labels, images, collectionview etc. or just anything. The upshot is that I want to achieve two different layouts in landscape and portrait modes programmatically irrespective of the device.

Points to be noted :-

i) I have tried used NSLayoutAnchor with "NSLayoutConstraint.activate" because apple recommends it, but if the code can be made shorter(and faster) with some other method like visual format etc. I'm okay with that as well/

ii) If possible, I do not want to use stackview or containerview, because there can be many more types of labels, buttons etc, but if there is no other way, then I will use it.

iii) Is my code DRY principle compliant ?

Body:
There are various ways to do this. One approach:

declare two "constraint" arrays

one to hold the "narrow view" constraints

one to hold the "wide view" constraints

activate / deactivate the constraints as needed

Here is a complete example:

class ChangeLayoutViewController: UIViewController {

    let redButton: UIButton = {
        let v = UIButton()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        v.setTitle("Red Button", for: [])
        return v
    }()

    let blueButton: UIButton = {
        let v = UIButton()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .blue
        v.setTitle("Blue Button", for: [])
        return v
    }()

    var narrowConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]()
    var wideConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(redButton)
        view.addSubview(blueButton)

        let g = view.safeAreaLayoutGuide

        var c: NSLayoutConstraint

        // MARK: - narrow orientation

        // constrain redButton above blueButton

        // constrain redButton leading and trailing to safe-area (with 8-pts on each side)
        c = redButton.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 8.0)
        narrowConstraints.append(c)
        c = redButton.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -8.0)
        narrowConstraints.append(c)

        // constrain blueButton leading and trailing to safe-area (with 8-pts on each side)
        c = blueButton.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 8.0)
        narrowConstraints.append(c)
        c = blueButton.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -8.0)
        narrowConstraints.append(c)

        // constrain redButton top 40-pts from safe-area top
        c = redButton.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0)
        narrowConstraints.append(c)
        // constrain blueButton top 20-pts from redButton bottom
        c = blueButton.topAnchor.constraint(equalTo: redButton.bottomAnchor, constant: 20.0)
        narrowConstraints.append(c)

        // MARK: - wide orientation

        // constrain redButton & blueButton side-by-side
        //  with equal widths and 8-pts between them

        // constrain redButton leading 8-pts from safe-area leading
        c = redButton.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 8.0)
        wideConstraints.append(c)
        // constrain blueButton trailing 8-pts from safe-area trailing
        c = blueButton.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -8.0)
        wideConstraints.append(c)

        // constrain blueButton leading 8-pts from redButton trailing
        c = blueButton.leadingAnchor.constraint(equalTo: redButton.trailingAnchor, constant: 8.0)
        wideConstraints.append(c)

        // constrain buttons to equal widths
        c = blueButton.widthAnchor.constraint(equalTo: redButton.widthAnchor)
        wideConstraints.append(c)

        // constrain both buttons centerY to safe-area centerY
        c = redButton.centerYAnchor.constraint(equalTo: g.centerYAnchor)
        wideConstraints.append(c)
        c = blueButton.centerYAnchor.constraint(equalTo: g.centerYAnchor)
        wideConstraints.append(c)

        // activate initial constraints based on view width:height ratio
        changeConstraints(view.frame.width > view.frame.height)

    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        // change active set of constraints based on view width:height ratio
        self.changeConstraints(size.width > size.height)
    }

    func changeConstraints(_ useWide: Bool) -> Void {
        if useWide {
            NSLayoutConstraint.deactivate(narrowConstraints)
            NSLayoutConstraint.activate(wideConstraints)
        } else {
            NSLayoutConstraint.deactivate(wideConstraints)
            NSLayoutConstraint.activate(narrowConstraints)
        }
    }

}

Results:


来源: stackexchange

问:
Binomial distribution series in C Programming
I can write the pascal triangle with the code below.
But my wish is to print the
**

(a+b)^p

** series.
My wish is as follows. Sample output:

```<code>(a+b)^p for unfolding p = 5
1
a^1 + b^1
a^2 + 2*a^1*b^1 + b^2
a^3 + 3*a^2*b^1 + 3*a^1*b^2 + b^3
a^4 + 4*a^3*b^1 + 6*a^2*b^2 + 4*a^1*b^3 + b^4
a^5 + 5*a^4*b^1 + 10*a^3*b^2 + 10*a^2*b^3 + 5*a^1*b^4 + b^5
</code>```

/******** MY Code *********/

```<code> #include <stdio.h>
 long paskal(int,int);
 int main()
 {
   int n=0;
   int m=0;
   int k=0;
   int s=0;
   printf("Enter number of rows:\n");
   scanf("%d", &n);
   for(k = 0; n >= k; k++) {
        for(m = 0; k >= m; m++) {
              long f = paskal(k, m);
                if(k==1)
                    printf("%ld",f);
                else
                    printf("a^%ld %ld b^%ld",k,f,k);
        }
        printf("\n");
    }
    return 0;
 }

 long paskal(int n, int i) {
    if(n == i || i == 0)
      return 1;
    else
      return paskal(n-1, i) + paskal(n-1, i-1);

   }
</code>```

/********OUTPUT**********/

```<code>  Enter number of rows:
  5
  11
  a^2 1 b^2a^2 2 b^2a^2 1 b^2
  a^3 1 b^3a^3 3 b^3a^3 3 b^3a^3 1 b^3
  a^4 1 b^4a^4 4 b^4a^4 6 b^4a^4 4 b^4a^4 1 b^4
  a^5 1 b^5a^5 5 b^5a^5 10 b^5a^5 10 b^5a^5 5 b^5a^5 1 b^5
</code>```

I am sorry for my English. Thank You

答:
I solved the problem

```<code>#include <stdio.h>
int main()
{
  int s=0;
  printf("Lütfen sayı giriniz:\n");
  scanf("%ld", &s);
 while (s < 0)
 {
   printf("Lütfen pozitif sayı giriniz:\n");
   scanf("%d", &s);
  }
  printf("(a+b)^%ld =",s);
  printf("\n");
  for(int k = 0; s >= k; k++) {

    hesapla(k);
    printf("\n");
   }
  return 0;
  }
  void yazdir(int n,int r, int deger)
 {
   if(r== 0){
      if (n-r != 0) {
        if(deger == 1){
            printf("(a^%ld) +",n-r);
         }else{
           printf(" %ld*(a^%ld) +",deger,n-r);
       }
      } else {
          printf("1");
     }
   } else if(r>0 && r<n){
      printf(" %ld*(a^%ld*b^%ld) +",deger,n-r,r);
   } else{
      if(deger==1){
        printf(" (b^%ld)",r);
      } else {
         printf(" %ld*(b^%ld)",deger,r);
     }
  }
 }
 void hesapla (int n){
    int r;
     int deger;
    for (r=0;r<=n;r++) {
      deger = kombinasyon(n,r);
      yazdir(n,r,deger);
    }
  }
  int kombinasyon ( int n, int k) {
  if(k == 0){
    return 1;
  }
    if(k>n-k){
     return kombinasyon(n,n-k);
    }
     return n*kombinasyon(n-1,k-1)/k;

   }
</code>```

/******** OUTPUT ***********/

```<code>Lütfen sayı giriniz:
 5
 (a+b)^5 =
 1
 (a^1) + (b^1)
 (a^2) + 2*(a^1*b^1) + (b^2)
 (a^3) + 3*(a^2*b^1) + 3*(a^1*b^2) + (b^3)
 (a^4) + 4*(a^3*b^1) + 6*(a^2*b^2) + 4*(a^1*b^3) + (b^4)
 (a^5) + 5*(a^4*b^1) + 10*(a^3*b^2) + 10*(a^2*b^3) + 5*(a^1*b^4) + (b^5)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can write the pascal triangle with the code below.
But my wish is to print the
**

(a+b)^p

** series.
My wish is as follows. Sample output:

(a+b)^p for unfolding p = 5
1
a^1 + b^1
a^2 + 2*a^1*b^1 + b^2
a^3 + 3*a^2*b^1 + 3*a^1*b^2 + b^3
a^4 + 4*a^3*b^1 + 6*a^2*b^2 + 4*a^1*b^3 + b^4
a^5 + 5*a^4*b^1 + 10*a^3*b^2 + 10*a^2*b^3 + 5*a^1*b^4 + b^5

/******** MY Code *********/

 #include <stdio.h>
 long paskal(int,int);
 int main()
 {
   int n=0;
   int m=0;
   int k=0;
   int s=0;
   printf("Enter number of rows:\n");
   scanf("%d", &n);
   for(k = 0; n >= k; k++) {
        for(m = 0; k >= m; m++) {
              long f = paskal(k, m);
                if(k==1)
                    printf("%ld",f);
                else
                    printf("a^%ld %ld b^%ld",k,f,k);
        }
        printf("\n");
    }
    return 0;
 }

 long paskal(int n, int i) {
    if(n == i || i == 0)
      return 1;
    else
      return paskal(n-1, i) + paskal(n-1, i-1);

   }

/********OUTPUT**********/

  Enter number of rows:
  5
  11
  a^2 1 b^2a^2 2 b^2a^2 1 b^2
  a^3 1 b^3a^3 3 b^3a^3 3 b^3a^3 1 b^3
  a^4 1 b^4a^4 4 b^4a^4 6 b^4a^4 4 b^4a^4 1 b^4
  a^5 1 b^5a^5 5 b^5a^5 10 b^5a^5 10 b^5a^5 5 b^5a^5 1 b^5

I am sorry for my English. Thank You

Body:
I solved the problem

#include <stdio.h>
int main()
{
  int s=0;
  printf("Lütfen sayı giriniz:\n");
  scanf("%ld", &s);
 while (s < 0)
 {
   printf("Lütfen pozitif sayı giriniz:\n");
   scanf("%d", &s);
  }
  printf("(a+b)^%ld =",s);
  printf("\n");
  for(int k = 0; s >= k; k++) {

    hesapla(k);
    printf("\n");
   }
  return 0;
  }
  void yazdir(int n,int r, int deger)
 {
   if(r== 0){
      if (n-r != 0) {
        if(deger == 1){
            printf("(a^%ld) +",n-r);
         }else{
           printf(" %ld*(a^%ld) +",deger,n-r);
       }
      } else {
          printf("1");
     }
   } else if(r>0 && r<n){
      printf(" %ld*(a^%ld*b^%ld) +",deger,n-r,r);
   } else{
      if(deger==1){
        printf(" (b^%ld)",r);
      } else {
         printf(" %ld*(b^%ld)",deger,r);
     }
  }
 }
 void hesapla (int n){
    int r;
     int deger;
    for (r=0;r<=n;r++) {
      deger = kombinasyon(n,r);
      yazdir(n,r,deger);
    }
  }
  int kombinasyon ( int n, int k) {
  if(k == 0){
    return 1;
  }
    if(k>n-k){
     return kombinasyon(n,n-k);
    }
     return n*kombinasyon(n-1,k-1)/k;

   }

/******** OUTPUT ***********/

Lütfen sayı giriniz:
 5
 (a+b)^5 =
 1
 (a^1) + (b^1)
 (a^2) + 2*(a^1*b^1) + (b^2)
 (a^3) + 3*(a^2*b^1) + 3*(a^1*b^2) + (b^3)
 (a^4) + 4*(a^3*b^1) + 6*(a^2*b^2) + 4*(a^1*b^3) + (b^4)
 (a^5) + 5*(a^4*b^1) + 10*(a^3*b^2) + 10*(a^2*b^3) + 5*(a^1*b^4) + (b^5)


问:
IP spoofing with Selenium / Buying shared proxies?
I am scraping an e-commerce website with selenium, because the pages are loaded by Javascipt.

Here's the workflow -:
1. Instantiate a web diver driver in virtual display mode, while sending a random user agent. Using a random user-agent decreases you chances of detection just a little bit. This will not reduce the chances of blocking by IP.
2. For each query term, say "pajamas" - create the search url  for that website - and open the url.
3. Get the corresponding text elements from Xpath, say top 10 prod ids, their prices, title of product etc.
4. Store them in a file - that I will further process

I have upwards of 38000 such urls that I need to fetch for the elements on page load.
I did multiprocessing, and I realized quickly that the process was failing since after a while, the website was blocked, so the page load did not happen.

How can I IP spoof in Python and will it work with selenium driving the web for you, not urllib/urlopen ?

Aside of setting the actual fetch via the xpaths, here's the basic code - more specifically, see init_driver

```<code>from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import argparse
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import codecs, urllib, os
import multiprocessing as mp
from my_custom_path import scraping_conf_updated as sf
from fake_useragent import UserAgent

def set_cookies(COOKIES, exp, driver):
    for key, val in COOKIES[exp].items():
        driver.add_cookie({'name': key, 'value': val, 'path': '/', 'secure': False, 'expiry': None})
    return driver

def check_cookies(driver, exp):
    print "printing cookie name & value"
    for cookie in driver.get_cookies():
        if cookie['name'] in COOKIES[exp].keys():
            print cookie['name'], "-->", cookie['value']

def wait_for(driver):
    if conf_key['WAIT_FOR_ID'] != '':
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, conf_key['WAIT_FOR_ID'])))
    elif conf_key['WAIT_FOR_CLASS'] != '':
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS, conf_key['WAIT_FOR_CLASS'])))
    return driver

def init_driver(base_url, url, exp):
    display = Display(visible=0, size=(1024, 768))
    display.start()
    profile = webdriver.FirefoxProfile()
    ua = UserAgent(cache=False)
    profile.set_preference("general.useragent.override",ua.random)
    driver=webdriver.Firefox(profile)
    if len(conf_key['COOKIES'][exp]) != 0:
        driver.get(base_url)
        driver.delete_all_cookies()
        driver = set_cookies(COOKIES, exp, driver)
        check_cookies(driver, exp)
    driver.get(url)
    driver.set_page_load_timeout(300)
    if len(conf_key['POP_UP']['XPATH']) > 0:
        driver = identify_and_close_popup(driver)
    driver = wait_for(driver)
    return driver
</code>```

答: use a vpn provider or an http or socks proxy to change your apparent originating ip address from your target website</p>

ContentLicense: CC BY-SA 3.0

Body:
I am scraping an e-commerce website with selenium, because the pages are loaded by Javascipt.

Here's the workflow -:
1. Instantiate a web diver driver in virtual display mode, while sending a random user agent. Using a random user-agent decreases you chances of detection just a little bit. This will not reduce the chances of blocking by IP.
2. For each query term, say "pajamas" - create the search url  for that website - and open the url.
3. Get the corresponding text elements from Xpath, say top 10 prod ids, their prices, title of product etc.
4. Store them in a file - that I will further process

I have upwards of 38000 such urls that I need to fetch for the elements on page load.
I did multiprocessing, and I realized quickly that the process was failing since after a while, the website was blocked, so the page load did not happen.

How can I IP spoof in Python and will it work with selenium driving the web for you, not urllib/urlopen ?

Aside of setting the actual fetch via the xpaths, here's the basic code - more specifically, see init_driver

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import argparse
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import codecs, urllib, os
import multiprocessing as mp
from my_custom_path import scraping_conf_updated as sf
from fake_useragent import UserAgent

def set_cookies(COOKIES, exp, driver):
    for key, val in COOKIES[exp].items():
        driver.add_cookie({'name': key, 'value': val, 'path': '/', 'secure': False, 'expiry': None})
    return driver

def check_cookies(driver, exp):
    print "printing cookie name & value"
    for cookie in driver.get_cookies():
        if cookie['name'] in COOKIES[exp].keys():
            print cookie['name'], "-->", cookie['value']

def wait_for(driver):
    if conf_key['WAIT_FOR_ID'] != '':
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, conf_key['WAIT_FOR_ID'])))
    elif conf_key['WAIT_FOR_CLASS'] != '':
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS, conf_key['WAIT_FOR_CLASS'])))
    return driver

def init_driver(base_url, url, exp):
    display = Display(visible=0, size=(1024, 768))
    display.start()
    profile = webdriver.FirefoxProfile()
    ua = UserAgent(cache=False)
    profile.set_preference("general.useragent.override",ua.random)
    driver=webdriver.Firefox(profile)
    if len(conf_key['COOKIES'][exp]) != 0:
        driver.get(base_url)
        driver.delete_all_cookies()
        driver = set_cookies(COOKIES, exp, driver)
        check_cookies(driver, exp)
    driver.get(url)
    driver.set_page_load_timeout(300)
    if len(conf_key['POP_UP']['XPATH']) > 0:
        driver = identify_and_close_popup(driver)
    driver = wait_for(driver)
    return driver


问:
Why do I get the error Map is not defined using Google's V8 engine?
Hi I am willing to embedded MathJax for an applicaton I am developing. I chose V8 as the JS engine but I am having problem loading MathJax.

The issue I get is that "Map" is undefined. Shouldn't this be a standard JavaScript built-in object?

```<code>#include <stdio.h>
#include <v8.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

v8::Handle< v8::Value > include( const v8::Arguments & args ) {
   for ( int i = 0; i < args.Length(); i++ )
   {
      v8::String::Utf8Value str( args[ i ] );

      std::string js_file;
      std::ifstream in_file( *str );
      if ( in_file )
      {
         std::ostringstream ofs;
         ofs << in_file.rdbuf();
         js_file = ofs.str();
      }

      if( js_file.length() > 0 ) {
         v8::Handle< v8::String > source = v8::String::New( js_file.c_str() );
         v8::Handle< v8::Script > script = v8::Script::Compile( source );
         return script->Run();
      }
   }

   return v8::Undefined();
}

int main( int argc, char* argv[] ) {

   v8::V8::Initialize();
   v8::Isolate * isolate = v8::Isolate::New();

   {
      // Create a stack-allocated isolate scope.
      v8::Isolate::Scope isolate_scope( isolate );

      // Create a stack-allocated handle scope.
      v8::HandleScope handle_scope;

      v8::Handle< v8::ObjectTemplate > global = v8::ObjectTemplate::New();
      global->Set( v8::String::New( "include" ), v8::FunctionTemplate::New( include ) );

      // Create a new context.
      v8::Handle< v8::Context > context = v8::Context::New( NULL, global );
      // Enter the created context
      v8::Context::Scope context_scope( context );

      v8::Handle< v8::String > source = v8::String::New(
         "include( \"/home/elias/mathjax/es5/tex-mml-svg.js\" )"
      );

      // Compile the source code.
      v8::Handle< v8::Script > script = v8::Script::Compile( source );

      // Run the script to get the result.
      v8::Handle< v8::Value > result = script->Run();

      // Convert the result to an ASCII string and print it.
      v8::String::AsciiValue ascii( result );
      printf( "%s\n", * ascii );
   }
   // Dispose the isolate and tear down V8.
   isolate->Dispose();
   v8::V8::Dispose();

   return 0;
}
</code>```

Above you can see the code I am using. I had even to implement the include() function, which seems to be present when scripts are run in browsers.

I was imagining that it could be possible to run any scrpit using V8, but it seems not to be the case.

答:
Seeing #include <v8.h> make me guess that you're using the libv8-dev package on Ubuntu, which for a long time was V8's 3.14 branch, dating back to the year 2012. Map was added to the standard in EcmaScript 2015 (aka ES6) and shipped in V8's 3.28 branch in 2014.

I recommend that you get a recent V8 version (8.3 would be a good choice right now) from v8.dev.

Body:
Hi I am willing to embedded MathJax for an applicaton I am developing. I chose V8 as the JS engine but I am having problem loading MathJax.

The issue I get is that "Map" is undefined. Shouldn't this be a standard JavaScript built-in object?

#include <stdio.h>
#include <v8.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

v8::Handle< v8::Value > include( const v8::Arguments & args ) {
   for ( int i = 0; i < args.Length(); i++ )
   {
      v8::String::Utf8Value str( args[ i ] );

      std::string js_file;
      std::ifstream in_file( *str );
      if ( in_file )
      {
         std::ostringstream ofs;
         ofs << in_file.rdbuf();
         js_file = ofs.str();
      }

      if( js_file.length() > 0 ) {
         v8::Handle< v8::String > source = v8::String::New( js_file.c_str() );
         v8::Handle< v8::Script > script = v8::Script::Compile( source );
         return script->Run();
      }
   }

   return v8::Undefined();
}

int main( int argc, char* argv[] ) {

   v8::V8::Initialize();
   v8::Isolate * isolate = v8::Isolate::New();

   {
      // Create a stack-allocated isolate scope.
      v8::Isolate::Scope isolate_scope( isolate );

      // Create a stack-allocated handle scope.
      v8::HandleScope handle_scope;

      v8::Handle< v8::ObjectTemplate > global = v8::ObjectTemplate::New();
      global->Set( v8::String::New( "include" ), v8::FunctionTemplate::New( include ) );

      // Create a new context.
      v8::Handle< v8::Context > context = v8::Context::New( NULL, global );
      // Enter the created context
      v8::Context::Scope context_scope( context );

      v8::Handle< v8::String > source = v8::String::New(
         "include( \"/home/elias/mathjax/es5/tex-mml-svg.js\" )"
      );

      // Compile the source code.
      v8::Handle< v8::Script > script = v8::Script::Compile( source );

      // Run the script to get the result.
      v8::Handle< v8::Value > result = script->Run();

      // Convert the result to an ASCII string and print it.
      v8::String::AsciiValue ascii( result );
      printf( "%s\n", * ascii );
   }
   // Dispose the isolate and tear down V8.
   isolate->Dispose();
   v8::V8::Dispose();

   return 0;
}

Above you can see the code I am using. I had even to implement the include() function, which seems to be present when scripts are run in browsers.

I was imagining that it could be possible to run any scrpit using V8, but it seems not to be the case.


问:
React native TouchableOpacity onPress not working on Android
TouchabelOpacity works fine on iOS but the onPress method does not work on Android for me.

My react-native version: 0.57.4

My code:

```<code>const initDrawer = navigation => (
  <TouchableOpacity
    style={{ left: 16 }}
    onPress={() => onPressDrawerButton(navigation)}
  >
    <Ionicons name="ios-menu" color="white" size={30} />
  </TouchableOpacity>
);
</code>```

答:
My problem wasn't listed here, so wanted to add it.

On Android if you have the TouchableOpacity inside a KeyboardAvoidingView, it won't work (at least with the settings I was using).

As soon as I scoped the KeyboardAvoidingView to only be around the input fields and not my TouchableOpacities, it started working again.

(It was fine on IOS btw)

Body:
TouchabelOpacity works fine on iOS but the onPress method does not work on Android for me.

My react-native version: 0.57.4

My code:

const initDrawer = navigation => (
  <TouchableOpacity
    style={{ left: 16 }}
    onPress={() => onPressDrawerButton(navigation)}
  >
    <Ionicons name="ios-menu" color="white" size={30} />
  </TouchableOpacity>
);


问:
How do I measure elapsed time in Python?
I want to measure the time it took to execute a function. I couldn't get timeit to work:

```<code>import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
</code>```

答:
Here's a pretty well documented and fully type hinted decorator I use as a general utility:

```<code>from functools import wraps
from time import perf_counter
from typing import Any, Callable, Optional, TypeVar, cast

F = TypeVar("F", bound=Callable[..., Any])

def timer(prefix: Optional[str] = None, precision: int = 6) -> Callable[[F], F]:
    """Use as a decorator to time the execution of any function.

    Args:
        prefix: String to print before the time taken.
            Default is the name of the function.
        precision: How many decimals to include in the seconds value.

    Examples:
        >>> @timer()
        ... def foo(x):
        ...     return x
        >>> foo(123)
        foo: 0.000...s
        123
        >>> @timer("Time taken: ", 2)
        ... def foo(x):
        ...     return x
        >>> foo(123)
        Time taken: 0.00s
        123

    """
    def decorator(func: F) -> F:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            nonlocal prefix
            prefix = prefix if prefix is not None else f"{func.__name__}: "
            start = perf_counter()
            result = func(*args, **kwargs)
            end = perf_counter()
            print(f"{prefix}{end - start:.{precision}f}s")
            return result
        return cast(F, wrapper)
    return decorator
</code>```

Example usage:

```<code>from timer import timer

@timer(precision=9)
def takes_long(x: int) -> bool:
    return x in (i for i in range(x + 1))

result = takes_long(10**8)
print(result)
</code>```

Output:

takes_long: 4.942629056s
True
```
</blockquote>
<p>The doctests can be checked with:</p>
```$ python3 -m doctest --verbose -o=ELLIPSIS timer.py
```
<p>And the type hints with:</p>
```$ mypy timer.py
```

Body:
I want to measure the time it took to execute a function. I couldn't get timeit to work:

import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)

Body:
Here's a pretty well documented and fully type hinted decorator I use as a general utility:

from functools import wraps
from time import perf_counter
from typing import Any, Callable, Optional, TypeVar, cast

F = TypeVar("F", bound=Callable[..., Any])

def timer(prefix: Optional[str] = None, precision: int = 6) -> Callable[[F], F]:
    """Use as a decorator to time the execution of any function.

    Args:
        prefix: String to print before the time taken.
            Default is the name of the function.
        precision: How many decimals to include in the seconds value.

    Examples:
        >>> @timer()
        ... def foo(x):
        ...     return x
        >>> foo(123)
        foo: 0.000...s
        123
        >>> @timer("Time taken: ", 2)
        ... def foo(x):
        ...     return x
        >>> foo(123)
        Time taken: 0.00s
        123

    """
    def decorator(func: F) -> F:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            nonlocal prefix
            prefix = prefix if prefix is not None else f"{func.__name__}: "
            start = perf_counter()
            result = func(*args, **kwargs)
            end = perf_counter()
            print(f"{prefix}{end - start:.{precision}f}s")
            return result
        return cast(F, wrapper)
    return decorator

Example usage:

from timer import timer

@timer(precision=9)
def takes_long(x: int) -> bool:
    return x in (i for i in range(x + 1))

result = takes_long(10**8)
print(result)

Output:

takes_long: 4.942629056s
True

The doctests can be checked with:

$ python3 -m doctest --verbose -o=ELLIPSIS timer.py

And the type hints with:

$ mypy timer.py


问:
Spark unable to write to S3 Encrypted Bucket even after specifying the hadoopConfigs
When i try to write to an S3 Bucket which is AES-256 Encrypted from my Spark Streaming App running on EMR it is throwing 403. For what ever reason the Spark Session is not honoring the "fs.s3a.server-side-encryption-algorithm" config option.

Here is the code i am using.

```<code>sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.access.key",accessKeyId);
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.secret.key", secretKeyId);
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.server-side-encryption-algorithm","AES256");
</code>```

When i use regular Java Code using AWS SDK i can upload the files without any issues.

Some how the Spark Session is not honoring this.

Thanks
Sateesh

答:
Able to resolve it. Silly mistake on my part.

We need to have the following property as well.

```<code>sparkSession.sparkContext().hadoopConfiguration().set("fs.s3.enableServerSideEncryption","true");
</code>```

Body:
When i try to write to an S3 Bucket which is AES-256 Encrypted from my Spark Streaming App running on EMR it is throwing 403. For what ever reason the Spark Session is not honoring the "fs.s3a.server-side-encryption-algorithm" config option.

Here is the code i am using.

sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.access.key",accessKeyId);
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.secret.key", secretKeyId);
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.server-side-encryption-algorithm","AES256");

When i use regular Java Code using AWS SDK i can upload the files without any issues.

Some how the Spark Session is not honoring this.

Thanks
Sateesh

Body:
Able to resolve it. Silly mistake on my part.

We need to have the following property as well.

sparkSession.sparkContext().hadoopConfiguration().set("fs.s3.enableServerSideEncryption","true");


问:
Django: How to read question mark (?) in the django URL
I am developing a Django app that stores the user input in the database. Now the problem is that when the user writes the ? in the input field, Django treats it as the part of querystring so it doesn't save it.

I am using the following JavaScript code:

```<code>$("#submit").on("click",function(){
    text = $("#input").val();
    $.get('/add/'+text);
}
</code>```

And here is my urls.py file:

```<code>urlpatterns = [
     path('add/<str:text>',views.add, name='add'),
     ..............
]
</code>```

And in views.py, I have:

```<code>def add(request,text):
    field = Text(text=text)
    field.save()
    return HttpResponse('')

</code>```

答:
That is because you did not encode it properly. You need to use percentage encoding [wiki] to encode data in a URL.

In JavaScript, you can use the encodeURIComponent function for that:

```<code>$("#submit").on("click",function(){
    text = $("#input").val();
    $.get('/add/'+<b>encodeURIComponent(</b>text<b>)</b>);
}</code>```

The question mark will thus be encoded to %3F, since this is the character that maps on codepoint 63 (or 0x3f as hexadecimal number).

Note that a str will not match a slash. You thus might want to use a path instead:

```<code>urlpatterns = [
     path('add/<<b>path:</b>text>',views.add, name='add'),
     # …
]</code>```

If you however create, delete, update, etc. records, then you should use a POST, PUT, PATCH or DELETE request, since GET requests are supposed to have no side-effects. In that case it might be better to pass the data as request payload.

Body:
I am developing a Django app that stores the user input in the database. Now the problem is that when the user writes the ? in the input field, Django treats it as the part of querystring so it doesn't save it.

I am using the following JavaScript code:

$("#submit").on("click",function(){
    text = $("#input").val();
    $.get('/add/'+text);
}

And here is my urls.py file:

urlpatterns = [
     path('add/<str:text>',views.add, name='add'),
     ..............
]

And in views.py, I have:

def add(request,text):
    field = Text(text=text)
    field.save()
    return HttpResponse('')

Body:
That is because you did not encode it properly. You need to use percentage encoding [wiki] to encode data in a URL.

In JavaScript, you can use the encodeURIComponent function for that:

$("#submit").on("click",function(){
    text = $("#input").val();
    $.get('/add/'+encodeURIComponent(text));
}

The question mark will thus be encoded to %3F, since this is the character that maps on codepoint 63 (or 0x3f as hexadecimal number).

Note that a str will not match a slash. You thus might want to use a path instead:

urlpatterns = [
     path('add/<path:text>',views.add, name='add'),
     # …
]

If you however create, delete, update, etc. records, then you should use a POST, PUT, PATCH or DELETE request, since GET requests are supposed to have no side-effects. In that case it might be better to pass the data as request payload.


问:
MongoDB pagination on arrays - Check if $slice reached the beginning of the array
In my application i have an box where users can read comments. If some user scrolls down, it loads more and more comments, everything fine. I slice the array from the back to the begin because i use $push whenever somebody write some comment so i slice it like this $slice: [ -5 , 5]. This will slice the last 5 elements out of the array. The -5 is actually an variable in my aggregation pipeline. Whenever i loaded some comments i decrease the value from -5 to -10 and so on so on. The problem i got here is if my array has an legth for example of 50, and i execute this slice $slice: [ -70, 5] i get the first 5 comments, but i expected to receive 0. The result is that i have an infinity scrollbar witch loads over and over the same 5 first comments. How do i fix this?

```<code>let result = await Post.aggregate([
    {
      $match: {
        _id: userId,
        "posts._id": postId
      }
    },
    {
      $addFields: {
        posts: {
          $map: {
            input: "$posts",
            as: "p",
            in: {
              _id: "$$p._id",
              comments: { $slice: ["$$p.comments", -start, 5] }
            }
          }
        }
      }
    },
    {
      $project: {
        posts: {
          $filter: {
            input: "$posts",
            as: "posts",
            cond: { $eq: ["$$posts._id", postId] }
          }
        }
      }
    }
  ]);
</code>```

答:
@lfaruki, I think you are on the right track reversing the array, as from the documentation, as also explained by @whoami

<position> If positive, $slice determines the starting position from the start of the array. If <position> is greater than the number of elements, the $slice returns an empty array.

```<code>comments: {
  $reverseArray: { // reverse back
    $slice: [
      {
        $reverseArray: "$comments"
      },
      endOffset, // this starts from 0, 5, 10, 15, ...
      5
    ]
  }
}
</code>```

I'm not sure what issues you faced when you try to implement it using the reverse array. But my general advice is it would have negative effect on performance on large arrays. If you already have your comments in a separate collection, better query it separately using "time-based" or "cursor-based" pagination. Because ultimately MongoDB has limits on document size and you don't want to process large arrays in aggregation.

Body:
In my application i have an box where users can read comments. If some user scrolls down, it loads more and more comments, everything fine. I slice the array from the back to the begin because i use $push whenever somebody write some comment so i slice it like this $slice: [ -5 , 5]. This will slice the last 5 elements out of the array. The -5 is actually an variable in my aggregation pipeline. Whenever i loaded some comments i decrease the value from -5 to -10 and so on so on. The problem i got here is if my array has an legth for example of 50, and i execute this slice $slice: [ -70, 5] i get the first 5 comments, but i expected to receive 0. The result is that i have an infinity scrollbar witch loads over and over the same 5 first comments. How do i fix this?

let result = await Post.aggregate([
    {
      $match: {
        _id: userId,
        "posts._id": postId
      }
    },
    {
      $addFields: {
        posts: {
          $map: {
            input: "$posts",
            as: "p",
            in: {
              _id: "$$p._id",
              comments: { $slice: ["$$p.comments", -start, 5] }
            }
          }
        }
      }
    },
    {
      $project: {
        posts: {
          $filter: {
            input: "$posts",
            as: "posts",
            cond: { $eq: ["$$posts._id", postId] }
          }
        }
      }
    }
  ]);

Body:
@lfaruki, I think you are on the right track reversing the array, as from the documentation, as also explained by @whoami

<position> If positive, $slice determines the starting position from the start of the array. If <position> is greater than the number of elements, the $slice returns an empty array.

comments: {
  $reverseArray: { // reverse back
    $slice: [
      {
        $reverseArray: "$comments"
      },
      endOffset, // this starts from 0, 5, 10, 15, ...
      5
    ]
  }
}

I'm not sure what issues you faced when you try to implement it using the reverse array. But my general advice is it would have negative effect on performance on large arrays. If you already have your comments in a separate collection, better query it separately using "time-based" or "cursor-based" pagination. Because ultimately MongoDB has limits on document size and you don't want to process large arrays in aggregation.


问:
survIDINRI package ERROR res.IDI.INF function R
I'm trying to calculate the integrated discrimination improvement for two Cox regression models (time, event), using the survIDINRI package and the res.IDI.INF function. However, I'm get an error message pointing towards an NA/NaN/Inf problem.

This is the code for the function:

```<code>#time = numeric (years) (max 15 years)
#event, censored = 0, event = 1
res.IDI.INF <- IDI.INF(indata = data[,c("time","event")],
                       covs0,
                       covs1,
                       t0 = 15,
                       npert = 300, npert.rand = NULL, seed1 = NULL, alpha = 0.05)
IDI.INF.OUT(res.IDI.INF)
</code>```

And I get the following error message:

```<code>Error in unoecdf(cc, pdiff[case], Wi[case] * PTB.Vi[case]) :
  NA/NaN/Inf in foreign function call (arg 5)

</code>```

Would be great if there is a solution. Thanks in advance.

答:
I hope my answer is not too late but maybe the cause of your problem comes from the argument "t0" in the function. I think that this argument must be in days and not in years, try to write t0 = 15*365, I think that it should work :)

Good luck

Body:
I'm trying to calculate the integrated discrimination improvement for two Cox regression models (time, event), using the survIDINRI package and the res.IDI.INF function. However, I'm get an error message pointing towards an NA/NaN/Inf problem.

This is the code for the function:

#time = numeric (years) (max 15 years)
#event, censored = 0, event = 1
res.IDI.INF <- IDI.INF(indata = data[,c("time","event")],
                       covs0,
                       covs1,
                       t0 = 15,
                       npert = 300, npert.rand = NULL, seed1 = NULL, alpha = 0.05)
IDI.INF.OUT(res.IDI.INF)

And I get the following error message:

Error in unoecdf(cc, pdiff[case], Wi[case] * PTB.Vi[case]) :
  NA/NaN/Inf in foreign function call (arg 5)

Would be great if there is a solution. Thanks in advance.


问:
Images with BBcode (php, preg_replace). Security question
Bbcode question. This:

```<code>$text = preg_replace("@\[img\](.*)\[\/img\]@si",
"<img src=\"$1\" border=\"0\" />", $text);
</code>```

works fine, but at the same time it's a big security problem, for example:

```<code>[img]http://www.domain.com/delete-account/[/img]
</code>```

or

```<code>[img]http://www.domain.com/logout/[/img]
</code>```

Any ideas how to control this so that only image links which ends with .jpg are being converted into html?

```<code>[img]http://www.domain.com/image.jpg[/img]
</code>```

Thanks.

答:
According to the HTTP1.1 standard, requesting URLs with GET (the method used to acquire images) should not result in any actions, such as logout. Therefore, you don't need to restrict to URLs with a .jpg at the end, and in general, it is a bad idea because there are other image formats, and the URL is in general unrelated to its content type.

More to the point, if requesting a URL does change a state of a server vulnerable.net, this Cross Site Request Forgery Vulnerability can be exploited anyway by setting up a custom server that 302-redirects http://evil.com/img.jpg to http://vulnerable.net/logout.

FYI, if you really wanted to replace only URLs ending with .jpg, you can just insert it in the group:

```<code>$text = preg_replace("@\[img\](.*\.jpg)\[\/img\]@si",
                     "<img src=\"$1\" border=\"0\" />", $text);
</code>```

But this is not a security mechanism, and fails if the browser (or a aggressively caching proxy, or a virus scanner, or ...) prefetches URLs. GET requests should not result in any action.

Body:
Bbcode question. This:

$text = preg_replace("@\[img\](.*)\[\/img\]@si",
"", $text);

works fine, but at the same time it's a big security problem, for example:

[img]http://www.domain.com/delete-account/[/img]

or

[img]http://www.domain.com/logout/[/img]

Any ideas how to control this so that only image links which ends with .jpg are being converted into html?

[img]http://www.domain.com/image.jpg[/img]

Thanks.

Body:
According to the HTTP1.1 standard, requesting URLs with GET (the method used to acquire images) should not result in any actions, such as logout. Therefore, you don't need to restrict to URLs with a .jpg at the end, and in general, it is a bad idea because there are other image formats, and the URL is in general unrelated to its content type.

More to the point, if requesting a URL does change a state of a server vulnerable.net, this Cross Site Request Forgery Vulnerability can be exploited anyway by setting up a custom server that 302-redirects http://evil.com/img.jpg to http://vulnerable.net/logout.

FYI, if you really wanted to replace only URLs ending with .jpg, you can just insert it in the group:

$text = preg_replace("@\[img\](.*\.jpg)\[\/img\]@si",
                     "<img src=\"$1\" border=\"0\" />", $text);

But this is not a security mechanism, and fails if the browser (or a aggressively caching proxy, or a virus scanner, or ...) prefetches URLs. GET requests should not result in any action.


问:
Pulling data from API - GET
I'm trying to pull all planets names via the Star Wars API: https://swapi.dev/

Not sure where my error is in the code below?

```<code>import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/",
            withCredentials: true
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data;
            this.setState({planets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    render() {
        return (
          <div>
            <h1>Star Wars Planets</h1>
              {
                this.state.planets.map(planet =>
                    <div>
                        <p>planet.name</p>
                    </div>
                )
              }
          </div>
        )
    }
}

export default Home
</code>```

答:
Looking at https://swapi.dev/api/planets/ I can see that maybe you should do something like:</p>

```<code>let planetslist = response.data.results;
</code>```

Title: Pulling data from API - GET

Body:
I'm trying to pull all planets names via the Star Wars API: https://swapi.dev/

Not sure where my error is in the code below?

import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/",
            withCredentials: true
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data;
            this.setState({planets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    render() {
        return (

Star Wars Planets

              {
                this.state.planets.map(planet =>

planet.name

                )
              }

        )
    }
}

export default Home

Body:
Looking at https://swapi.dev/api/planets/ I can see that maybe you should do something like:

let planetslist = response.data.results;


问:
Different results trying to solve the same problem using for and while loops in python
Hi! I am new to coding and was trying to solve I tried to solve a problem that required me to sum all of the negative integers in a list using loops. I tried to solve the problem using both for and while loops but got different answers.

For Loop Code

```<code>glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
    if glist3[i]<0:
        total3+=glist3[i]
print(total3)
</code>```

While Loop Code

```<code>glist4 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
i2=0
total4=0
while i2 < len(glist4):
    if glist4[i2] < 0:
        total4+=glist4[i2]
    i2+=1
print (total4)
</code>```

The Result I got for the for loop is -12 (which is incorrect), but the while loop did give back the correct answer which is -13. Just wanted to ask for possible causes for this discrepancy. Thank you!

答:
While loops loop until the condition defined next to the "while" keyword is met.

For loops loop through iterators, for example: lists, dictionaries or even files.

So if you loop for example through a list of fruits like this:

```<code>fruits = ['banana', 'apple', 'mango', 'pear', 'pineapple']
for fruit in fruits:
</code>```

The variable "fruit" will be equal to "banana" during the first loop, then "apple" the second and so on. "fruit" will not be equal to the index of the item. So in that example doing:

```<code>fruits = ['banana', 'apple', 'mango', 'pear', 'pineapple']
for fruit in fruits:
    print(fruits[fruit])
</code>```

would result in an error since fruit is not an integer but a string.

If you wish to keep track of the index during a for loop you need to set a variable out of the for loop and then increment it in the loop.

Here's a working example of what you want to do using a for loop:

```<code>glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3 = 0
for number in glist3:
    if number < 0:
        total3 += number
print(total3)
</code>```

Body:
Hi! I am new to coding and was trying to solve I tried to solve a problem that required me to sum all of the negative integers in a list using loops. I tried to solve the problem using both for and while loops but got different answers.

For Loop Code

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
    if glist3[i]<0:
        total3+=glist3[i]
print(total3)

While Loop Code

glist4 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
i2=0
total4=0
while i2 < len(glist4):
    if glist4[i2] < 0:
        total4+=glist4[i2]
    i2+=1
print (total4)

The Result I got for the for loop is -12 (which is incorrect), but the while loop did give back the correct answer which is -13. Just wanted to ask for possible causes for this discrepancy. Thank you!

Body:
While loops loop until the condition defined next to the "while" keyword is met.

For loops loop through iterators, for example: lists, dictionaries or even files.

So if you loop for example through a list of fruits like this:

fruits = ['banana', 'apple', 'mango', 'pear', 'pineapple']
for fruit in fruits:

The variable "fruit" will be equal to "banana" during the first loop, then "apple" the second and so on. "fruit" will not be equal to the index of the item. So in that example doing:

fruits = ['banana', 'apple', 'mango', 'pear', 'pineapple']
for fruit in fruits:
    print(fruits[fruit])

would result in an error since fruit is not an integer but a string.

If you wish to keep track of the index during a for loop you need to set a variable out of the for loop and then increment it in the loop.

Here's a working example of what you want to do using a for loop:

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3 = 0
for number in glist3:
    if number < 0:
        total3 += number
print(total3)


问:
how to add class to 9 divs random in javascript avoid repetition
Hi Guys anyone who can help me please.
I want to add class radom to 9 divs without repetition and it must at least skip 3 divs before adding next class.

My current problem it doesn't skip divs it just adding from index 0 to 8 without skipping any index.

I want to add 9 classes random to divs. Please see my code below.

jQuery(document).ready(function( $ ){
    // Your code in here
var classes = ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"];

  $(".productRow .productWrapper .productItem").each(function(){
    var getClass = classes.splice(~~(Math.random()*classes.length), 1)[0];
    $(this).addClass(getClass);
    $(this).append("
");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="productRow">
    <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>

        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>

        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>

        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>

        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
</div></code>```

答:
You are telling it to do each and every item, thus, it's doing exactly what you told it to do:

```<code>$(".productRow .productWrapper .productItem").each(function(){
                                              ^^^^
</code>```

If you want to have it "skip" products, you need to track how many to skip, and thus which one to use.

It may be better if you do NOT use each, but instead, a for loop. But let's try to do it with your each loop by using a variable to keep track of your current item.

```<code>currentProduct = 0
$(".productRow .productWrapper .productItem").each(function(){
  if ((currentProduct % 4) === 0) {  // currentProduct modulus 4 = 0, i.e, 0, 4, 8, etc
    //do whatever you want to do
  }
  currentProduct++;
}
</code>```

You can adjust the loop to run for different offset, different loop size, etc.

Body:
Hi Guys anyone who can help me please.
I want to add class radom to 9 divs without repetition and it must at least skip 3 divs before adding next class.

My current problem it doesn't skip divs it just adding from index 0 to 8 without skipping any index.

I want to add 9 classes random to divs. Please see my code below.

jQuery(document).ready(function( $ ){
    // Your code in here
var classes = ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"];

  $(".productRow .productWrapper .productItem").each(function(){
    var getClass = classes.splice(~~(Math.random()*classes.length), 1)[0];
    $(this).addClass(getClass);
    $(this).append("
");
  });
});

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Body:
You are telling it to do each and every item, thus, it's doing exactly what you told it to do:

$(".productRow .productWrapper .productItem").each(function(){
                                              ^^^^

If you want to have it "skip" products, you need to track how many to skip, and thus which one to use.

It may be better if you do NOT use each, but instead, a for loop. But let's try to do it with your each loop by using a variable to keep track of your current item.

currentProduct = 0
$(".productRow .productWrapper .productItem").each(function(){
  if ((currentProduct % 4) === 0) {  // currentProduct modulus 4 = 0, i.e, 0, 4, 8, etc
    //do whatever you want to do
  }
  currentProduct++;
}

You can adjust the loop to run for different offset, different loop size, etc.


问:
Linq: using let statement based on string to group data
Here´s my scenario...

Supposing i have this class (called nf) w/values:

```<code>MyDate,Tons,ClientCode
25/12/2020,10,A
26/12/2020,5,A
27/12/2020,5,A
14/12/2020,7,A
11/12/2020,3,A
</code>```

So i wrote the following code to get results grouped.

```<code>   List<HC> nfs = (from n in ctx.nf
                   where n.ClientCode.StartsWith(CLIENT_CODE_STR)
                   let quinzena = $"{n.MyDate.Year}/{n.MyDate.Month}/{(n.DataEmissao.Day >= 1 && n.MyDate.Day <= 15 ? "1QZ" : "2QZ")}"
                   group n by new { quinzena } into g
                   select new { qnz = g.Key.quinzena, totalc = g.Sum(x => x.Tons) }
                  ).Take(12)
                  .OrderByDescending(a => a.qnz)
                  .AsEnumerable()
                  .Select(r=> new HC{ Period = r.qnz, TotalTons = r.totalc }).ToList();
</code>```

The expected result is:

```<code>Period,TotalTons
2020/12/1QZ,10
2020/12/2QZ,20
</code>```

The point is the let statement... which is used to group data properly...
When the code runs I get this error...

LINQ to Entities does not recognize the method 'System.String
  Format(System.String, System.Object, System.Object, System.Object)'
  method, and this method cannot be translated into a store expression.

Is there a way to perform this grouping??
thx a lot

答:
Why not keep those values separate until you need to combine them in memory.</p>

```<code>List<HC> nfs = (from n in ctx.nf
               where n.ClientCode.StartsWith(CLIENT_CODE_STR)
               let q = n.DataEmissao.Day >= 1 && n.MyDate.Day <= 15 ? "1QZ" : "2QZ"
               group n by new { n.MayDate.Year, n.MayDate.Month, Q = q } into g
               select new { qnz = g.Key, totalc = g.Sum(x => x.Tons) }
              ).Take(12)
              .OrderByDescending(a => a.qnz.Year)
              .ThenByDescending(a => a.qnz.Month)
              .ThenByDescending(a => a.qnz.Q)
              .AsEnumerable()
              .Select(r=> new HC
              {
                  Period = $"{r.qnzYear}/{r.qnz.Month}/{r.qnz.Q}",
                  TotalTons = r.totalc
              })
              .ToList();
</code>```

Body:
Here´s my scenario...

Supposing i have this class (called nf) w/values:

MyDate,Tons,ClientCode
25/12/2020,10,A
26/12/2020,5,A
27/12/2020,5,A
14/12/2020,7,A
11/12/2020,3,A

So i wrote the following code to get results grouped.

   List<HC> nfs = (from n in ctx.nf
                   where n.ClientCode.StartsWith(CLIENT_CODE_STR)
                   let quinzena = $"{n.MyDate.Year}/{n.MyDate.Month}/{(n.DataEmissao.Day >= 1 && n.MyDate.Day <= 15 ? "1QZ" : "2QZ")}"
                   group n by new { quinzena } into g
                   select new { qnz = g.Key.quinzena, totalc = g.Sum(x => x.Tons) }
                  ).Take(12)
                  .OrderByDescending(a => a.qnz)
                  .AsEnumerable()
                  .Select(r=> new HC{ Period = r.qnz, TotalTons = r.totalc }).ToList();

The expected result is:

Period,TotalTons
2020/12/1QZ,10
2020/12/2QZ,20

The point is the let statement... which is used to group data properly...
When the code runs I get this error...

LINQ to Entities does not recognize the method 'System.String
  Format(System.String, System.Object, System.Object, System.Object)'
  method, and this method cannot be translated into a store expression.

Is there a way to perform this grouping??
thx a lot

Body:
Why not keep those values separate until you need to combine them in memory.

List<HC> nfs = (from n in ctx.nf
               where n.ClientCode.StartsWith(CLIENT_CODE_STR)
               let q = n.DataEmissao.Day >= 1 && n.MyDate.Day <= 15 ? "1QZ" : "2QZ"
               group n by new { n.MayDate.Year, n.MayDate.Month, Q = q } into g
               select new { qnz = g.Key, totalc = g.Sum(x => x.Tons) }
              ).Take(12)
              .OrderByDescending(a => a.qnz.Year)
              .ThenByDescending(a => a.qnz.Month)
              .ThenByDescending(a => a.qnz.Q)
              .AsEnumerable()
              .Select(r=> new HC
              {
                  Period = $"{r.qnzYear}/{r.qnz.Month}/{r.qnz.Q}",
                  TotalTons = r.totalc
              })
              .ToList();


问:
how to deploy GWT app to tomcat
I searched this site for answer to this question and couldn't find a solution.
what i did is that i simply compress the war directory in my eclipse GWT app project then rename it to .war then drop it to tomcat webapps folder.
when i run the web app, the first screen is successfully shown but when i call a servlet within my  src code it gives me resource not found by tomcat server.
i'm sure i have added entry for servlet in web.xml file and the app worked well when i run it in eclipse gwt dev mode. something prevent my servlets (standard servlets not GWT RPC servlets) to be found and executed by tomcat. what could be the reason?

UPDATE

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

  <!-- Servlets -->

  <servlet>
        <servlet-name>OAuth</servlet-name>
        <servlet-class>org.goauth.server.OAuthServlet</servlet-class>

    </servlet>
    <servlet-mapping>
        <servlet-name>OAuth</servlet-name>
        <url-pattern>/goauth/oauth</url-pattern>
    </servlet-mapping>
     <servlet>
        <servlet-name>OAuthCallback</servlet-name>

        <servlet-class>org.goauth.server.OAuthCallbackServlet</servlet-class>

    </servlet>
    <servlet-mapping>
        <servlet-name>OAuthCallback</servlet-name>
        <url-pattern>/goauth/callback</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>service</servlet-name>

        <servlet-class>org.goauth.server.OAuthServiceImpl</servlet-class>

    </servlet>
    <servlet-mapping>
        <servlet-name>service</servlet-name>
        <url-pattern>/goauth/service</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>OAuthConfirm</servlet-name>
        <servlet-class>org.goauth.server.OAuthConfirmServlet</servlet-class>

    </servlet>
    <servlet-mapping>
        <servlet-name>OAuthConfirm</servlet-name>
        <url-pattern>/goauth/confirm</url-pattern>
    </servlet-mapping>
  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>GOAuth.html</welcome-file>
  </welcome-file-list>
</web-app>
</code>```

Error

nothing in tomcate logs files
the only error in browser is :

```<code>HTTP Status 404 - /goauth/oauth

type Status report

message /goauth/oauth

description The requested resource (/goauth/oauth) is not available.
Apache Tomcat/6.0.20
</code>```

答: Take a look at how to create a GWT .war in eclipse: http://blog.elitecoderz.net/gwt-and-tomcat-create-war-using-eclipse-to-deploy-war-on-tomcat/2009/12/</p>

Title: how to deploy GWT app to tomcat

Body:
I searched this site for answer to this question and couldn't find a solution.
what i did is that i simply compress the war directory in my eclipse GWT app project then rename it to .war then drop it to tomcat webapps folder.
when i run the web app, the first screen is successfully shown but when i call a servlet within my  src code it gives me resource not found by tomcat server.
i'm sure i have added entry for servlet in web.xml file and the app worked well when i run it in eclipse gwt dev mode. something prevent my servlets (standard servlets not GWT RPC servlets) to be found and executed by tomcat. what could be the reason?

UPDATE

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

  <servlet>
        <servlet-name>OAuth</servlet-name>
        <servlet-class>org.goauth.server.OAuthServlet</servlet-class>

    </servlet>
    <servlet-mapping>
        <servlet-name>OAuth</servlet-name>
        <url-pattern>/goauth/oauth</url-pattern>
    </servlet-mapping>
     <servlet>
        <servlet-name>OAuthCallback</servlet-name>

        <servlet-class>org.goauth.server.OAuthCallbackServlet</servlet-class>

    </servlet>
    <servlet-mapping>
        <servlet-name>OAuthCallback</servlet-name>
        <url-pattern>/goauth/callback</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>service</servlet-name>

        <servlet-class>org.goauth.server.OAuthServiceImpl</servlet-class>

    </servlet>
    <servlet-mapping>
        <servlet-name>service</servlet-name>
        <url-pattern>/goauth/service</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>OAuthConfirm</servlet-name>
        <servlet-class>org.goauth.server.OAuthConfirmServlet</servlet-class>

    </servlet>
    <servlet-mapping>
        <servlet-name>OAuthConfirm</servlet-name>
        <url-pattern>/goauth/confirm</url-pattern>
    </servlet-mapping>

  <welcome-file-list>
    <welcome-file>GOAuth.html</welcome-file>
  </welcome-file-list>
</web-app>

Error

nothing in tomcate logs files
the only error in browser is :

HTTP Status 404 - /goauth/oauth

type Status report

message /goauth/oauth

description The requested resource (/goauth/oauth) is not available.
Apache Tomcat/6.0.20


问:
In Python - Trying to aggregate a row and create a pivot table
```<code>pd.pivot_table(df,index=['Custodian'])

del df['Name']
del df['Model 2']

print(df)
</code>```

Shows this:

```<code>                            Model  Current Value
Custodian
Heldaway                 529 Plan        3791.94
Heldaway                 529 Plan       11364.87
Heldaway                 529 Plan       22422.58
Heldaway                 529 Plan       33859.74
Heldaway   Core Aggressive Growth      667703.89
                          ...            ...
US Bank           High Yield Cash           0.00
US Bank           High Yield Cash       60056.55
US Bank           High Yield Cash       18023.68
US Bank           High Yield Cash           0.00
US Bank           High Yield Cash      142132.76

[5286 rows x 2 columns]
</code>```

I would like to make it so it custodian type shows once then all the models under that custodian. Then I would like to know how to make it so the model column is sorted by a specific order according to the string.

答:
You probably mean:

df=df.reset_index().groupby(["Model", "Custodian"], as_index=False)["Current Value"].sum()
```

Body:
pd.pivot_table(df,index=['Custodian'])

del df['Name']
del df['Model 2']

print(df)

Shows this:

                            Model  Current Value
Custodian
Heldaway                 529 Plan        3791.94
Heldaway                 529 Plan       11364.87
Heldaway                 529 Plan       22422.58
Heldaway                 529 Plan       33859.74
Heldaway   Core Aggressive Growth      667703.89
                          ...            ...
US Bank           High Yield Cash           0.00
US Bank           High Yield Cash       60056.55
US Bank           High Yield Cash       18023.68
US Bank           High Yield Cash           0.00
US Bank           High Yield Cash      142132.76

[5286 rows x 2 columns]

I would like to make it so it custodian type shows once then all the models under that custodian. Then I would like to know how to make it so the model column is sorted by a specific order according to the string.


问:
LinkedIn share returns cached URL when sending to a specific person Issue
Lately i've been working on a share button which should take some specific information on the website and post it on LinkedIn. The website is an single-page application with Angular ui-router.

I followed LinkedIns developer guide docs with the customized URL to execute this action. My link looks like this:

https://www.linkedin.com/shareArticle?mini=true&summary= Description
  &title= Title &url= Url &picture= Image.

Description, Title, Url and Image are unique values which is set by the content of the page and i've set the Open Graph meta tags:

meta property="og:title" content="website title"

  meta property="og:description"
  content="website description"

  meta property="og:url" content="website url"

meta property="og:image" content="website image"

Since the page is an single-page application, the page "never" really reloads, but just changes the content inside the body element. Therefore i've created some Javascript to do the job for me which works like a charm with LinkedIn sharing to your network but "sending to a specific person" is inserting the wrong url.

When the user enter our website, locate to an article they want to share and click on the LinkedIn icon in the top right corner, a new tab appears. In the new tab, the user sees the title of the page, some of the url link and some of the description. They can check whether to share an update or / and send to a specific person. If the user checks to share an update with their network, the correct information is set with title, description, image and url. But when the user wants to send it to a specific person, which the user is notified about in their messages, the title and description is correct, but the link is not.

This issue seems to be connected to some sort of caching. If the user visit a new page, where no one has shared any article or so on linkedIn via the website, the correct link for both the network and the person, who is recieving the message. Let's say it is website.com/#3/5521. But when another user wants to share a different article on the page, the message url link is set to the first one, that the other user earlier shared. The link should have been website.com/#3/9978 but is set to website.com/#3/5521 no matter what i do. It's the same link that sharing with your network gets as when sharing to a specific person, so i can't see, how i can deal with this problem properly.

I hope this gives an idea of what the issue is. Tell me if you guys need any more explaining.

The problem appears on this website, if you want to see it in live action:
http://gentofte.viewer.dkplan.niras.dk/plan/52#/23703

Thanks in advance.

答:
I'm not experiencing this problem at all.  Is it still broken?

Here I am trying to share this URL: http://www.revoltlib.com/?id=17.  I am using this URL...

```<code>https://www.linkedin.com/sharing/share-offsite/?url=http%3A%2F%2Fwww.revoltlib.com%2F%3Fid%3D17
</code>```

This is the screen on sharing...

And this is the result after sharing...

It appears to work!  Is it still broken for you?

Body:
I'm not experiencing this problem at all.  Is it still broken?

Here I am trying to share this URL: http://www.revoltlib.com/?id=17.  I am using this URL...

https://www.linkedin.com/sharing/share-offsite/?url=http%3A%2F%2Fwww.revoltlib.com%2F%3Fid%3D17

This is the screen on sharing...

And this is the result after sharing...

It appears to work!  Is it still broken for you?


问:
Kubernetes dashboard issue
Unable to access the Kubernetes dashboard.
Executed below steps:

kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta4/aio/deploy/recommended.yaml

kubectl proxy --address="192.168.56.12" -p 8001 --accept-hosts='^*$'

Now trying to access from url:
http://192.168.56.12:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/

```<code>{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {

  },
  "status": "Failure",
  "message": "no endpoints available for service \"https:kubernetes-dashboard:\"",
  "reason": "ServiceUnavailable",
  "code": 503
}```

Output of a few commands that will required:

```

<p>[root@k8s-master ~]# kubectl logs kubernetes-dashboard-6bb65fcc49-zn2c2 --namespace=kubernetes-dashboard</p>

<p>Error from server: Get https://192.168.56.14:10250/containerLogs/kubernetes-dashboard/kubernetes-dashboard-6bb65fcc49-7wz6q/kubernetes-dashboard: dial tcp 192.168.56.14:10250: connect: no route to host
[root@k8s-master ~]#</p>

```$kubectl get pods -o wide --all-namespaces
NAMESPACE              NAME                                        READY   STATUS             RESTARTS   AGE   IP              NODE
ATES
kube-system            coredns-5c98db65d4-89c9p                    1/1     Running            0          76m   10.244.0.14     k8s-master
kube-system            coredns-5c98db65d4-ggqfj                    1/1     Running            0          76m   10.244.0.13     k8s-master
kube-system            etcd-k8s-master                             1/1     Running            0          75m   192.168.56.12   k8s-master
kube-system            kube-apiserver-k8s-master                   1/1     Running            0          75m   192.168.56.12   k8s-master
kube-system            kube-controller-manager-k8s-master          1/1     Running            1          75m   192.168.56.12   k8s-master
kube-system            kube-flannel-ds-amd64-74zrn                 1/1     Running            1          74m   192.168.56.14   node1
kube-system            kube-flannel-ds-amd64-hgcp8                 1/1     Running            0          75m   192.168.56.12   k8s-master
kube-system            kube-proxy-2lczb                            1/1     Running            0          74m   192.168.56.14   node1
kube-system            kube-proxy-8dxdm                            1/1     Running            0          76m   192.168.56.12   k8s-master
kube-system            kube-scheduler-k8s-master                   1/1     Running            1          75m   192.168.56.12   k8s-master
kubernetes-dashboard   dashboard-metrics-scraper-fb986f88d-d49sw   1/1     Running            0          71m   10.244.1.21     node1
kubernetes-dashboard   kubernetes-dashboard-6bb65fcc49-7wz6q       0/1     CrashLoopBackOff   18         71m   10.244.1.20     node1

=========================================

[root@k8s-master ~]# kubectl describe pod kubernetes-dashboard-6bb65fcc49-7wz6q -n kubernetes-dashboard
Name:           kubernetes-dashboard-6bb65fcc49-7wz6q
Namespace:      kubernetes-dashboard
Priority:       0
Node:           node1/192.168.56.14
Start Time:     Mon, 23 Sep 2019 12:56:18 +0530
Labels:         k8s-app=kubernetes-dashboard
                pod-template-hash=6bb65fcc49
Annotations:    <none>
Status:         Running
IP:             10.244.1.20
Controlled By:  ReplicaSet/kubernetes-dashboard-6bb65fcc49
Containers:
  kubernetes-dashboard:
    Container ID:  docker://2cbbbc9b95a43a5242abe13f8178dc589487abcfccaea06ff4be70781f4c3711
    Image:         kubernetesui/dashboard:v2.0.0-beta4
    Image ID:      docker-pullable://docker.io/kubernetesui/dashboard@sha256:a35498beec44376efcf8c4478eebceb57ec3ba39a6579222358a1ebe455ec49e
    Port:          8443/TCP
    Host Port:     0/TCP
    Args:
      --auto-generate-certificates
      --namespace=kubernetes-dashboard
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    2
      Started:      Mon, 23 Sep 2019 14:10:27 +0530
      Finished:     Mon, 23 Sep 2019 14:10:28 +0530
    Ready:          False
    Restart Count:  19
    Liveness:       http-get https://:8443/ delay=30s timeout=30s period=10s #success=1 #failure=3
    Environment:    <none>
    Mounts:
      /certs from kubernetes-dashboard-certs (rw)
      /tmp from tmp-volume (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from kubernetes-dashboard-token-q7j4z (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  kubernetes-dashboard-certs:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  kubernetes-dashboard-certs
    Optional:    false
  tmp-volume:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  kubernetes-dashboard-token-q7j4z:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  kubernetes-dashboard-token-q7j4z
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node-role.kubernetes.io/master:NoSchedule
                 node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason   Age                        From            Message
  ----     ------   ----                       ----            -------
  Warning  BackOff  <invalid> (x354 over 63m)  kubelet, node1  Back-off restarting failed container
[root@k8s-master ~]#

```

答:
After realizing that the chart stable/kubernetes-dashboard is outdated, I found that you need to apply this manifest  :

kubectl apply -f \
   https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta4/aio/deploy/recommended.yaml
```
<p>However, this is not acceptable to migrate from helm chart to hard coded manifests..
After some search, the related chart is now under this Git repo subfolder
No more <code>stable</code> repo, but use the following:</p>
<pre class="lang-sh prettyprint-override"><code>helm repository add kubernetes-dashboard https://kubernetes.github.io/dashboard/
helm install kubernetes-dashboard/kubernetes-dashboard --name my-release
</code>```

Good luck! This will fix all your issues since this chart considers all dependencies.

By the way:

even the image repository is no more k8s.gcr.io/kubernetes-dashboard-amd64
Instead, it is now under dockerhub kubernetesui/dashboard

There is a sidecar for metrics scraper which not defined in the  stable chart.

Title: Kubernetes dashboard issue

Body:
Unable to access the Kubernetes dashboard.
Executed below steps:

kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta4/aio/deploy/recommended.yaml

kubectl proxy --address="192.168.56.12" -p 8001 --accept-hosts='^*$'

Now trying to access from url:
http://192.168.56.12:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/

{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {

  },
  "status": "Failure",
  "message": "no endpoints available for service \"https:kubernetes-dashboard:\"",
  "reason": "ServiceUnavailable",
  "code": 503
}```

Output of a few commands that will required:

[root@k8s-master ~]# kubectl logs kubernetes-dashboard-6bb65fcc49-zn2c2 --namespace=kubernetes-dashboard

Error from server: Get https://192.168.56.14:10250/containerLogs/kubernetes-dashboard/kubernetes-dashboard-6bb65fcc49-7wz6q/kubernetes-dashboard: dial tcp 192.168.56.14:10250: connect: no route to host
[root@k8s-master ~]#

$kubectl get pods -o wide --all-namespaces
NAMESPACE              NAME                                        READY   STATUS             RESTARTS   AGE   IP              NODE
ATES
kube-system            coredns-5c98db65d4-89c9p                    1/1     Running            0          76m   10.244.0.14     k8s-master
kube-system            coredns-5c98db65d4-ggqfj                    1/1     Running            0          76m   10.244.0.13     k8s-master
kube-system            etcd-k8s-master                             1/1     Running            0          75m   192.168.56.12   k8s-master
kube-system            kube-apiserver-k8s-master                   1/1     Running            0          75m   192.168.56.12   k8s-master
kube-system            kube-controller-manager-k8s-master          1/1     Running            1          75m   192.168.56.12   k8s-master
kube-system            kube-flannel-ds-amd64-74zrn                 1/1     Running            1          74m   192.168.56.14   node1
kube-system            kube-flannel-ds-amd64-hgcp8                 1/1     Running            0          75m   192.168.56.12   k8s-master
kube-system            kube-proxy-2lczb                            1/1     Running            0          74m   192.168.56.14   node1
kube-system            kube-proxy-8dxdm                            1/1     Running            0          76m   192.168.56.12   k8s-master
kube-system            kube-scheduler-k8s-master                   1/1     Running            1          75m   192.168.56.12   k8s-master
kubernetes-dashboard   dashboard-metrics-scraper-fb986f88d-d49sw   1/1     Running            0          71m   10.244.1.21     node1
kubernetes-dashboard   kubernetes-dashboard-6bb65fcc49-7wz6q       0/1     CrashLoopBackOff   18         71m   10.244.1.20     node1

=========================================

[root@k8s-master ~]# kubectl describe pod kubernetes-dashboard-6bb65fcc49-7wz6q -n kubernetes-dashboard
Name:           kubernetes-dashboard-6bb65fcc49-7wz6q
Namespace:      kubernetes-dashboard
Priority:       0
Node:           node1/192.168.56.14
Start Time:     Mon, 23 Sep 2019 12:56:18 +0530
Labels:         k8s-app=kubernetes-dashboard
                pod-template-hash=6bb65fcc49
Annotations:    <none>
Status:         Running
IP:             10.244.1.20
Controlled By:  ReplicaSet/kubernetes-dashboard-6bb65fcc49
Containers:
  kubernetes-dashboard:
    Container ID:  docker://2cbbbc9b95a43a5242abe13f8178dc589487abcfccaea06ff4be70781f4c3711
    Image:         kubernetesui/dashboard:v2.0.0-beta4
    Image ID:      docker-pullable://docker.io/kubernetesui/dashboard@sha256:a35498beec44376efcf8c4478eebceb57ec3ba39a6579222358a1ebe455ec49e
    Port:          8443/TCP
    Host Port:     0/TCP
    Args:
      --auto-generate-certificates
      --namespace=kubernetes-dashboard
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    2
      Started:      Mon, 23 Sep 2019 14:10:27 +0530
      Finished:     Mon, 23 Sep 2019 14:10:28 +0530
    Ready:          False
    Restart Count:  19
    Liveness:       http-get https://:8443/ delay=30s timeout=30s period=10s #success=1 #failure=3
    Environment:    <none>
    Mounts:
      /certs from kubernetes-dashboard-certs (rw)
      /tmp from tmp-volume (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from kubernetes-dashboard-token-q7j4z (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  kubernetes-dashboard-certs:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  kubernetes-dashboard-certs
    Optional:    false
  tmp-volume:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  kubernetes-dashboard-token-q7j4z:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  kubernetes-dashboard-token-q7j4z
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node-role.kubernetes.io/master:NoSchedule
                 node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason   Age                        From            Message
  ----     ------   ----                       ----            -------
  Warning  BackOff  <invalid> (x354 over 63m)  kubelet, node1  Back-off restarting failed container
[root@k8s-master ~]#

Body:
After realizing that the chart stable/kubernetes-dashboard is outdated, I found that you need to apply this manifest  :

kubectl apply -f \
   https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta4/aio/deploy/recommended.yaml

However, this is not acceptable to migrate from helm chart to hard coded manifests..
After some search, the related chart is now under this Git repo subfolder
No more stable repo, but use the following:

helm repository add kubernetes-dashboard https://kubernetes.github.io/dashboard/
helm install kubernetes-dashboard/kubernetes-dashboard --name my-release

Good luck! This will fix all your issues since this chart considers all dependencies.

By the way:

even the image repository is no more k8s.gcr.io/kubernetes-dashboard-amd64
Instead, it is now under dockerhub kubernetesui/dashboard

There is a sidecar for metrics scraper which not defined in the  stable chart.